Search completed in 3.63 seconds.
Signaling and video calling - Web APIs
a connection is established through a discovery and negotiation process
called signaling.
... this tutorial will guide you through building a two-way video-
call.
...this process is
called signaling and involves both devices connecting to a third, mutually agreed-upon server.
...And 90 more matches
Rendering and the WebXR frame animation callback - Web APIs
once that's in hand, you request that the browser
call your rendering function the next time it needs a framebuffer to render your scene.
... this is done by
calling the xrsession method requestanimationframe().
...space( 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 xrreferencespace method getoffsetreferencespace().
...And 31 more matches
JS_SetGCCallback
specify a new
callback function for the garbage collector.
... syntax void js_setgc
callback(jsruntime *rt, jsgc
callback cb, void *data); jsgc
callback js_setgc
callback(jscontext *cx, jsgc
callback cb); // obsolete since jsapi 13 jsgc
callback js_setgc
callbackrt(jsruntime *rt, jsgc
callback cb); // obsolete since jsapi 13 name type description cx jscontext * (for the old js_setgc
callback) any jscontext.
... the gc
callback of the associated jsruntime is set.
...And 27 more matches
xptcall FAQ
what is xpt
call?
... xpt
call is a small low level xpcom method
call library.
...it is used to facilitate cross language and cross thread method
calls.
...And 24 more matches
JS_SetOperationCallback
this article covers features introduced in spidermonkey 1.8.5 set a
callback function that is automati
cally
called periodi
cally while javascript code runs.
... these methods/types are renamed to js_setinterrupt
callback, js_getinterrupt
callback, js_requestinterrupt
callback and jsinterrupt
callback in spidermonkey 30.
... syntax void js_setoperation
callback(jscontext *cx, jsoperation
callback
callback); jsoperation
callback js_getoperation
callback(jscontext *cx); void js_triggeroperation
callback(jsruntime *rt); name type description cx jscontext * a context.
...And 22 more matches
JS::CallArgs
this article covers features introduced in spidermonkey 17 helper class encapsulating access to the
callee, this value, arguments, and argument count for a function
call.
... syntax js::
callargs js::
callargsfromvp(unsigned argc, js::value *vp); name type description args unsigned number of argument.
...(3nd argument of jsnative) methods methods of js::
callargs method description bool requireatleast(jscontext *cx, const char *fnname, unsigned required) returns true if there are at least required arguments passed in.
...And 20 more matches
JS_SetBranchCallback
specifies a
callback function that is automati
cally
called when a script branches backward during execution, when a function returns, and at the end of the script.
... replaced with js_setoperation
callback.
... syntax jsbranch
callback js_setbranch
callback(jscontext *cx, jsbranch
callback cb); name type description cx jscontext * the context to hook.
...And 18 more matches
Declaring and Using Callbacks
c functions occasionally take function pointers as arguments, which are generally used as
callbacks.
... in these cases, js-ctypes allows you to pass a regular javascript function as the
callback.
... this is very powerful, since it allows native code to transparently
call into javascript.
...And 18 more matches
Call Tree - Firefox Developer Tools
the
call tree tells you which javascript functions the browser spent the most time in.
... the
call tree is a sampling profiler.
... it periodi
cally samples the state of the javascript engine and records the stack for the code executing at the time.
...And 16 more matches
JS_SetContextCallback
specifies a
callback function that is automati
cally
called whenever a jscontext is created or destroyed.
... syntax void js_setcontext
callback(jsruntime *rt, jscontext
callback cx
callback, void *data); name type description rt jsruntime * pointer to a js runtime.
... cx
callback jscontext
callback pointer to the
callback function, described below.
...And 15 more matches
JS_SetInterruptCallback
this article covers features introduced in spidermonkey 31 set a
callback function that is automati
cally
called periodi
cally while javascript code runs.
... syntax jsinterrupt
callback js_setinterrupt
callback(jsruntime *rt, jsinterrupt
callback
callback); jsinterrupt
callback js_getinterrupt
callback(jsruntime *rt); void js_requestinterrupt
callback(jsruntime *rt); name type description rt jsruntime * the runtime.
...
callback jsinterrupt
callback the
callback function to install.
...And 15 more matches
JS_AddFinalizeCallback
this article covers features introduced in spidermonkey 17 add/remove
callback function for finalization.
... syntax bool js_addfinalize
callback(jsruntime *rt, jsfinalize
callback cb, void *data); // added in spidermonkey 38 (jsapi 32) void js_removefinalize
callback(jsruntime *rt, jsfinalize
callback cb); // added in spidermonkey 38 (jsapi 32) void js_setfinalize
callback(jsruntime *rt, jsfinalize
callback cb); // obsolete since jsapi 32 name type description rt jsruntime * the jsruntime for which to set the finalization
callback.
... cb jsfinalize
callback pointer to the new
callback function to use.
...And 14 more matches
Xptcall Porting Guide
overview xpt
call is a library that supports both invoking methods on arbitrary xpcom objects and implementing classes whose objects can impersonate any xpcom interface.
...this code needs to be ported to all platforms that want to support xpt
call (and thus mozilla).
... the tree mozilla/xpcom/reflect/xpt
call +--public // exported headers +--src // core source | \--md // platform specific parts | +--mac // mac ppc | +--unix // all unix | \--win32 // win32 | +--test // simple tests to get started \--tests // full tests via api porters are free to create subdirectories under the base md directory for their given platforms and to integrate into the build system as appropriate for their platform.
...And 14 more matches
arguments.callee - JavaScript
the arguments.
callee property contains the currently executing function.
... description
callee is a property of the arguments object.
...this is useful when the name of the function is unknown, such as within a function expression with no name (also
called "anonymous functions").
...And 14 more matches
Creating JavaScript callbacks in components
callback patterns in idl xpcom components use idl to create interfaces.
...basi
cally, the component defines an observer (or listener) interface which is implemented by some external code and this implementation is passed to the component.
... the component can then
call methods on the observer interface to signal the external code when predefined events occur.
...And 12 more matches
JS_CallFunction
calls a specified js function.
... syntax /* added in spidermonkey 31 */ bool js_
callfunction(jscontext *cx, js::handleobject obj, js::handlefunction fun, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js_
callfunctionname(jscontext *cx, js::handleobject obj, const char *name, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js_
callfunctionvalue(jscontext *cx, js::handleobject obj, js::handlevalue fval, const js::handlevaluearray& args, js::mutablehandlevalue rval); /* obsolete since jsapi 30 */ bool js_
callfunction(jscontext *cx, jsobject *obj, jsfunction *fun, unsigned argc, jsval *argv, jsval *rval); bool js_
callfunctionname(jscontext *cx, jsobject *obj, const char *name, unsigned argc, ...
... jsval *argv, jsval *rval); bool js_
callfunctionvalue(jscontext *cx, jsobject *obj, jsval fval, unsigned argc, jsval *argv, jsval *rval); name type description cx jscontext * pointer to a js context from which to derive runtime information.
...And 12 more matches
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
a
call stack is a mechanism for an interpreter (like the javascript interpreter in a web browser) to keep track of its place in a script that
calls multiple functions — what function is currently being run and what functions are
called from within that function, etc.
... when a script
calls a function, the interpreter adds it to the
call stack and then starts carrying out the function.
... any functions that are
called by that function are added to the
call stack further up, and run where their
calls are reached.
...And 11 more matches
JS_SetFunctionCallback
sets a
callback to be run whenever a javascript function is invoked or exited.
... note: this method is only available if moz_trace_js
calls was defined at compile time using --enable-trace-js
calls.
... syntax void js_setfunction
callback(jscontext *cx, jsfunction
callback fcb); name type description cx jscontext * pointer to a js context from which to derive runtime information.
...And 10 more matches
Function.prototype.call() - JavaScript
the
call() method
calls a function with a given this value and arguments provided individually.
... syntax func.
call([thisarg[, arg1, arg2, ...argn]]) parameters thisarg optional the value to use as this when
calling func.
... return value the result of
calling the function with the specified this value and arguments.
...And 10 more matches
NPN_PluginThreadAsyncCall - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary thread safe way to request that the browser
calls a plug-in function on the browser or plugin thread (the thread on which the plug-in was initiated).
... syntax #include <npapi.h> void npn_pluginthreadasync
call(npp plugin, void (*func)(void *), void *userdata); parameters the function has the following parameters: plugin pointer to the current plug-in instance.
... func pointer to the function to
call on the correct thread.
...And 8 more matches
Function.caller - JavaScript
the function.
caller property returns the function that invoked the specified function.
... it returns null for strict, async function and generator function
callers.
... description if the function f was invoked by the top level code, the value of f.
caller is null, otherwise it's the function that
called f.
...And 7 more matches
JS::Call
this article covers features introduced in spidermonkey 17
call a specified js function.
... syntax bool js::
call(jscontext *cx, js::handleobject thisobj, js::handlefunction fun, const js::handlevaluearray &args, js::mutablehandlevalue rval); bool js::
call(jscontext *cx, js::handleobject thisobj, const char *name, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js::
call(jscontext *cx, js::handleobject thisobj, js::handlevalue fun, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js::
call(jscontext *cx, js::handlevalue thisv, js::handlevalue fun, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js::
call(jscontext *cx, js::handlevalue thisv, js::handleobject funobj, const js::handlevaluearray& args, js::mutablehandlevalue rval); name type description ...
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...And 6 more matches
JS::SetOutOfMemoryCallback
this article covers features introduced in spidermonkey 31 specify a new
callback function for out of memory error.
... syntax void js::setoutofmemory
callback(jsruntime *rt, js::outofmemory
callback cb, void *data); name type description rt jsruntime * the jsruntime for which to set the gc
callback.
... cb js::outofmemory
callback pointer to the new
callback function to use.
...And 6 more matches
JS_SetCompartmentNameCallback
this article covers features introduced in spidermonkey 17 set
callback function to name each compartment.
... syntax void js_setcompartmentname
callback(jsruntime *rt, jscompartmentname
callback
callback); name type description cx jsruntime * the runtime to set the
callback function.
...
callback jscompartmentname
callback
callback function which will be
called to name each compartment (see below).
...And 6 more matches
window.requestIdleCallback() - Web APIs
the window.requestidle
callback() method queues a function to be
called during a browser's idle periods.
...functions are generally
called in first-in-first-out order; however,
callbacks which have a timeout specified may be
called out-of-order if necessary in order to run them before the timeout elapses.
... you can
call requestidle
callback() within an idle
callback function to schedule another
callback to take place no sooner than the next pass through the event loop.
...And 6 more matches
JS::SetLargeAllocationFailureCallback
this article covers features introduced in spidermonkey 31 specify a new
callback function for large memory allocation failure.
... syntax void js::setlargeallocationfailure
callback(jsruntime *rt, js::largeallocationfailure
callback afc, void *data); name type description rt jsruntime * the jsruntime for which to set the gc
callback.
... cb js::largeallocationfailure
callback pointer to the new
callback function to use.
...And 5 more matches
JS_BindCallable
this article covers features introduced in spidermonkey 17 bind the given
callable to use the given object as this.
... syntax jsobject* js_bind
callable(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.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...And 5 more matches
JS_GetLocaleCallbacks
get and set locale specific string conversion and error message
callbacks.
... syntax jslocale
callbacks * js_getlocale
callbacks(jsruntime *rt); void js_setlocale
callbacks(jsruntime *rt, jslocale
callbacks *
callbacks); name type description cx jscontext * pointer to a js context from which to derive runtime information.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...And 5 more matches
JS_SetCheckObjectAccessCallback
set the runtime-wide check-object-access
callback.
...in spidermonkey 1.8.1 and later, use js_setruntimesecurity
callbacks instead.
... syntax jscheckaccessop js_setcheckobjectaccess
callback( jsruntime *rt, jscheckaccessop acb); name type description rt jsruntime * the runtime to configure.
...And 5 more matches
mozIStorageStatementCallback
the mozistoragestatement
callback interface represents a
callback handler that the storage api
calls with result, error, and completion notifications while handling asynchronous database queries.
... storage/public/mozistoragestatement
callback.idlscriptable please add a summary to this article.
... methods handlecompletion()
called when a statement finishes executing.
...And 5 more matches
JSClass.call
the jsclass.
call and jsclass.construct hooks are
called when a custom object is used like a function.
... note that when a custom object is
called, a this argument is calculated for it just as if it were a function.
... that is, the obj argument received by the jsnative is the this argument, not the custom object that was
called!
...And 4 more matches
JS_GetSecurityCallbacks
syntax /* added in spidermonkey 17 */ void js_setsecurity
callbacks(jsruntime *rt, const jssecurity
callbacks *
callbacks); const jssecurity
callbacks * js_getsecurity
callbacks(jsruntime *rt); /* obsolete since jsapi 13 */ jssecurity
callbacks * js_setcontextsecurity
callbacks(jscontext *cx, jssecurity
callbacks *
callbacks); jssecurity
callbacks * js_getruntimesecurity
callbacks(jsruntime *rt); jssecurity
callbacks * js_setruntimesecurity
callbacks(jsruntime *rt, jssecurity
callbacks *
callbacks); name type description rt jsruntime * a runtime to get/set the security
callbacks.
...
callbacks const jssecurity
callbacks * a pointer to the new
callbacks for the runtime.
...
callback structure struct jssecurity
callbacks { jscspevalchecker contentsecuritypolicyallows; // added in spidermonkey 1.8.5 jssubsumesop subsumes; // added in spidermonkey 31 jscheckaccessop checkobjectaccess; // obsolete since jsapi 29 jsprincipalstranscoder principalstranscoder; // obsolete since jsapi 13 jsobjectprincipalsfinder findobjectprincipals; // obsolete since jsapi 13 }; name type description contentsecuritypolicyallows jscspevalchecker a pointer to the function which checks if a csp instance wants to disable eval() and friends.
...And 4 more matches
JS_SetDestroyCompartmentCallback
this article covers features introduced in spidermonkey 17 set the
callback function for each compartment being destroyed.
... syntax void js_setdestroycompartment
callback(jsruntime *rt, jsdestroycompartment
callback
callback); name type description cx jsruntime * the runtime to set the
callback function.
...
callback jsdestroycompartment
callback
callback function which will be
called for each compartment being destroyed (see below).
...And 4 more matches
Making cross-thread calls using runnables
typi
cally, thread activities are triggered and managed using an xpcom event-passing framework that uses the nsirunnable interface.
...so we declare an asynchronous version of the same function: typedef void (*pi
callback)(const nscstring& result); //
callback function void calculatepiasynchronously(int digits, pi
callback
callback); creating a runnable nsrunnable is a helper class: it already implements threadsafe refcounting, so all you need to do is override the run() function.
...#include "nsthreadutils.h" class piresulttask : public nsrunnable { public: piresulttask(pi
callback
callback, const nsacstring& result) : m
callback(
callback) , mresult(result) , mworkerthread(do_getcurrentthread()) { moz_assert(!ns_ismainthread()); // this should be running on the worker thread } ns_imethod run() { moz_assert(ns_ismainthread()); // this method is supposed to run on the main thread!
...And 4 more matches
Xptcall Porting Status
this is a status page for the multiplatform porting of xpt
call.
... xpt
call has a faq and a porting guide.
...feel free to email me with questions or to volunteer to contribute xpt
call code for any platform.
...And 4 more matches
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
tutorial: show allocations per
call path this page shows how to use the debugger api to show how many objects a web page allocates, sorted by the function
call path that allocated them.
...note that stack entries are '===' if // they represent the same site with the same
callers.
...this stops logging allocations, and displays a tree of allocations: an allocation plot, displayed in the console the numbers at the left edge of each line show the total number of objects allocated at that site or at sites
called from there.
...And 4 more matches
Testing media queries programmatically - CSS: Cascading Style Sheets
the dom provides features that can test the results of a media query programmati
cally, via the mediaquerylist interface and its methods and properties.
...to do this,
call the addlistener() method on the mediaquerylist object, with a
callback function to invoke when the media query status changes (e.g., the media query test goes from true to false): // create the query list.
... const mediaquerylist = window.matchmedia("(orientation: portrait)"); // define a
callback function for the event listener.
...And 4 more matches
NPAnyCallbackStruct - Archive of obsolete content
syntax typedef struct { int32 type; } npany
callbackstruct; fields the data structure has the following field: type always contains np_print.
... description
callback structures are used to pass platform-specific information.
... the npany
callbackstruct structure contains information required by the platformprint field of the npembedprint structure during embedded mode printing.
...And 3 more matches
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
the debug.mstraceasync
callbackstarting function associates the
callback stack with a previously specified asynchronous operation.
... syntax debug.mstraceasync
callbackstarting(asyncoperationid) parameters asyncoperationid the id associated with the asynchronous operation.
... remarks
call this function in the
callback function for the asynchronous operation after the
call to debug.mstraceasyncoperationcompleted.
...And 3 more matches
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
the debug.mstraceasync
callbackcompleted function indicates that an asynchronous operation has completed.
... syntax debug.mstraceasync
callbackcompleted() parameters asyncoperationid the id associated with the asynchronous operation.
... remarks
call this function when the asynchronous operation completes.
...And 3 more matches
JS_GetFunctionCallback
returns the
callback currently configured to be
called when javascript functions are invoked or exited, as established by a prior
call to js_setfunction
callback.
... note: this method is only available if moz_trace_js
calls was defined at compile time using --enable-trace-js
calls.
... syntax jsfunction
callback js_getfunction
callback(jscontext *cx); name type description cx jscontext * pointer to a js context from which to derive runtime information.
...And 3 more matches
nsIContentPrefCallback2
dom/interfaces/base/nsicontentprefservice2.idlscriptable
callback used by nsicontentprefservice2 methods 1.0 66 introduced gecko 20.0 inherits from: nsisupports last changed in gecko 20.0 (firefox 20.0 / thunderbird 20.0 / seamonkey 2.17) method overview void handlecompletion(in unsigned short reason); void handleerror(in nsresult error); void handleresult(in nsicontentpref pref); constants constant value description complete_ok 0 complete_error 1 methods handlecompletion()
called when the method finishes.
... this will be
called exactly once for each method invocation, and afterward no other
callback methods will be
called.
... handleerror()
called when an error occurs.
...And 3 more matches
TypeError: X.prototype.y called on incompatible type - JavaScript
the javascript exception "
called on incompatible target (or object)" occurs when a function (on a given object), is
called with a this not corresponding to the type expected by the function.
... message typeerror: 'this' is not a set object (edge) typeerror: function.prototype.tostring
called on incompatible object (firefox) typeerror: function.prototype.bind
called on incompatible target (firefox) typeerror: method set.prototype.add
called on incompatible receiver undefined (chrome) typeerror: bind must be
called on a function (chrome) error type typeerror what went wrong?
... when this error is thrown, a function (on a given object), is
called with a this not corresponding to the type expected by the function.
...And 3 more matches
ReferenceError: deprecated caller or arguments usage - JavaScript
the javascript strict mode-only exception "deprecated
caller or arguments usage" occurs when the deprecated function.
caller or function.arguments properties are used.
... message typeerror: 'arguments', '
callee' and '
caller' are restricted function properties and cannot be accessed in this context (edge) warning: referenceerror: deprecated
caller usage (firefox) warning: referenceerror: deprecated arguments usage (firefox) typeerror: '
callee' and '
caller' cannot be accessed in strict mode.
... in strict mode, the function.
caller or function.arguments properties are used and shouldn't be.
...And 3 more matches
Dynamically modifying XUL-based user interface - Archive of obsolete content
it explains the concept of dom documents, demonstrates a few simple examples of using dom
calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods.
...if you have ever written a script that interacts with a xul (or html) document, you have already used dom
calls.
...you may also have used other
calls, such as element.setattribute(), or, if you wrote an extension, the addeventlistener() method.
...And 2 more matches
NPPrintCallbackStruct - Archive of obsolete content
syntax typedef struct { int32 type; file* fp; } npprint
callbackstruct; fields the data structure has the following fields: type always contains np_print.
... description
callback structures are used to pass platform-specific information.
... the npprint
callbackstruct structure contains the file pointer to which the plug-in should write its postscript data.
...And 2 more matches
NPSetWindowCallbackStruct - Archive of obsolete content
syntax typedef struct { int32 type; display* display; visual* visual; colormap colormap; unsigned int depth; } npsetwindow
callbackstruct; fields the data structure has the following fields: type always contains np_setwindow.
... description
callback structures are used to pass platform-specific information.
... the npsetwindow
callbackstruct object, allocated by the browser, contains information required for the ws_info field of an npwindow.
...And 2 more matches
Debug.msUpdateAsyncCallbackRelation - Archive of obsolete content
the debug.msupdateasync
callbackrelation function updates the relationship status between a synchronous work item and the associated asynchronous operation.
... syntax debug.msupdateasync
callbackrelation(relatedasyncoperationid, relationtype) parameters relatedasyncoperationid the id associated with the asynchronous operation.
... remarks the synchronous work item is typi
cally the
callback function for the asynchronous operation.
...And 2 more matches
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
a
callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
... here is a quick example: function greeting(name) { alert('hello ' + name); } function processuserinput(
callback) { var name = prompt('please enter your name.');
callback(name); } processuserinput(greeting); the above example is a synchronous
callback, as it is executed immediately.
... note, however, that
callbacks are often used to continue code execution after an asynchronous operation has completed — these are
called asynchronous
callbacks.
...And 2 more matches
JSSecurityCallbacks.contentSecurityPolicyAllows
the jssecurity
callbacks.contentsecuritypolicyallows
callback is
called when a script attempts to access an object property.
... the
callback can deny the script access to the property.
... jscheckaccessop is the type of the
callback.
...And 2 more matches
JS_EnterCrossCompartmentCall
this article covers features introduced in spidermonkey 1.8.1 js_entercrosscompartment
call has been removed in bug 786068.
... syntax jscrosscompartment
call * js_entercrosscompartment
call(jscontext *cx, jsobject *target); name type description cx jscontext * the context on which a cross-compartment
call is needed.
...any access to an object in a different compartment must be bracketed by
calling js_entercrosscompartment
call and js_leavecrosscompartment
call.
...And 2 more matches
JS_LeaveCrossCompartmentCall
this article covers features introduced in spidermonkey 1.8.1 js_leavecrosscompartment
call has been removed in bug 786068.
... leave a the compartment, returning to the compartment active before the corresponding js_entercrosscompartment
call.
... syntax void js_leavecrosscompartment
call(jscrosscompartment
call *
call); name type description
call jscrosscompartment
call * value returned by previous
call to js_entercrosscompartment
call.
...And 2 more matches
nsIAsyncVerifyRedirectCallback
netwerk/base/public/nsiasyncverifyredirect
callback.idlscriptable implement this interface to receive a
callback that lets you know whether an asynchronous redirect was verified or vetoed.
... 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface implements the
callbacks passed to the nsichanneleventsink.asynconchannelredirect() method.
... method overview void onredirectverify
callback(in nsresult result); methods onredirectverify
callback() implements the asynchronous
callback passed to nsichanneleventsink.asynconchannelredirect().
...And 2 more matches
nsIFaviconDataCallback
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 oncomplete(in nsiuri auri, in unsigned long adatalen, [const,array,size_is(adatalen)] in octet adata, in autf8string amimetype); methods oncomplete()
called when the required favicon's information is available.
... it's up to the invoking method to state if the
callback is always invoked, or
called on success only.
...the
caller will receive the most information we can gather on the icon, but it's not guaranteed that all of them will be set.
...And 2 more matches
RTCSessionDescriptionCallback - Web APIs
the rtcsessiondescription
callback type is used to represent the
callback function passed into the deprecated
callback-based version of createoffer() or createanswer() when using them to create offers or answers.
... because this function type is part of the legacy webrtc api, you should avoid using it (and the
callback-based forms of createoffer() and createanswer() that make use of it).
... syntax rtcsessiondescription
callback(description); parameters description an rtcsessiondescriptioninit (or rtcsessiondescription) object describing the session being offered or being accepted.
...And 2 more matches
window.cancelIdleCallback() - Web APIs
summary the window.cancelidle
callback() method cancels a
callback previously scheduled with window.requestidle
callback().
... syntax window.cancelidle
callback(handle); parameters handle the id value returned by window.requestidle
callback() when the
callback was established.
... desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetcancelidle
callback experimentalchrome full support 47edge full support 79firefox full support 55 full support 55 full support 53disabled disabled from version 53: this feature is behind the...
...And 2 more matches
-webkit-touch-callout - CSS: Cascading Style Sheets
the -webkit-touch-
callout css property controls the display of the default
callout shown when you touch and hold a touch target.
... when a target is touched and held on ios, safari displays a
callout information about the link.
... /* keyword values */ -webkit-touch-
callout: default; -webkit-touch-
callout: none; /* global values */ -webkit-touch-
callout: initial; -webkit-touch-
callout: inherit; -webkit-touch-
callout: unset; syntax values default the default
callout is displayed.
...And 2 more matches
arguments.caller - Archive of obsolete content
the obsolete arguments.
caller property used to provide the function that invoked the currently executing function.
... description this property is not available anymore, but you can still use function.
caller.
... function who
called() { if (who
called.
caller == null) console.log('i was
called from the global scope.'); else console.log(who
called.
caller + '
called me!'); } examples the following code was used to check the value of arguments.
caller in a function, but doesn't work anymore.
... function who
called() { if (arguments.
caller == null) console.log('i was
called from the global scope.'); else console.log(arguments.
caller + '
called me!'); } specifications not part of any standard.
Callgraph
the
callgraph project is intended to produce a complete
callgraph covering c and c++ code within mozilla.
...0 : 1; } the
callgraph would be foo() -> good() -> evil().
...the
callgraph project uses gcc and treehydra to generate information about function and method
calls at compile time, and aggregates it into a sqlite database.
... documentation installing
callgraph download and installation of
callgraph schema reference explanation of the database schema further details implementation ideas for
callgraph ...
JS::IsCallable
this article covers features introduced in spidermonkey 38 return whether the given function object is
callable/a valid constructor.
... syntax bool js::is
callable(jsobject *obj); bool js::isconstructor(jsobject *obj); name type description obj jsobject * pointer to the function.
... description js::is
callable returns whether the given function object is
callable.
... see also mxr id search for js::is
callable mxr id search for js::isconstructor js_isconstructor js_isnativefunction bug 1065811 ...
mozIVisitInfoCallback
toolkit/components/places/public/moziasynchistory.idlscriptable this interface provides
callback handling functionality for moziasynchistory.updateplaces() 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) method overview void handleerror(in nsresult aresultcode, in moziplaceinfo aplaceinfo); void handleresult(in moziplaceinfo aplaceinfo); void oncomplete(in nsresult aresultcode, in moziplaceinfo aplaceinfo);obsolete since gecko 8.0 methods handleerror()
called when a moziplaceinfo couldn't be processed.
... handleresult()
called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces().
... if more than one operation is done for a given visit, this method is only
called once (for all changes at once).
... oncomplete() obsolete since gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5)
called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces().
nsIAuthPromptCallback
netwerk/base/public/nsiauthprompt
callback.idlscriptable interface for
callback methods for the asynchronous nsiauthprompt2 method.
... 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3)
callers must
call exactly one method if nsiauthprompt2.asyncpromptauth() returns successfully.
... they must not
call any method on this interface before nsiauthprompt2.asyncpromptauth() returns.
... usercancel if false, this prompt was cancelled by
calling the the cancel method on the nsicancelable; otherwise, it was cancelled by the user.
nsIDOMGeoPositionCallback
the nsidomgeoposition
callback interface is
called when updated position information is available.
... you need to implement this interface to accept
callbacks after using nsidomgeolocation.watchposition().
... dom/interfaces/geolocation/nsidomgeoposition
callback.idlscriptable please add a summary to this article.
... 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.
nsIMemoryMultiReporterCallback
xpcom/base/nsimemoryreporter.idlscriptable implement this interface to handle
callbacks from nsimemorymultireporter instances.
... 1.0 66 introduced gecko 7.0 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) method overview void
callback(in acstring process, in autf8string path, in print32 kind, in print32 units, in print64 amount, in autf8string description, in nsisupports closure); methods
callback()
called to provide information from a multi-reporter.
...void
callback( in acstring process, in autf8string path, in print32 kind, in print32 units, in print64 amount, in autf8string description, in nsisupports closure ); parameters process the value of the process attribute for the memory reporter.
... closure an nsisupports object providing any additional data the
callback might need; you provide this when you
call nsimemorymultireporter.collectreports().
nsITextInputProcessorCallback
dom/interfaces/base/nsitextinputprocessor.idlscriptable a
callback interface for nsitextinputprocessor user 1.0 66 introduced gecko 38 inherits from: nsisupports last changed in gecko 38.0 (firefox 38.0 / thunderbird 38.0 / seamonkey 2.35) nsitextinputprocessor
callback is defined for receiving requests and notifications to ime from gecko.
... example of simple js-ime: var simpleime = { _hasfocus: false, _hasrightstocompose: false, _tip: null, _
callback: function simpleime_
callback(atip, anotification) { try { switch (anotification.type) { case "request-to-commit": atip.commitcomposition(); break; case "request-to-cancel": atip.cancelcomposition(); break; case "notify-focus": this._hasfocus = true; break; case "notify-blur": this._hasfocus = false; break; case "notify-detached": this._hasfocus = false; this._hasrightstocompose = false; break; } return true; ...
... createinstance(components.interfaces.nsitextinputprocessor); } if (!this._tip.begininputtransaction(window, this._
callback)) { return false; } ...
... }, } method overview boolean onnotify(in nsitextinputprocessor atextinputprocessor, in nsitextinputprocessornotification anotification); methods onnotify() this is
called when gecko requests or notifies something to ime.
Automatically Handle Failed Asserts in Debug Builds - Archive of obsolete content
as of 2004-12-8, it is now possible to automati
cally handle failed asserts in debug builds of mozilla for windows.
...the valid values are: 0x5 automati
cally ignore 0x4 automati
cally retry 0x3 automati
cally abort note that you can also force windbgdlg to prompt, by setting a value of 0xfffffffe.
...rtion: no document: 'mdocument != nsnull', file d:/cvs-1.11.4/mozilla/content/xul/content/src/nsxulelement.cpp, line 3173 (note that i have my source tree in d:/cvs-1.11.4/mozilla) if you have a dword in hkcu\software\mozilla.org\windbgdlg\ named "d:/cvs-1.11.5/mozilla/content/xul/content/src/nsxulelement.cpp," (with the comma - matches are whole-word only) and value 0x5, the assert would automati
cally be ignored.
PRCallOnceType
syntax #include <prinit.h> typedef struct pr
calloncetype { printn initialized; print32 inprogress; prstatus status; } pr
calloncetype; fields the structure has these fields: initialized if not zero, the initialization process has been completed.
...
calling threads that observe this status block until inprogress is zero.
... description the client is responsible for initializing the pr
calloncetype structure to all zeros.
PR_CALLBACK
used to define pointers to functions that will be implemented by the client but
called from a (different) shared library.
... syntax #include <prtypes.h>type pr_
callbackimplementation description functions that are implemented in an application (or shared library) that are intended to be
called from another shared library (such as nspr) must be declared with the pr_
callback attribute.
...the pr_
callback attribute is included as part of the function's definition between its return value type and the function's name.
PR_CallOnce
syntax prstatus pr_
callonce( pr
calloncetype *once, pr
calloncefn func); parameters pr_
callonce has these parameters: once a pointer to an object of type pr
calloncetype.
... func a pointer to the function the
calling client has designed to perform the subsystem initialization.
... the function will be
called once, at most, for each subsystem to be initialized.
JS_SetCallReturnValue2
syntax void js_set
callreturnvalue2(jscontext *cx, jsval v); name type description cx jscontext * the context in which the native function is running.
... description
calling js_set
callreturnvalue2 indicates to the runtime that the native will return a value of type reference.
... an example is in js/src/js.c; searching for js_set
callreturnvalue2 should find it.
mozIStorageCompletionCallback
this interface should be implemented to handle
callbacks from asynchronous storage api routines.
... storage/public/mozistoragecompletion
callback.idlscriptable please add a summary to this article.
... last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsisupports method overview void complete(); methods complete()
called when an asynchronous storage routine has completed.
nsIDOMGeoPositionErrorCallback
the nsidomgeopositionerror
callback interface is used to represent an object that receives
callback notifications when geolocation errors occur.
... dom/interfaces/geolocation/nsidomgeopositionerror
callback.idlscriptable please add a summary to this article.
... last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void handleevent(in nsidomgeopositionerror position); methods handleevent()
called to handle a geolocation error.
nsIProtocolProxyCallback
netwerk/base/public/nsiprotocolproxy
callback.idlscriptable this interface serves as a closure for nsiprotocolproxyservice.asyncresolve().
... 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void onproxyavailable(in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus); methods onproxyavailable() this method is
called when proxy info is available or when an error in the proxy resolution occurs.
... astatus the status of the
callback.
nsITimerCallback
xpcom/threads/nsitimer.idlscriptable defines the
callback interface for nsitimer events.
...this version takes a function to
call and a closure to pass to that function.
... void notify( in nsitimer timer ); parameters timer nsitimer the timer which has expired see also nsitimer nsitimer
callbackfunc ...
Navigator.mozIsLocallyAvailable() - Web APIs
the navigator.mozislo
callyavailable() method allows add-ons to determine whether or not a given resource is available.
... syntax navigator.mozislo
callyavailable(uri, ifoffline); parameters uri the uri of the resource whose availability is to be checked, as a string.
... example var available = navigator.mozislo
callyavailable("my-image-file.png", true); if (available) { /* the offline resource is present */ } else { console.log("certain needed resources are not available offline"); } specifications not part of any specifications.
XRFrameRequestCallback - Web APIs
the xrframerequest
callback is a
callback function passed into xrsession.requestanimationframe (part of webxr api) to obtain the current time and the current xrframe.
... syntax function xrframerequest
callback(time, xrframe){ // process xrframe here } xrsession.requestanimationframe(xrframerequest
callback) parameters domhighrestimestamp a timestamp corresponding to the returned xrframe.
... specifications specification status comment webxr device apithe definition of 'xrframerequest
callback' in that specification.
Intl.getCanonicalLocales() - JavaScript
the intl.getcanoni
callocales() method returns an array containing the canonical locale names.
... syntax intl.getcanoni
callocales(locales) parameters locales a list of string values for which to get the canonical locale names.
... examples using getcanoni
callocales intl.getcanoni
callocales('en-us'); // ["en-us"] intl.getcanoni
callocales(['en-us', 'fr']); // ["en-us", "fr"] intl.getcanoni
callocales('en_us'); // rangeerror:'en_us' is not a structurally valid language tag specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.getcanoni
callocales' in that specification.
PR_Calloc
syntax #include <prmem.h> void *pr_
calloc ( pruint32 nelem, pruint32 elsize); parameters nelem the number of elements of size elsize to be allocated.
...
call pr_geterror() to retrieve the error returned by the libc function malloc().
amIInstallCallback
toolkit/mozapps/extensions/amiinstalltrigger.idlscriptable a
callback function that web pages can implement to be notified when triggered installs complete.
... 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 oninstallended(in astring aurl, in print32 astatus); methods oninstallended()
called when an install completes or fails.
nsIInputStreamCallback
inherits from: nsisupports last changed in gecko 1.7 method overview void oninputstreamready(in nsiasyncinputstream astream); methods oninputstreamready()
called to indicate that the stream is either readable or closed.
... void oninputstreamready( in nsiasyncinputstream astream ); parameters astream the stream whose nsiasyncinputstream.asyncwait() method was
called.
nsIOutputStreamCallback
inherits from: nsisupports last changed in gecko 1.7 method overview void onoutputstreamready(in nsiasyncoutputstream astream); methods onoutputstreamready()
called to indicate that the stream is either writable or closed.
... void onoutputstreamready( in nsiasyncoutputstream astream ); parameters astream the stream whose nsiasyncoutputstream.asyncwait() method was
called.
<xsl:call-template> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:
call-template> element invokes a named template.
... syntax <xsl:
call-template name=name> <xsl:with-param> [optional] </xsl:
call-template> required attribute name specifies the name of the template you wish to invoke.
PRCallOnceFN
syntax #include <prinit.h> typedef prstatus (pr_
callback *pr
calloncefn)(void); description the function is
called to perform the initialization desired.
mozIRepresentativeColorCallback
toolkit/components/places/mozicoloranalyzer.idlscriptable provides
callback methods for mozicoloranalyzer 1.0 66 introduced gecko 17.0 inherits from: nsisupports last changed in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) method overview void oncomplete(in boolean success, [optional] in unsigned long color); methods oncomplete() will be
called when color analysis finishes.
mozIVisitStatusCallback
toolkit/components/places/moziasynchistory.idlscriptable this interface provides
callback handling functionality for moziasynchistory.isurivisited 1.0 66 introduced gecko 11.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) method overview void isvisited(in nsiuri auri, in boolean avisitedstatus); methods isvisited()
called when the moziasynchistory.isurivisited() method's check to determine whether a given uri has been visited has completed.
Index - Web APIs
23 abstractworker.onerror api, abstractworker, eventhandler, property, reference, web workers, workers, onerror the abstractworker.onerror property of the abstractworker interface represents an eventhandler, that is a function to be
called when the error event occurs and bubbles through the worker.
... 29 addresserrors api, address, addresserrors, dictionary, errors, interface, payment address, payment request, payment request api, reference, payment, paymentaddress the addresserrors dictionary is used by the payment request api to to report validation errors in a physical address (typi
cally a billing address or a shipping address).
... 59 analysernode.maxdecibels api, analysernode, property, reference, web audio api, maxdecibels the maxdecibels property of the analysernode interface is a double value representing the maximum power value in the scaling range for the fft analysis data, for conversion to unsigned byte/float values — basi
cally, this specifies the maximum value for the range of results when using getfloatfrequencydata() or getbytefrequencydata().
...And 398 more matches
Index
8 generating guids add-ons, developing mozilla, developing_mozilla:tools, extensions, tools, xpcom guids are used in mozilla programming for identifying several types of entities, including xpcom interfaces (this type of guids is
callled iid), components (cid), and legacy add-ons—like extensions and themes—that were created prior to firefox 1.5.
...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.
...that means you can
call javascript methods from c++ and vice versa.
...And 211 more matches
sslfnc.html
ssl initialization functions ssl export policy functions ssl configuration functions ssl communication functions ssl functions used by
callbacks ssl handshake functions nss shutdown function deprecated functions ssl initialization functions this section describes the initialization functions that are specific to ssl.
... note that at least one of the functions listed in ssl export policy functions must also be
called during nss initialization.
...nss_init isnot idempotent, so
call it only once.
...And 154 more matches
Index
the most typical operations that are relevant for fast program execution are property accesses and function
calls.
...the most commonplace operations that are relevant for fast program execution are property accesses and function
calls.
...if so, int_fits_in_jsval returns true, and i can be cast to jsval by
calling int_to_jsval(i).
...And 137 more matches
Bytecode Descriptions
bytecode listing this document is automati
cally generated from opcodes.h by make_opcode_doc.py.
...it just
calls tonumber(val).
... the conversion can
call .tostring()/.valueof() methods and can throw.
...And 104 more matches
WebIDL bindings
the configuration file, dom/bindings/bindings.conf, is basi
cally a python dict that maps interface names to information about the interface,
called a descriptor.
... implement a wrapobject override on mozilla::dom::myinterface that just
calls through to mozilla::dom::myinterface_binding::wrap.
... note that if your c++ type is implementing multiple distinct web idl interfaces, you need to choose which mozilla::dom::myinterface_binding::wrap to
call here.
...And 102 more matches
Index - Archive of obsolete content
instead, sdk add-ons need to factor the code that gets access to web content into separate scripts that are
called content scripts.
... 110 system/unload register
callbacks that are
called when a module is unloaded.
... 181 downloading files code snippets to download a file, create an instance of nsiwebbrowserpersist and
call its nsiwebbrowserpersist.saveuri() method, passing it a url to download and an nsifile instance representing the local file name/path.
...And 100 more matches
Document - Web APIs
document.timelineread only returns timeline as a special instance of documenttimeline that is automati
cally created on page load.
... document.onfullscreenchange is an eventhandler representing the code to be
called when the fullscreenchange event is raised.
... document.onfullscreenerror is an eventhandler representing the code to be
called when the fullscreenerror event is raised.
...And 91 more matches
GlobalEventHandlers - Web APIs
globaleventhandlers.onabort is an eventhandler representing the code to be
called when the abort event is raised.
... globaleventhandlers.onanimationcancel an eventhandler
called when an animationcancel event is sent, indicating that a running css animation has been canceled.
... globaleventhandlers.onanimationend an eventhandler
called when an animationend event is sent, indicating that a css animation has stopped playing.
...And 84 more matches
Parser API
source string default: null a description of the input source; typi
cally a filename, path, or url.
...the expected
callback methods are described under builder objects.
... interface newexpression <: expression { type: "newexpression";
callee: expression; arguments: [ expression ]; } a new expression.
...And 76 more matches
JSAPI User Guide
it can compile and execute scripts, get and set object properties,
call javascript functions, convert javascript data from one type to another, create objects, and so on.
... 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.
...And 65 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
each of these components is
called a channel.
...specifi
cally, blink began as a fork of the webcore library in webkit, which handles layout, rendering, and dom, but now stands on its own as a separate rendering engine.
... 35 block cipher mode of operation block cipher mode of operation, cryptography, glossary, security a block cipher mode of operation, usually just
called a "mode" in context, specifies how a block cipher should be used to encrypt or decrypt messages that are longer than the block size.
...And 57 more matches
Index
2 an overview of nss internals api, intermediate, intro, nss, tools a high-level overview to the internals of network security services (nss) software developed by the mozilla.org projects traditionally used its own implementation of security protocols and cryptographic algorithms, originally
called netscape security services, nowadays
called network security services (nss).
...in order to support multiple operating systems (os), it is based on a cross platform portability layer,
called the netscape portable runtime (nspr), which provides cross platform application programming interfaces (apis) for os specific apis like file system access, memory management, network communication, and multithreaded programming.
... in order to allow interoperability between software and devices that perform cryptographic operations, nss conforms to a standard
called pkcs#11.
...And 54 more matches
Starting WebLock
getting
called at startup no person is an island to himself, and neither are components.
...after having its registration procedure
called, the component does nothing.
...weblock does the latter and gets
called when a gecko profile startup occurs.
...And 52 more matches
JavaScript Daemons Management - Archive of obsolete content
it also offers an alternative way to pass the this object to the
callback functions (see the "this" problem for details).
... about the “
callback arguments” polyfill in order to make this framework compatible with internet explorer (which doesn't support sending additional parameters to timers'
callback function, neither with settimeout() or setinterval()) we included the ie-specific compatibility code (commented code), which enables the html5 standard parameters' passage functionality in that browser for both timers (polyfill), at ...
...mon)) { 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); } } /* create the daemon.blank() constructor and the global daemon.context object */ daemon.blank = function () {}; daemon.context = daemon.blank.prototype; /* make love with the gc :-) */ daemon.blank.prototype = /* important!
...And 50 more matches
AddonManager
the majority of the methods are asynchronous meaning that results are delivered through
callbacks passed to the method.
... the
callbacks will be
called just once but that may be before or after the method returns.
...getinstallforurl(in string url, in install
callback?
...And 50 more matches
Using DTMF with WebRTC - Web APIs
se with legacy telephone services that rely on dtmf tones to perform tasks such as: teleconferencing systems menu systems voicemail systems entry of credit card or other payment information passcode entry note: while the dtmf is not sent to the remote peer as audio, browsers may choose to play the corresponding tone to the local user as part of their user experience, since users are typi
cally used to hearing their phone play the tones audibly.
...from there, you can simply
call rtcdtmfsender.insertdtmf() to enqueue dtmf signals to be sent on the track to the other peer.
... html the html for this example is very basic; there are only three elements of importance: an <audio> element to play the audio received by the rtcpeerconnection being "
called." a <button> element to trigger creating and connecting the two rtcpeerconnection objects, then sending the dtmf tones.
...And 48 more matches
Editor Embedding Guide - Archive of obsolete content
in the beginning there is makeeditable given an nsiwebbrowser instance, get an nsidomwindow from the getcontentdomwindow
call.
... then simply
call nsiwebbrowser->do_getinterface on the nsiwebbrowser to retrieve the nsieditingsession from it.
... from there you
call editingsession->makewindoweditable(domwindow, editortype, pr_true).
...And 47 more matches
Streams - Plugins
streams produced by the browser can be automati
cally sent to or requested by the plug-in instance.
... 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.
... random-access mode: the plug-in
calls the npn_requestread method to "pull" stream data.
...And 47 more matches
Background Tasks API - Web APIs
the cooperative scheduling of background tasks api (also referred to as the background tasks api or simply the requestidle
callback() api) provides the ability to queue tasks to be executed automati
cally by the user agent when it determines that there is free time to do so.
...window.requestidle
callback() makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag.
... getting the most out of idle
callbacks because idle
callbacks are intended to give your code a way to cooperate with the event loop to ensure that the system is utilized to its full potential without over-tasking it, resulting in lag or other performance problems, you should be thoughtful about how you go about using them.
...And 45 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
the setinterval() method, offered on the window and worker interfaces, repeatedly
calls a function or executes a code snippet, with a fixed time delay between each
call.
... it returns an interval id which uniquely identifies the interval, so you can remove it later by
calling clearinterval().
...if you want to enable this functionality on that browser, you must use a polyfill (see the
callback arguments section).
...And 45 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 automati
cally configured (preferences) at startup to the current user connected on the computer.
... file location (not tested since 2012 ...) in thunderbird , firefox, the javascript preference file that
calls the centralized preference file is located in $install_dir_moz_app/defaults/pref, for example in thunderbird this would be repectively for windows/linux: c:\program files\mozilla thunderbird\defaults\pref /usr/lib/thunderbird/default/pref ( it used to be in /usr/lib/thunderbird-version#/default/pref as in /usr/lib/thunderbird-5/default/pref ) for the record/history purpose ...
... that pref
calls.js is now archive in omni.jar file located at the root of the mozilla apps installation, example of tb5: # jar -tvf /usr/lib/thunderbird/omni.jar | grep pref
calls.js 7499 sat nov 05 09:21:34 cet 2011 defaults/autoconfig/pref
calls.js traditionally (previous apps versions) is was in mozilla_home/default/autoconfig/pref
calls.js.
...And 43 more matches
Drawing and Event Handling - Plugins
it is drawn in a target
called a drawable, which corresponds to either the browser window or an off-screen bitmap.
... for windowless plug-ins, the browser
calls the npp_setwindow method with an npwindow structure that represents a drawable.
... for windowed plug-ins, the browser
calls the npp_setwindow method with an npwindow structure that represents a window.
...And 41 more matches
Understanding WebAssembly text format - WebAssembly
parameters are basi
cally just locals that are initialized with the value of the corresponding argument passed by the
caller.
... when a function is
called, it starts with an empty stack which is gradually filled up and emptied as the body’s instructions are executed.
... our first function body as mentioned before, the function body is simply a list of instructions that are followed as the function is
called.
...And 41 more matches
Debugger.Frame - Firefox Developer Tools
every handler method
called while the debuggee is running in a given frame is given the same frame object.
...this allows the code using each debugger instance to place whatever properties it likes on its debugger.frame instances, without worrying about interfering with other debuggers.) when the debuggee pops a stack frame (say, because a function
call has returned or an exception has been thrown from it), the debugger.frame instance referring to that frame becomes inactive: its live property becomes false, and accessing its other properties or
calling its methods throws an exception.
... visible frames when inspecting the
call stack, debugger does not reveal all the frames that are actually present on the stack: while it does reveal all frames running debuggee code, it omits frames running the debugger’s own code, and omits most frames running non-debuggee code.
...And 39 more matches
JIT Optimization Outcomes
the most typical operations that are relevant for fast program execution are property accesses and function
calls.
... icoptstub_genericsuccess icgetpropstub_readslot icgetpropstub_
callgetter icgetpropstub_arraylength icgetpropstub_unboxedread icgetpropstub_unboxedreadexpando icgetpropstub_unboxedarraylength icgetpropstub_typedarraylength icgetpropstub_domproxyshadowed icgetpropstub_domproxyunshadowed icgetpropstub_genericproxy icgetpropstub_argumentslength icsetpropstub_slot icsetpropstub_genericproxy icsetpropstub_domproxyshadowed icsetpropstub_domproxyunshadowed ...
... icsetpropstub_
callsetter icsetpropstub_addslot icsetpropstub_setunboxed icgetelemstub_readslot icgetelemstub_
callgetter icgetelemstub_readunboxed icgetelemstub_dense icgetelemstub_densehole icgetelemstub_typedarray icgetelemstub_argselement icgetelemstub_argselementstrict icsetelemstub_dense icsetelemstub_typedarray icnamestub_readslot icnamestub_
callgetter
call inlining outcomes optimization outcomes of attempts to inline function
calls.
...And 37 more matches
Shell global objects
these are the global objects that are set up automati
cally by the spidermonkey js command-line interpreter when you start the program.
...filename is relative to the
calling script.
...the first
call with a string argument sets the source buffer.
...And 37 more matches
nsIDOMWindowUtils
cannot be accessed from unprivileged context (not content-accessible) will throw a dom security error if
called without universalxpconnect privileges.
... note: if there are some panels at the point, this method send the query event to the panel's widget automati
cally.
... cannot be accessed from unprivileged context (not content-accessible) will throw a dom security error if
called without universalxpconnect privileges.
...And 37 more matches
Getting Started Guide
it is a template class that acts, syntacti
cally, just like an ordinary pointer in c or c++, i.e., you can apply * or -> to it to "get to" what it points at.
...the client's reference to the object is typi
cally
called `an interface pointer'.
...the
caller can then hold onto the reference indefinitely,
calling release when it no longer needs it.
...And 36 more matches
Window - Web APIs
window.scrollmaxy read only the maximum offset that the window can be scrolled to verti
cally (i.e., the document height minus the viewport height).
... window.scrolly read only returns the number of pixels that the document has already been scrolled verti
cally.
... window.dialogarguments read only gets the arguments passed to the window (if it's a dialog box) at the time window.showmodaldialog() was
called.
...And 36 more matches
IME handling guide
if ime is available on focused elements, we
call that state "enabled".
... if ime is not fully available(i.e., user cannot enable ime), we
call this state "disabled".
... if ime is enabled but users use direct input mode (e.g., for inputting latin characters), we
call it "ime is closed".
...And 35 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 34 more matches
Graceful asynchronous programming with Promises - Learn web development
the application has a window with a list of the user's friends, and clicking on a button next to a user starts a video
call to that user.
... that button's handler
calls getusermedia() in order to get access to the user's camera and microphone.
... since getusermedia() has to ensure that the user has permission to use those devices and ask the user which microphone to use and which camera to use (or whether to be a voice-only
call, among other possible options), it can block until not only all of those decisions are made, but also the camera and microphone have been engaged.
...And 33 more matches
Mozilla DOM Hacking Guide
when, in javascript, a client tries to access a dom object or a dom method on a dom object, the js engine asks xpconnect to search for the relevant c++ method to
call.
...and indeed it will find it, and thus
call it.
...if that is the case, we
call nsidomlocation::sethref().
...And 33 more matches
nsIContentPrefService2
specifi
cally, a content preference is a structure with three values: a domain with which the preference is associated, a name that identifies the preference within its domain, and a value.
...a preference need not have a domain, and in that case the preference is
called a "global" preference.
...
callbacks the methods of
callback objects are always
called asynchronously.
...And 33 more matches
nsITextInputProcessor
createinstance(components.interfaces.nsitextinputprocessor); next, you need to get the rights to create composition or dispatch keyboard events with begininputtransaction() or begininputtransactionfortests(): if (!tip.begininputtransaction(window,
callback)) { return; } if begininputtransaction() or begininputtransactionfortests() returns false, it means that another instance of nsitextinputprocessor has composition on the window or is dispatching an event.
... the second argument,
callback, should be an object which implements nsitextinputprocessor
callback or just a function which is the same as nsitextinputprocessor
callback.onnotify().
... see the document of nsitextinputprocessor
callback for the detail.
...And 33 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
return value the returned timeoutid is a positive integer value which identifies the timer created by the
call to settimeout(); this value can be passed to cleartimeout() to cancel the timeout.
... it may be helpful to be aware that settimeout() and setinterval() share the same pool of ids, and that cleartimeout() and clearinterval() can techni
cally be used interchangeably.
... it is guaranteed that a timeout id will never be reused by a subsequent
call to settimeout() or setinterval() on the same object (a window or a worker).
...And 33 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
it was originally going to be
called livescript, but it was renamed in an ill-fated marketing decision that attempted to capitalize on the popularity of sun microsystem's java language — despite the two having very little in common.
...and to be techni
cally accurate, functions are just a special type of object.
...there's also a built-in object that we did not mention earlier
called math that provides advanced mathematical functions and constants: math.sin(3.5); var circumference = 2 * math.pi * r; you can convert a string to an integer using the built-in parseint() function.
...And 33 more matches
JIT Optimization Strategies
the most commonplace operations that are relevant for fast program execution are property accesses and function
calls.
... optimization information is currently collected for the following operations: getproperty (obj.prop) setproperty (obj.prop = val) getelement (obj[elemname]) setelement (obj[elemname] = val)
call (func(...)) at each operation site, ionmonkey tries a battery of strategies, from the most optimized but most restrictive to the least optimized but least restrictive.
...the function containing the arguments.length is allowed to use the arguments object in the following ways without disabling this optimization: access arguments.length access arguments.
callee access individual args using arguments[i] save arguments into variables, as long as those variables cannot be accessed by any nested function, and as long as there exists no eval anywhere within the function or nested function definitions.
...And 32 more matches
Intersection Observer API - Web APIs
histori
cally, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish.
... implementing intersection detection in the past involved event handlers and loops
calling methods like element.getboundingclientrect() to build up the needed information for every element affected.
...it uses a vendor-provided library to manage the advertisements placed periodi
cally throughout the page, has animated graphics here and there, and uses a custom library that draws notification boxes and the like.
...And 32 more matches
Observer Notifications
called when xpcom is initialized.
... profile-before-change
called just before the profile is lost.
... profile-before-change-qm
called to shut down the quotamanager; this is separated from profile-before-change to allow everything inside profile-before-change to continue using it.
...And 31 more matches
sslintro.html
an ssl application typi
cally includes five parts: initialization configuration communication functions used by
callbacks cleanup although the details differ somewhat for client and server applications, the concepts and many of the functions are the same for both.
... initialization initialization includes setting up configuration files, setting global defaults, and setting up
callback functions.
...must be
called before any other nss functions.
...And 30 more matches
Component; nsIPrefBranch
n string avalue); requires gecko 58 void setstringpref(in string aprefname, in utf8string avalue); void setcomplexvalue(in string aprefname, in nsiidref atype, in nsisupports avalue); void setintpref(in string aprefname, in long avalue); void unlockpref(in string aprefname); attributes attribute type description root string
called to get the root on which this branch is based, such as "browser.startup." read only.
...for example holding the "root" prefbranch and
calling addobserver("foo.bar.", ...) will observe changes to foo.bar.baz and foo.bar.bzip.
... clearuserpref()
called to clear a user set value from a specific preference.
...And 30 more matches
this - JavaScript
in most cases, the value of this is determined by how a function is
called (runtime binding).
... it can't be set by assignment during execution, and it may be different each time the function is
called.
... es5 introduced the bind() method to set the value of a function's this regardless of how it's
called, and es2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).
...And 30 more matches
EventTarget.addEventListener() - Web APIs
the eventtarget method addeventlistener() sets up a function that will be
called whenever the specified event is delivered to the target.
... addeventlistener() works by adding a function or an object that implements eventlistener to the list of event listeners for the specified event type on the eventtarget on which it's
called.
...see the event listener
callback for details on the
callback itself.
...And 29 more matches
Anatomy of a video game - Game development
this once-per-frame model is implemented in something
called a main loop.
... building a main loop in javascript javascript works best with events and
callback functions.
... modern browsers strive to
call methods right as they are needed and idle (or do their other tasks) in the gaps.
...And 28 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
setinterval() execute a specified block of code repeatedly with a fixed time delay between each
call.
... it's important to know that you can (and often will) run other code before a settimeout()
call executes, or between iterations of setinterval().
...the
callbacks you pass to these functions cannot run until the stack on the main thread is empty.
...And 28 more matches
PKCS11 Implement
this document supplements the information in pkcs #11: cryptographic token interface standard, version 2.0 with guidelines for implementors of cryptographic modules who want their products to work with mozilla client software: how nss
calls pkcs #11 functions.
...how nss
calls pkcs #11 functions this section is organized according to the categories used in pkcs #11: cryptographic token interface standard, version 2.0.
... general-purpose functions c_initialize the nss
calls c_initialize on startup or when it loads a new module.
...And 28 more matches
JSPropertyOp
jspropertyop and jsstrictpropertyop are the type of property getter and setter
callbacks in the jsapi.
... they are also the types of the jsclass.addproperty, getproperty, and setproperty
callbacks, which are
called during object property accesses.
...in js_threadsafe builds, the javascript engine
calls this
callback only from within an active request on cx.
...And 28 more matches
Mail composition back end
the feedback mechanism is provided by a nsimsgsendlistener which is implemented by the
caller.
... the
caller has the ability to add or remove listener interfaces to the nsimsgsend object and the interface can support multiple listeners.
...(note: this method could easily be broken in to a few different
calls.
...And 28 more matches
HTTP Cache
nsicachestorage //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicachestorage.idl obtained from
call to one of the *storage methods on nsicachestorageservice.
... unimplemented or underimplemented functionality: asyncevictstorage (bug 977766), asyncvisitstorage (bug 916052) nsicacheentryopen
callback //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicacheentryopen
callback.idl the result of nsicachestorage.asyncopenuri is always and only sent to
callbacks on this interface.
... these
callbacks are ensured to be invoked when asyncopenuri returns ns_ok.
...And 27 more matches
IPDL Tutorial
all ipdl messages are sent between parent and a child end points,
called actors.
... the parent actor is typi
cally the more permanent side of the conversation: parent/child actors parent child ipc tabs chrome process content process ipc plugins content process plugin process each protocol is declared in a separate file.
...each outgoing message is a c++ method which can be
called.
...And 27 more matches
Key Values - Web APIs
the tables below list the standard key values in various categories of key, with an explanation of what the key is typi
cally used for.
...typi
cally found between the windows (or os) key and the control key on the right side of the keyboard.
...typi
cally used as an exit, cancel, or "escape this operation" button.
...And 27 more matches
HTML parser threading
if the parser is not script-created, nshtml5parser::markasnotscriptcreated() is
called to create an nshtml5streamparser for the nshtml5parser.
... due to legacy interface design oddities, an nshtml5parser is initialized by
calling nshtml5parser::parse(nsiuri*, nsirequestobserver*, void*, nsdtdmode).
... that method
call doesn't yet cause anything to be parsed, though.
...And 26 more matches
Sqlite.jsm
there is even a shrinkmemory api that will minimize memory usage of the connection automati
cally.
...sqlite.jsm exposes a transaction api built on top of task.jsm that allows transactions to be written as procedural javascript functions (as opposed to a series of
callback driven operations).
... if the function throws, the transaction is automati
cally rolled back.
...And 26 more matches
Mozilla internal string guide
all string classes support the following three ownership models dynami
cally: reference counted, copy-on-write, buffers (the default) adopted buffers (a buffer that the string class owns, but is not reference counted, because it came from somewhere else) dependent buffers, that is, an underlying buffer that the string class does not own, but that the
caller that constructed the string guarantees will outlive the string instance in addition, there is a special stri...
...if one tries to
call a non-const method on a const string the compiler will flag this as an error at build time.
...
calling setcapacity() before beginwriting() does not affect what the previous sentence says.
...And 26 more matches
nsIHttpChannel
exceptions thrown ns_error_not_available if
called before the response has been received (before onstartrequest()).
... exceptions thrown ns_error_not_available if
called before the response has been received (before onstartrequest()).
... exceptions thrown ns_error_not_available if
called before the response has been received (before onstartrequest()).
...And 26 more matches
Debugger.Object - Firefox Developer Tools
spidermonkey creates exactly one debugger.object instance for each debuggee object it presents to a given debugger instance: if the debugger encounters the same object through two different routes (perhaps two functions are
called on the same object), spidermonkey presents the same debugger.object instance to the debugger each time.
...
callable true if the referent is a
callable object (such as a function or a function proxy); false otherwise.
... proxy
calltrap if the referent is a function proxy whose handler object was allocated by debuggee code, this is its
call trap function—the function
called when the function proxy is
called.
...And 26 more matches
Timing element visibility with the Intersection Observer API - Web APIs
the first column (sized automati
cally based on its content) is used for the sidebar and the second column (which will be used for body content) is sized to be at least the width of the contents of the column and at most all remaining available space.
...the rows are sized the same way as the columns: the first one is automati
cally sized and the one uses the remaining space, but at least enough space to provide room for all elements within it.
...he 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(intersection
callback, 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 26 more matches
Capabilities, constraints, and settings - Web APIs
histori
cally, writing scripts for the web that work intimately with web apis has had a well-known challenge: often, your code needs to know whether or not an api exists and if so, what its limitations are on the user agent it's running on.
...this article discusses capabilities and constraints, as well as media settings, and includes an example we
call the constraint exerciser.
... overview the process works like this (using mediastreamtrack as an example): if needed,
call mediadevices.getsupportedconstraints() to get the list of supported constraints, which tells you what constrainable properties the browser knows about.
...And 26 more matches
Modularization techniques - Archive of obsolete content
a pure virtual interface is simply a class where every method is defined as pure virtual, that is: virtual int foo(int bar) = 0; pure virtual interfaces provide an easy mechanism for passing function tables between modules that may reside in separate, possibly dynami
cally loaded, libraries.
...the
caller passes in an id and a pointer to a address to place the resulting interface.
...if a
call to release() causes the reference count to hit zero, the object will generally free itself.
...And 25 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
m './moreactions.svelte' then add the described functions at the end of the <script> section: const checkalltodos = (completed) => todos.foreach(t => t.completed = completed) const removecompletedtodos = () => todos = todos.filter(t => !t.completed) now go to the bottom of the todos.svelte markup section and replace the btn-group <div> that we copied into moreactions.svelte with a
call to the moreactions component, like so: <!-- moreactions --> <moreactions on:checkall={e => checkalltodos(e.detail)} on:removecompleted={removecompletedtodos} /> ok, let's go back into the app and try it out!
...basi
cally, the virtual dom is an in-memory copy of the contents of the web page.
... these frameworks, by default, basi
cally re-run all our javascript on every change against this virtual dom, and apply different methods to cache expensive calculations and optimize execution.
...And 25 more matches
Reference Manual
in debug builds, if you subvert this invariant with one of the assignment forms that doesn't
call queryinterface, nscomptr will assert at runtime in the bad assignment.
... nscomptr<nsifoo> foo = ...; foo->addref(); // error: |addref| is private delete foo.get(); // error: |operator delete| is private ns_release(foo); // error: |release| is private of course, the most important safety feature provided by nscomptr is that it addrefs and releases automati
cally at the appropriate times.
...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.
...And 25 more matches
XPIDL
t nsacstring& nsacstring& string only chars in range \u0000-\u00ff permitted astring const nsastring& nsastring& string full unicode set permitted jsval const jsval& jsval* anything jsid jsid jsid* not allowed promise mozilla::dom::promise* mozilla::dom::promise** promise typedefs in idl are basi
cally as they are in c or c++: you define first the type that you want to refer to and then the name of the type.
... constants constants are techni
cally legal at the top level, but xpidl i forbids them from being placed there; instead, they must be in an interface.
...interfaces are basi
cally a collection of constants, methods, and attributes; in mozilla, these are the primary ways in which javascript code can interact with native c++ code.
...And 25 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
javascript promises and the mutation observer api both use the microtask queue to run their
callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up.
... tasks a task is any javascript code which is scheduled to be run by the standard mechanisms such as initially starting to run a program, an event
callback being run, or an interval or timeout being fired.
... an event fires, adding the event's
callback function to the task queue.
...And 25 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
logging errors a function
called logglerror() is implemented to provide an easily customized way to output logging information for errors that occur while executing webgl functions.
... handling the startup and shutdown ui then we
call the setupxrbutton() function, which handles configuring the "enter/exit webxr" button to enable or disable it as necessary depending on the availability of webxr support for the session type specified in the session_type constant.
...if it is, we
call sessionstarted() to begin running the scene in the webxr session.
...And 25 more matches
Functions - JavaScript
to use a function, you must define it somewhere in the scope from which you wish to
call it.
... defining functions function declarations a function definition (also
called a function declaration, or function statement) consists of the function keyword, followed by: the name of the function.
... for example, the following code defines a simple function named square: function square(number) { return number * number; } the function square takes one parameter,
called number.
...And 25 more matches
jspage - Archive of obsolete content
c=k.implement;var h=k.generics;var f=k.initialize;var g=k.afterimplement||function(){};var d=f||i;h=h!==false;d.constructor=native;d.$family={name:"native"}; if(i&&f){d.prototype=i.prototype;}d.prototype.constructor=d;if(a){var e=a.tolowercase();d.prototype.$family={name:e};native.typize(d,e);}var j=function(n,l,o,m){if(!b||m||!n.prototype[l]){n.prototype[l]=o; }if(h){native.genericize(n,l,b);}g.
call(n,l,o);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return j(this,m,l,o);}for(var n in m){j(this,n,m[n],l); }return this;};if(c){d.implement(c);}return d;};native.genericize=function(b,c,a){if((!a||!b[c])&&typeof b.prototype[...
...c]=="function"){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 ...
...And 24 more matches
Using IndexedDB - Web APIs
the
call to the open() function returns an idbopendbrequest object with a result (success) or error value that you handle as an event.
...}; which of the two functions, onsuccess() or onerror(), gets
called?
... now, assuming that the user allowed your request to create a database, and you've received a success event to trigger the success
callback; what's next?
...And 24 more matches
MMgc - Archive of obsolete content
managed memory is memory that is reclaimed automati
cally by the garbage collector.
...in mmgc, you get managed memory by subclassing gcobject/gcfinalizedobject/rcobject, or by
calling gc::alloc.
...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).
...And 23 more matches
Introducing asynchronous JavaScript - Learn web development
there are two main types of asynchronous code style you'll come across in javascript code, old-style
callbacks and newer promise-style code.
... async
callbacks async
callbacks are functions that are specified as arguments when
calling a function which will start executing code in the background.
... when the background code finishes running, it
calls the
callback function to let you know the work is done, or to let you know that something of interest has happened.
...And 23 more matches
WebRTC connectivity - Web APIs
we
call this the signal channel or signaling service.
... session descriptions the configuration of an endpoint on a webrtc connection is
called a session description.
... when a user starts a webrtc
call to another user, a special description is created
called an offer.
...And 23 more matches
Indexed collections - JavaScript
for example, consider an array
called emp, which contains employees' names indexed by their numerical employee number.
... the bracket syntax is
called an "array literal" or "array initializer." it's shorter than other forms of array creation, and so is generally preferred.
...
calling arr.length will return arraylength, but the array doesn't contain any elements.
...And 23 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.
... syntax let boundfunc = func.bind(thisarg[, arg1[, arg2[, ...argn]]]) parameters thisarg the value to be passed as the this parameter to the target function func when the bound function is
called.
...when using bind to create a function (supplied as a
callback) inside a settimeout, any primitive value passed as thisarg is converted to object.
...And 23 more matches
Using the Editor from XUL - Archive of obsolete content
editoronload() is
called.
... 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.
... now we set up the editorshell by
calling its init() method, telling it what type of editor we want (text or html), pointing it at the webshellwindow to use, and telling it the content node that it lives on: editorshell.init(); editorshell.seteditortype(editortype); editorshell.webshellwindow = window; editorshell.contentwindow = window._content; the webshellwindow (a settable attribute on nsieditorshell) points to the top-level...
...And 22 more matches
CustomizableUI.jsm
when a customizable toolbar's xbl binding is constructed (generally, that is when a <toolbar customizable="true"/> node is appended to the document and isn't invisible), the binding will
call into customizableui and register the toolbar's node as being one of the concrete instances of its area.
... the lifetime of your widget should be identical to the lifetime of the add-on - it's process-global, so if you
call createwidget on bootstrap's "startup" and destroywidget on bootstrap's "shutdown", that's enough.
... legacy set to true if you want customizableui to automati
cally migrate the currentset attribute.
...And 22 more matches
L20n Javascript API
l20n javascript api var ctx = l20n.getcontext(); ctx.linkresource('./locales/strings.l20n'); ctx.requestlocales(); when you freeze the context by
calling requestlocales, the resource files will be retrieved, parsed and compiled.
... alternatively, you can register
callbacks to execute when the context is ready (or when globals change and translations need to be updated) with ctx.localize.
...if it is undefined, or if registerlocales hasn't been
called at all, the context instance will create a special locale
called i-default to be used as the default.
...And 22 more matches
An overview of NSS Internals
a high-level overview to the internals of network security services (nss) software developed by the mozilla.org projects traditionally used its own implementation of security protocols and cryptographic algorithms, originally
called netscape security services, nowadays
called network security services (nss).
...in order to support multiple operating systems (os), it is based on a cross platform portability layer,
called the netscape portable runtime (nspr), which provides cross platform application programming interfaces (apis) for os specific apis like file system access, memory management, network communication, and multithreaded programming.
... in order to allow interoperability between software and devices that perform cryptographic operations, nss conforms to a standard
called pkcs#11.
...And 22 more matches
Hacking Tips
without arguments, it will dump the bytecode of its
caller.
... the backtrace contains in the following order, the stack depth, the interpreter frame pointer (see js/src/vm/stack.h, stackframe class) or (nil) if compiled with ionmonkey, the file and line number of the
call location and under parentheses, the jsscript pointer and the jsbytecode pointer (pc) executed.
... $ gdb --args js […] (gdb) b js::reportoverrecursed (gdb) r js> function f(i) { if (i % 2) f(i + 1); else f(i + 3); } js> f(0) breakpoint 1, js::reportoverrecursed (maybecx=0xfdca70) at /home/nicolas/mozilla/ionmonkey/js/src/jscntxt.cpp:495 495 if (maybecx) (gdb)
call js::dumpbacktrace(maybecx) #0 (nil) typein:2 (0x7fffef1231c0 @ 0) #1 (nil) typein:2 (0x7fffef1231c0 @ 24) #2 (nil) typein:3 (0x7fffef1231c0 @ 47) #3 (nil) typein:2 (0x7fffef1231c0 @ 24) #4 (nil) typein:3 (0x7fffef1231c0 @ 47) […] #25157 0x7fffefbbc250 typein:2 (0x7fffef1231c0 @ 24) #25158 0x7fffefbbc1c8 typein:3 (0x7fffef1231c0 @ 47) #25159 0x7fffefbbc140 typein:2 (0x7fffef1231c0 @ 24) #25160 0x7fffefbbc0b8 typein:3 (0x7fffef1231c0 @ 47) #25161 0x7ff...
...And 22 more matches
Details of the object model - JavaScript
in that definition you can specify special methods,
called constructors, to create instances of the class.
...next, you define the manager constructor function,
calling the employee constructor and specifying the reports property.
... adding and removing properties in class-based languages, you typi
cally create a class at compile time and then you instantiate instances of the class either at compile time or at run time.
...And 22 more matches
Using Promises - JavaScript
essentially, a promise is a returned object to which you attach
callbacks, instead of passing
callbacks into a function.
... imagine a function, createaudiofileasync(), which asynchronously generates a sound file given a configuration record and two
callback functions, one
called if the audio file is successfully created, and the other
called if an error occurs.
... here's some code that uses createaudiofileasync(): function success
callback(result) { console.log("audio file ready at url: " + result); } function failure
callback(error) { console.error("error generating audio file: " + error); } createaudiofileasync(audiosettings, success
callback, failure
callback); modern functions return a promise that you can attach your
callbacks to instead: if createaudiofileasync() were rewritten to return a promise, using it could be as simple as this: createaudiofileasync(audiosettings).then(success
callback, failure
callback); that's shorthand for: const promise = createaudiofileasync(audiosettings); promise.then(success
callback, failure
callback); we
call this an asynchronous function
call.
...And 22 more matches
Array.prototype.every() - JavaScript
syntax arr.every(
callback(element[, index[, array]])[, thisarg]) parameters
callback a function to test for each element, taking three arguments: element the current element being processed in the array.
... array optional the array every was
called upon.
... thisarg optional a value to use as this when executing
callback.
...And 22 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
mozilla does not support accessing an element through document.elementname or even through the element's name, which internet explorer does (also
called global namespace polluting).
...the method returns an array in javascript, and can be
called on the document element or other nodes to search only their subtree.
...h a nodetype of 1: html: <div id="foo"> <span>test</span> </div> javascript: var mydiv = document.getelementbyid("foo"); var mychildren = mydiv.childnodes; for (var i = 0; i < mychildren.length; i++) { if (mychildren[i].nodetype == 1){ // element node }; }; generate and manipulate content mozilla supports the legacy methods for adding content into the dom dynami
cally, such as document.write, document.open and document.close.
...And 21 more matches
Working with Svelte stores - Learn web development
sometimes, your app state will need to be accessed by multiple components that are not hierarchi
cally related, or by a regular javascript module.
... 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!".
... next we import the ondestroy() lifecycle function, which lets us execute a
callback after the component has been unmounted.
...And 21 more matches
NSS PKCS11 Functions
caller owns the reference if unsuccessful, null.
...once the the module has been successfully loaded, other nss
calls will use it in the normal course of searching.
...the
caller is responsible for making sure the module spec is correct and usable.
...And 21 more matches
JSAPI reference
ntexts 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_setcontext
callback enum jscontextop js_getruntime js_getparentruntime added in spidermonkey 31 js_getobjectruntime added in spidermonkey 17 js_getcontextprivate js_setcontextprivate js_getsecondcontextprivate added in spidermonkey 17 js_setsecondcontextprivate added in spidermonkey 17 js_setinterrupt
callback added in spidermonkey 31 js_getinterrupt
callback added in spidermonkey 31 ...
...js_requestinterrupt
callback added in spidermonkey 31 js_checkforinterrupt added in jsapi 45 js_destroycontextmaybegc obsolete since jsapi 14 js_setbranch
callback obsolete since javascript 1.9.1 js_setoperation
callback obsolete since jsapi 30 js_getoperation
callback obsolete since jsapi 30 js_triggeroperation
callback obsolete since jsapi 30 js_clearoperation
callback obsolete since javascript 1.9.1 js_getoperationlimit obsolete since javascript 1.9.1 js_setoperationlimit obsolete since javascript 1.9.1 js_max_operation_limit obsolete since javascript 1.9.1 js_operation_weight_base obsolete since javascript 1.9.1 js_setthreadstacklimit obsolete since jsapi 13 js_setscriptstackquota obsolete since javascript 1.8.6 js_setoptions obsolete since jsapi 27 js_getoptions obsolete si...
...ed 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_setdestroycompartment
callback added in spidermonkey 17 js_setcompartmentname
callback added in spidermonkey 17 js_newcompartmentandglobalobject added in spidermonkey 1.8.1 obsolete since jsapi 16 js_entercrosscompartment
call added in spidermonkey 1.8.1 obsolete since jsapi 18 js_leavecrosscompartment
call added in spidermonkey 1.8.1 obsolete since jsapi 18 locale
callbacks: struct jslocale
callbacks js_getlocale...
...And 21 more matches
An Overview of XPCOM
the brief sections in this chapter introduce the concepts at a very high level, so that we can discuss and use them with more familiarity in the tutorial itself, which describes the creation of a mozilla component
called weblock.
...this is the contractual agreement of this unencapsulated class: a set of rules that define when each method can be
called and what it is expected to do.
... one rule might specify that dosomethinguseful may only be
called after a
call to init().
...And 21 more matches
Creating the Component Code
specifi
cally, the component library has to contain implementations for the component-related interfaces described in this chapter: nsimodule and nsifactory, which are entry points for your implementation code.
...applications typi
cally use regxpcom, described in the next section.
...this is very useful if the
caller is required to know information about the component like its threading module, whether or not it's a singleton, its implementation language, and so forth.
...And 21 more matches
imgIDecoderObserver
if an image is decoded on load and not visibly discarded, decode notifications are nested logi
cally inside load notifications as one might expect.
...if imgidecoder::flag_sync_decode is passed to a function that triggers a decode, all notifications that can be generated from the currently loaded data fire before the
call returns.
... if flag_sync_decode is not passed, all, some, or none of the notifications may fire before the
call returns.
...And 21 more matches
nsITimer
nsitimer instances must be initialized by
calling one of the initialization methods.
... method overview void cancel(); void init(in nsiobserver aobserver, in unsigned long adelay, in unsigned long atype); void initwith
callback(in nsitimer
callback a
callback, in unsigned long adelay, in unsigned long atype); void initwithfunc
callback(in nstimer
callbackfunc a
callback, in voidptr aclosure, in unsigned long adelay, in unsigned long atype); native code only!
... attributes attribute type description
callback nsitimer
callback the nsitimer
callback object passed to initwith
callback().
...And 21 more matches
Migrating from Firebug - Firefox Developer Tools
that means that when you open a page on the same origin in a different tab, firebug gets opened automati
cally.
... and when you open a page of a different origin in the same tab, it closes automati
cally.
...in the devtools this option is
called enable persistent logs and is available within the toolbox options panel.
...And 21 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
negotiation is an inherently asymmetric operation: one side needs to serve as the "
caller" while the other peer is the "
callee." the perfect negotiation pattern smooths this difference away by separating that difference out into independent negotiation logic, so that your application doesn't need to care which end of the connection it is.
... as far as your application is concerned, it makes no difference whether you're
calling out or receiving a
call.
... the best thing about perfect negotiation is that the same code is used for both the
caller and the
callee, so there's no repetition or otherwise added levels of negotiation code to write.
...And 21 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
there's no magic object provided by either the webgl or the webxr api that represents the viewer that you can simply rotate and move around to automati
cally change what's seen on the screen.
... points of view since the camera is a virtual object which, rather than necessarily representing a physical object in the virtual world, represents a viewer's position and viewing direction, it's useful to think about the kinds of situation that
call for the use of a camera.
... when using webgl to accelerate 2d graphics drawing, the camera is typi
cally placed directly above the center of the scene with the distance and field of view set to allow the entire scene to be presented.
...And 21 more matches
context-menu - Archive of obsolete content
usage instead of manually adding items when particular contexts occur and then removing them when those contexts go away, you bind items to contexts, and the adding and removing is automati
cally handled for you.
...when the user invokes the context menu, all of the items bound to the current context are automati
cally added to the menu.
...likewise, any items that were previously in the menu but are not bound to the current context are automati
cally removed from the menu.
...And 20 more matches
Functions — reusable blocks of code - Learn web development
previous overview: building blocks next another essential concept in coding is functions, which allow you to store a piece of code that does a single task inside a defined block, and then
call that code whenever you need it using a single short command — rather than having to type out the same code multiple times.
...in fact, some of the code you are
calling when you invoke (a fancy word for run, or execute) a built in browser function couldn't be written in javascript — many of these functions are
calling parts of the background browser code, which is written largely in low-level system languages like c++, not web languages like javascript.
... functions versus methods programmers
call functions that are part of objects methods.
...And 20 more matches
Performance best practices for Firefox front-end engineers
use requestidle
callback() if you simply cannot avoid doing some kind of long job on the main thread, try to break it up into smaller pieces that you can run when the browser has a free moment to spare, and the user isn't doing anything.
... you can do that using requestidle
callback() and the cooperative scheduling of background tasks api, and doing it only when we have a free second where presumably the user isn’t doing something.
... see also the blog post collective scheduling with requestidle
callback.
...And 20 more matches
Web Replay
these behaviors mainly originate from system
calls (i/o and such).
... both of these involve inter-thread communication and
calls to non-deterministic apis, and the resulting non-determinism must be allowed within the replaying process.
... recording a recording content process differs from a normal content process in the following ways:
calls to certain functions are intercepted by hooking them (rewriting the machine code at their entry points to
call a different function with the same signature), including the function used to dispatch mach messages.
...And 20 more matches
nsIPromptService
it typi
cally has the label "ok", "yes", or "save".
...it typi
cally has the label "cancel" or "no".
... acheckstate contains the initial checked state of the checkbox when this method is
called and the final checked state after this method returns.
...And 20 more matches
Debugger.Object - Firefox Developer Tools
spidermonkey creates exactly one debugger.object instance for each debuggee object it presents to a given debugger instance: if the debugger encounters the same object through two different routes (perhaps two functions are
called on the same object), spidermonkey presents the same debugger.object instance to the debugger each time.
...
callable true if the referent is a
callable object (such as a function or a function proxy); false otherwise.
...this can return null if the promise was not resolved by
calling its resolve or reject resolving functions from script.
...And 20 more matches
A basic 2D WebGL animation example - Web APIs
let uscalingfactor; let uglobalcolor; let urotationvector; let avertexposition; // animation timing let previoustime = 0.0; let degreespersecond = 90.0; initializing the program is handled through a load event handler
called startup(): window.addeventlistener("load", startup, false); function startup() { glcanvas = document.getelementbyid("glcanvas"); gl = glcanvas.getcontext("webgl"); const shaderset = [ { type: gl.vertex_shader, id: "vertex-shader" }, { type: gl.fragment_shader, id: "fragment-shader" } ]; shaderprogram = buildshaderprogram(shaderset); aspec...
... once the vertex array has been created, we create a new gl buffer to contain them by
calling gl.createbuffer().
... we bind the standard webgl array buffer reference to that by
calling gl.bindbuffer() and then copy the vertex data into the buffer using gl.bufferdata().
...And 20 more matches
Classes and Inheritance - Archive of obsolete content
instead, it uses something
called prototypal inheritance.
...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 automati
cally creates a new object and binds it to the keyword this for the duration of the
call.
...And 19 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
an xpinstall package is usually
called an xpi package for short (and often pronounced "zippy").
...xpi packages, like zip files, "contain" other files, typi
cally: the software component to be installed.
... a javascript file
called install.js, which is the install logic that drives the installation.
...And 19 more matches
XPCOM Interfaces - Archive of obsolete content
calling native objects by using xul we can build a complex user interface.
...we also need to have a way for our scripts to
call the native code easily.
...the components are constructed from a number of definitions
called interfaces.
...And 19 more matches
Build your own function - Learn web development
active learning: let's build a function the custom function we are going to build will be
called displaymessage().
...any parameters we want to give to our function go inside the parentheses, and the code that runs when we
call the function goes inside the curly braces.
... the first line uses a dom api function
called document.queryselector() to select the <html> element and store a reference to it in a constant
called html, so we can do things to it later on: const html = document.queryselector('html'); the next section uses another dom api function
called document.createelement() to create a <div> element and store a reference to it in a constant
called panel.
...And 19 more matches
Drawing graphics - Learn web development
to draw onto the canvas we need to get a special reference to the drawing area
called a context.
...the a value defines what's
called the "alpha channel, " or the amount of transparency the color has.
... strokes and line widths so far we've looked at drawing filled rectangles, but you can also draw rectangles that are just outlines (
called strokes in graphic design).
...And 19 more matches
Handling common JavaScript problems - Learn web development
the trouble with javascript histori
cally, javascript was plagued with cross-browser compatibility problems — back in the 1990s, the main browser choices back then (internet explorer and netscape) had scripting implemented in different language flavours (netscape had javascript, ie had jscript and also offered vbscript as an option), and while at least javascript and jscript were compatible to some degree (both based on the ecmascript...
...if you want this to work correctly, you need to define a function to add the handler separately,
calling it on each iteration and passing it the current value of para and i each time (or something similar).
... you should see a package
called lint at the top of the list.
...And 19 more matches
Setting up your own test automation environment - Learn web development
objective: to show how to set up a selenium testing environment lo
cally and run tests with it, and how to integrate it with tools like lambdatest, sauce labs, and browserstack.
...there are other ways, but the best way to use selenium is via webdriver, a powerful api that builds on top of selenium and makes
calls to a browser to automate it, carrying out actions such as "open this web page", "move over this element on the page", "click this link", "see whether the link opens this url", etc.
...
call it something different, like selenium-test.
...And 19 more matches
source-editor.jsm
the source-editor.jsm javascript code module implements an editor specifi
cally tailored for editing source code; its primary purpose is to provide support for web developer tools to display and edit web site code.
... method overview initialization and destruction void destroy(); void init(element aelement, object aconfig, function a
callback); search operations number find(string astring, [optional] object options); number findnext(boolean awrap); number findprevious(boolean awrap); event management void addeventlistener(string aeventtype, function a
callback); void removeeventlistener(string aeventtype, function a
callback); undo stack operations bool...
... sourceeditor.prefs.expand_tab "devtools.editor.expandtab" a boolean value that indicates whether or not to automati
cally expand tabs out to a series of spaces.
...And 19 more matches
Necko walkthrough
nshttpchannel::asyncopen
called from openuri; openchannel isn't named the best, since the opening happens in the context of openuri, its
calling function.
...but the interface for clients of necko is important to consider: send request uri helps creates channel setup channel (headers, request data, response
callback...) channel->asyncopen.
... receive response get a
callback to each of these: nsistreamlistener::onstartrequest (header info) nsistreamlistener::ondataavailable (data in single or multiple chunks) nsistreamlistener::onstoprequest (no more data from http) this all happens on the main thread, in a non-blocking fashion: make your request on the main thread, then carry on and get the async response later, also on the main thread.
...And 19 more matches
Introduction to XPCOM for the DOM
such a class is
called an interface.
...if the interface is
called nsifoo and the class is
called nsfoo, we say that "nsfoo implements nsifoo", or that "nsfoo inherits from nsifoo".
... an instance of a class (
called an object) can be allocated dynami
cally (on the heap, or free store), using the syntax nsfoo *fooptr = new nsfoo; that object can then be manipulated only through fooptr.
...And 19 more matches
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.
... then, the uri can be fetched by
calling open() or asyncopen().
...in earlier versions
callers could get the "content-length" property as 64-bit value by queryinterfacing the channel to nsipropertybag2, if that interface is exposed by the channel.
...And 19 more matches
nsIDBChangeListener
nhdrpropertychanged: function(ahdrtochange, aprechange, astatus, ainstigator) {}, onevent: function(adb, aevent) {}, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsidbchangelistener) && !aiid.equals(components.interfaces.nsisupports)) throw components.results.ns_error_no_interface; return this; } }; and to attach it in thunderbird, we must
call addlistener on a nsidbchangeannouncer, typi
cally through a nsimsgdatabase.
...id onreadchanged(in nsidbchangelistener ainstigator); void onjunkscorechanged(in nsidbchangelistener ainstigator); void onhdrpropertychanged(in nsimsgdbhdr ahdrtochange, in unsigned long aoldflags, in prbool aprechange, inout pruint32 astatus, in nsidbchangelistener ainstigator); void onevent(in nsimsgdatabase adb, in string aevent); methods onhdrflagschanged()
called when a message's flags change.
... ainstigator the
caller who changed the header.
...And 19 more matches
nsINavHistoryResultObserver
although this attribute is read-write, you should not alter it directly; instead,
call nsinavhistoryresult.addobserver() to add an observer to a result.
... containerclosed() obsolete since gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8)
called when a container node's state changes from opened to closed.
... containeropened() obsolete since gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8)
called when a container node's state changes from closed to opened.
...And 19 more matches
nsINavHistoryResultViewer
methods containerclosed()
called when a container node's state changes from closed to opened.
... containeropened()
called when a container node's state changes from closed to opened.
... invalidatecontainer()
called when something has happened that requires that the contents of a container be rebuilt.
...And 19 more matches
nsIXULTemplateQueryProcessor
the query is expected to consist of either text or dom nodes that, when executed by a
call to the generateresults() method, will allow the generation of a list of results.
...the template builder must
call initializeforbuilding() before the other methods, except for translateref().
... the builder will then
call compilequery() for each query in the template to compile the queries.
...And 19 more matches
Storage
it is available to trusted
callers, meaning extensions and firefox components only.
...this extension is treated specially by windows as a known extension for an 'application compatibility database' and changes are backed up by the system automati
cally as part of system restore functionality.
...the latter will allow all ongoing transactions to complete before closing the connection, and will optionally notify you via
callback when the connection is closed.
...And 19 more matches
WebGL best practices - Web APIs
and to a lesser degree, vao attachments (vertexattribpointer, disable/enablevertexattribarray) drawing from static, unchanging vaos is faster than mutating the same vao for every draw
call.
...the overhead for this is relatively low, but re-using vaos means fewer vertexattribpointer
calls too, so it's worth doing wherever it's easy.
... for example, it is possible for the following to never complete without context loss: sync = glfencesync(gl_sync_gpu_commands_complete, 0); glclientwaitsync(sync, 0, gl_timeout_ignored); webgl doesn't have a swapbuffers
call by default, so a flush can help fill the gap, as well.
...And 19 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
practical tips for developers and how mozilla does it contents this document is for developers working to support msaa in an application in order to make it accessible with 3rd party assistive technologies, as well as for hackers wishing to be involved in mozilla's msaa support specifi
cally.
... myth: msaa is too slow reality: assistive technology vendors have found ways around most of the performance problems related to out-of-process com method
calls.
...we'll have to wait and see how good the msaa support in longhorn is, before we can
call this one.
...And 19 more matches
Bootstrapped extensions - Archive of obsolete content
traditional extensions include overlays, wherein the application can load up xul from the extension's package and automati
cally apply it on top its own ui.
...these are special extensions that, instead of using overlays to apply their user interface to the application, programmati
cally insert themselves into the application.
... this is done using a special script file that's included in the extension that contains functions the browser
calls to command the extension to install, uninstall, start up, and shut down.
...And 18 more matches
Adding preferences to an extension - Archive of obsolete content
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".
... startup() the stockwatcher.startup() function is
called when our extension is first loaded.
... its job is to start up the observer to watch for changes to our preferences, instantiate an object to use to manage our preferences, and install an interval routine to update the stock information periodi
cally.
...And 18 more matches
LiveConnect Overview - Archive of obsolete content
when programming in javascript, you can use a wrapper object to access methods and fields of the java object;
calling a method or accessing a property on the wrapper results in a
call on the java object.
...these java methods are available in javascript as methods of the javaobject, and you can
call them as follows: mystring.length(); // returns 11 static members can be
called directly on the javaclass object.
...for example, suppose the redwood corporation uses a java package
called redwood to contain various java classes that it implements.
...And 18 more matches
React interactivity: Events and state - Learn web development
callback props in react applications, interactivity is rarely confined to just one component: events that happen in one component will affect other parts of the app.
...this function-as-a-prop is
called a
callback prop.
... once we have our
callback prop, we can
call it inside <form /> to send the right data to <app />.
...And 18 more matches
Introduction to automated testing - Learn web development
using a task runner to automate testing tools as we said above, you can drasti
cally speed up common tasks such as linting and minifying code by using a task runner to run everything you need to run automati
cally at a certain point in your build process.
... this file is basi
cally a config file for the project.
... 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.
...And 18 more matches
Introducing a complete toolchain - Learn web development
parcel to build and minify our code, and to write a bunch of configuration file content automati
cally for us.
... for our sample project, we'll be using a toolchain specifi
cally designed to aid our software development and support the technical choices made during the software design phase.
... 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 techni
cally you only need to create one new account.
...And 18 more matches
Profiling with the Firefox Profiler
black: these indicate synchronous ipc
calls.
...the change in stack height is useful to find patterns like long blocking
calls (long flatlines) or very tall spiky blocks (recursive
calls and js).
...
call tree the
call tree shows the samples organized by 'running time' which will show the data by wall clock time.
...And 18 more matches
JSS FAQ
if i don't
call setcipherpolicy, is the domestic policy used by default?
... can you explain jss ssl certificate approval
callbacks?
...ontent.java org/mozilla/jss/pkix/crmf/certreqmsg.java org/mozilla/jss/pkix/crmf/certtemplate.java org/mozilla/jss/pkix/primitive/name.java org/mozilla/jss/provider/javax/crypto/jsssecretkeyfactoryspi.java org/mozilla/jss/util/utf8converter.java org/mozilla/jss/util/base64inputstream.java jss/samples/pqggen.java jss/samples/pkcs12.java if i don't
call setcipherpolicy, is the domestic policy used by default?
...And 18 more matches
Python binding for NSS
the design of python-nss follows these basic guiding principles: be a thin layer with almost a one-to-one mapping of nss/nspr
calls to python methods and functions.
... nss/nspr objects which have "get" and "set" api function
calls are exposed as python properties.
...the python global interpreter lock (gil) is released prior to
calling nss/nspr c functions and reaquired after the nss/nspr c function returns.
...And 18 more matches
XPCOM array guide
for example: // handlelist cannot modify the array because of const void handlelist(const nstarray<t>&); in-place enumeration most of the arrays presented here provide
callback-style means to enumerate members of an array.
... instead of incrementally accessing each element of the array by its index, the arrays provide a way to pass in a
callback function that will be
called for each element in the array.
... for most concrete c++ classes like nstarray<t> and nscomarray<t>, indexing should be faster than the
callback-style enumeration, because accessing an indexed member of such an array is usually very fast, while enumeration has slight function
call overhead.
...And 18 more matches
Add to iPhoto
this extension for mac os x serves as a demonstration of how to use js-ctypes to
call mac os x carbon, core foundation, and other system frameworks from an extension written entirely in javascript.
... 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.
... cfarray the cfarray type is used to create arrays of objects; the objects in the array can be of any type, thanks to a set of
callbacks you can provide to handle managing their memory and performing operations such as comparisons.
...And 18 more matches
Plug-in Basics - Plugins
with the plug-in api, you can create dynami
cally 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 b...
... how plug-ins work the life cycle of a plug-in, unlike that of an application, is completely controlled by the web page that
calls it.
... the following stages outline the life of a plug-in from loading to deletion: when gecko encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it dynami
cally loads the plug-in code into memory, if it hasn't been loaded already, and it creates a new instance of the plug-in.
...And 18 more matches
A simple RTCDataChannel sample - Web APIs
starting up when the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function is
called.
... establishing a connection when the user clicks the "connect" button, the connectpeers() method is
called.
... the next step is to create the rtcdatachannel by
calling rtcpeerconnection.createdatachannel() and set up event listeners to monitor the channel so that we know when it's opened and closed (that is, when the channel is connected or disconnected within that peer connection).
...And 18 more matches
Using Web Workers - Web APIs
dedicated workers as mentioned above, a dedicated worker is only accessible by the script that
called it.
...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.
... terminating a worker if you need to immediately terminate a running worker from the main thread, you can do so by
calling the worker's terminate method: myworker.terminate(); the worker thread is killed immediately.
...And 18 more matches
ui/button/toggle - Archive of obsolete content
they have an extra attribute checked that is automati
cally toggled when the button is clicked.
... you can generate click and change events programmati
cally with the button's click() method.
...to set state like this,
call state() with 2 parameters: the first parameter is a window or tab object or as a shorthand, the string "window" for the currently active window, or the string "tab" for the currently active tab the second parameter is an object containing the state properties you wish to update.
...And 17 more matches
Index - Archive of obsolete content
422 deprecated and defunct markup reference, xul {many elements on this page are wrongly marked as deprecated, this page needs review} 423 dynami
cally modifying xul-based user interface add-ons, dom, extensions, xul this article discusses manipulating xul interfaces, using dom and other apis.
... it explains the concept of dom documents, demonstrates a few simple examples of using dom
calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods.
...typi
cally, the value will be a uri that identifies the location of the data.
...And 17 more matches
NSS API Guidelines
the functions in these apis should never
call api layers above them.
...specifi
cally, this library provides nss_init() for establishing default certificate, key, module databases, and initializing a default random number generator.
...
callback functions, and functions used in function tables, should have a typedef used to define the complete signature of the given function.
...And 17 more matches
nsITreeView
inherits from: nsisupports last changed in gecko 22 (firefox 22 / thunderbird 22 / seamonkey 2.19) implementing a nsitreeview in lieu of dom methods for tree creation can improve performance dramati
cally, and removes the need to make changes to the tree manually when changes to the database occur.
... cyclecell()
called on the view when a cell in a non-selectable cycling column (for example, unread/flag/and so on.) is clicked.
... cycleheader()
called on the view when a header is clicked.
...And 17 more matches
Choosing the right approach - Learn web development
asynchronous
callbacks generally found in old-style apis, involves a function being passed into another function as a parameter, which is then invoked when an asynchronous operation has been completed, so that the
callback can in turn do something with the result.
... 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.ap...
...pendchild(image); } loadasset('coffee.jpg', 'blob', displayimage); pitfalls nested
callbacks can be cumbersome and hard to read (i.e.
...And 16 more matches
Client-side storage - Learn web development
saving data and assets lo
cally so a site will be quicker (and potentially less expensive) to download, or be usable without a network connection.
... saving web application generated documents lo
cally for use offline often client-side and server-side storage are used together.
... next, note how our html references a javascript file
called index.js (see line 40).
...And 16 more matches
Package management basics - Learn web development
a bundle is the term that’s generally used to refer to a single file on your web server that contains all the javascript for your software — typi
cally compressed as much as possible to help reduce the time it takes to get your software downloaded and displayed in your visitors’ browser.
...as we touched on in the previous article, dependencies can be installed globally or lo
cally to your project.
... although there tend to be more pros for installing globally, the pros for installing lo
cally are more important — such as code portability and version locking.
...And 16 more matches
Gecko Profiler FAQ
to stop the profiler from gathering more samples after the “startup end” marker that you’re interested in, you can
call services.profiler.pause(); or you can insert a marker with a special string and then write a script that filters out all samples that were gathered after your marker.
...the only way that i’ve tried before is to use a “difference
calltree”: in the regular
call tree, each node of the
calltree is assigned a weight which is just the number of samples that were under this
call stack.
... in a difference
call tree, each node’s weight instead is computed as <number of samples under this stack in the “after” profile> minus <number of samples under this stack in the “before” profile>.
...And 16 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 javascript, unlike java, the method by itself is an object and can be evaluated as well as being
called.
...for example, the following code actually
calls the file object's getname and isdirectory methods.
... js> f.name test.txt js> f.directory false
calling overloaded methods the process of choosing a method to
call based upon the types of the arguments is
called overload resolution.
...And 16 more matches
Waterfall - Firefox Developer Tools
recorded operations,
called markers, are shown as horizontal bars, laid out in a waterfall to reflect the serial nature of the browser's execution.
... javascript functions executed in the page are labeled with the reason the function was
called: script tag setinterval settimeout requestanimationframe promise
callback promise init worker javascript uri event handler stack
call stack, with links to functions.
... stack
call stack, with links to functions.
...And 16 more matches
Geometry and reference spaces in WebXR - Web APIs
the webgl coordinates and lengths are transformed automati
cally at render time to the size of the viewport in which the scene is being rendered.
...as such the time is typi
cally in alignment with the refresh rate of the display, or some fraction thereof if the frame rate needs to be constrained due to performance issues.
... a space will typi
cally have foreground, mid-distance, and background elements.
...And 16 more matches
HTML documentation index - HTML: Hypertext Markup Language
4 block-level elements beginner, development, guide, html, html5, web html (hypertext markup language) elements histori
cally were categorized as either "block-level" elements or "inline-level" elements.
... 9 autocapitalize autocapitalize, global attributes, html, reference the autocapitalize global attribute is an enumerated attribute that controls whether and how text input is automati
cally capitalized as it is entered/edited by the user.
... 13 data-* global attributes, html, reference the data-* global attributes form a class of attributes
called custom data attributes, that allow proprietary information to be exchanged between the html and its dom representation by scripts.
...And 16 more matches
JavaScript modules - JavaScript
note: if you want to download the examples and run them lo
cally, you'll need to run them through a local web server.
... basic example structure in our first example (see basic-modules) we have a file structure as follows: index.html main.js modules/ canvas.js square.js note: all of the examples in this guide have basi
cally the same structure; the above should start getting pretty familiar.
...to import the main.js script, we use this: <script type="module" src="main.js"></script> you can also embed the module's script directly into the html file by placing the javascript code within the body of the <script> element: <script type="module"> /* javascript module code here */ </script> the script into which you import the module features basi
cally acts as the top-level module.
...And 16 more matches
FinalizationRegistry - JavaScript
a finalizationregistry object lets you request a
callback when an object is garbage-collected.
... description finalizationregistry provides a way to request that a cleanup
callback get
called at some point when an object registered with the registry has been reclaimed (garbage-collected).
... (cleanup
callbacks are sometimes
called finalizers.) note: cleanup
callbacks should not be used for essential program logic.
...And 16 more matches
Using custom elements - Web Components
so for example, we can define a custom word-count element like this: customelements.define('word-count', wordcount, { extends: 'p' }); the element is
called word-count, its class object is wordcount, and it extends the <p> element.
...for example, wordcount is structured like so: class wordcount extends htmlparagraphelement { constructor() { // always
call super first in constructor super(); // element functionality written in here ...
...it is possible to define specific lifecycle
callbacks inside the class, which run at specific points in the element's lifecycle.
...And 16 more matches
passwords - Archive of obsolete content
typi
cally a credential consists of a username and a password.
... you don't supply this value when storing an add-on credential: it is automati
cally generated for you.
...ted authentication with a response code like this: http/1.0 401 authorization required server: apache/1.3.27 www-authenticate: basic realm="exampleco login" the corresponding values for the credential (excluding username and password) should be: url: "http://www.example.com" realm: "exampleco login" oncomplete and onerror this api is explicitly asynchronous, so all its functions take two
callback functions as additional options: oncomplete and onerror.
...And 15 more matches
More Event Handlers - Archive of obsolete content
re
call that the capturing phase occurs before the bubbling phase, so any capturing listeners will trigger before any bubbling listeners.
...to manually stop event propagation,
call the event object's stoppropagation method, as in the following example.
...the stoppropagation method has been
called in the box's listener, so the button's listener never gets
called.
...And 15 more matches
Index - Learn web development
beginner, infrastructure, navigation, needsactivelearning hyperlinks, usually
called links, are a foundational concept behind the web.
...for example, this css selects paragraph text, setting the color to red: 38 dealing with files beginner, codingscripting, files, guide, html, l10n:priority, theory, website when you are working on a website lo
cally on your computer, you should keep all the related files in a single folder that mirrors the published website's file structure on the server.
...a website can do basi
cally anything, but, for your first try, you should keep things simple.
...And 15 more matches
Command line crash course - Learn web development
macos macos has a system
called darwin that sits underneath the graphical user interface.
... windows has traditionally had its own terminal-like program
called cmd (“the command prompt”) for a long time, but this definitely doesn’t have parity with unix commands, and is equivalent to the old-style windows dos prompt.
...techni
cally, a terminal is software that starts and connects to a shell.
...And 15 more matches
Displaying Places information using views
for more complicated queries or queries whose uris you plan on changing, you will want to set the view's place property dynami
cally using javascript.
... note that in the latter case it is not sufficient to
call setattribute on the element; use the element's place property instead.
... when a view's underlying data changes, the view will automati
cally update itself so that it displays the new data.
...And 15 more matches
Promise
a reference to an existing promise may be received by different means, for example as the return value of a
call into an asynchronous api.
... once you have a reference to a promise, you can
call its then() method to execute an action when the value becomes available, or when an error occurs.
... note:
calling this method with a pending promise as the avalue argument, and then
calling it again with another value before the promise is fulfilled or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise.
...And 15 more matches
pkfnc.html
wincx a pointer to application data for the password
callback function.
...when you are finished with the certificate structure returned by pk11_findcertfromnickname, you must free it by
calling cert_destroycertificate.
... the pk11_findcertfromnickname function
calls the password
callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter.
...And 15 more matches
JSClass
eop enumerate; jsresolveop resolve; jsconvertop convert; /* obsolete since spidermonkey 44 */ /* optional since spidermonkey 25 */ jsfinalizeop finalize; /* optional */ jsclassinternal reserved0; /* obsolete since spidermonkey 13 */ jscheckaccessop checkaccess; /* obsolete since spidermonkey 29 */ jsnative
call; jshasinstanceop hasinstance; jsnative construct; jsxdrobjectop xdrobject; /* obsolete since spidermonkey 13 */ jstraceop trace; /* added in spidermonkey 17 */ jsclassinternal reserved1; /* obsolete since spidermonkey 13 */ void *reserved[n]; /* sizeof 'reserved' depends on version */ }; name typ...
... addproperty jspropertyop a hook
called just after adding a new property.
... delproperty jsdeletepropertyop a hook
called when deleting a property.
...And 15 more matches
Building the WebLock UI
specifi
cally, the user interface we create in this chapter will be overlaid into the statusbar of the browser component, where it will provide a small icon the user can click to access the web lock interface.
...a boolean wlocked variable can do this: // initialize the wlocked variable as unlocked var wlocked = 0; then the functions that get
called from the interface and
call through to the lock and unlock methods of the weblock component must also adjust this variable accordingly: function wlock() { // check to see if locking is on or off weblock.lock(); wlocked = 1; } function wunlock() { // check to see if locking is on or off weblock.unlock(); wlocked = 0; } an important preliminary of these functions is that the weblo...
...this section describes the functions that are
called from the interface and how they interact with the weblock component.
...And 15 more matches
Using XPCOM Utilities to Make Things Easier
some differ only in whether or not a method is
called when the module is created and/or destroyed.
... ns_impl_nsgetmodule_with_ctor(name, components, ctor) same as above but allows for a special function to be
called when the module is created.
... ns_impl_nsgetmodule_with_dtor(name, components, dtor) same as the first macro but allows for a special function to be
called when the module is destroyed.
...And 15 more matches
mozIStorageConnection
method overview void asyncclose([optional] in mozistoragecompletion
callback a
callback); void begintransaction(); void begintransactionas(in print32 transactiontype); mozistoragestatement clone([optional] in boolean areadonly); void close(); void committransaction(); void createaggregatefunction(in autf8string afunctionname, in long anumarguments, in mozistorageaggregatefunction afunction); mozistorage...
... in long anumarguments, in mozistoragefunction afunction); mozistoragestatement createstatement(in autf8string asqlstatement); void createtable(in string atablename, in string atableschema); mozistoragependingstatement executeasync([array, size_is(anumstatements)] in mozistoragebasestatement astatements, in unsigned long anumstatements, [optional] in mozistoragestatement
callback a
callback ); void executesimplesql(in autf8string asqlstatement); boolean indexexists(in autf8string aindexname); void preload(); obsolete since gecko 1.9 void removefunction(in autf8string afunctionname); mozistorageprogresshandler removeprogresshandler(); void rollbacktransaction(); void setgrowthincrement(in print32 aincreme...
... void asyncclose( in mozistoragecompletion
callback a
callback optional ); parameters a
callback optional an optional
callback handler to be executed when the connection is successfully closed.
...And 15 more matches
Initialization and Destruction - Plugins
initialization: the browser
calls the plug-in api function np_initialize when the plug-in code is first loaded.
... instance creation: the browser
calls the plug-in api function npp_new when the instance is created.
... instance destruction: the plug-in instance is deleted when the user leaves the instance page or closes the instance window; the browser
calls the function npp_destroy to tell the plug-in that the instance is being deleted.
...And 15 more matches
Flame Chart - Firefox Developer Tools
this gives you a way to know exactly which function was executing at any point during the recording, how long it ran for, and where it was
called from.
... the
call tree and the flame chart are both used to analyze your site's javascript, and they both use the same data: a sample of the javascript engine's stack, taken periodi
cally during the recording.
... but while the
call tree organizes this data to show you where your program is spending most time in aggregate across the recording, the flame chart uses it to show you when in the recording particular functions are executing.
...And 15 more matches
lang/functional - Archive of obsolete content
when the method is invoked on an instance of the object, the original function is
called.
...
calling the wrapped version will
call the original function during the next event loop.
... this is similar to
calling settimeout with no wait (i.e.
...And 14 more matches
JavaScript Client API - Archive of obsolete content
all you have to do is write an object that extends cryptowrapper and maintains a property
called cleartext.
... the skeleton of a sample record implementation: function foorecord(collection, id) { cryptowrapper.
call(this, collection, id); } foorecord.prototype = { __proto__: cryptowrapper.prototype, _logname: "record.foo", ttl: foo_ttl, // optional get bar() this.cleartext.bar, set bar(value) { this.cleartext.bar = value; }, get baz() this.cleartext.baz, set baz(value) { this.cleartext.baz = value; } }; to save all that typing for declaring the getters and setters, you can also use utils.defergetset: function foorecord(...
...collection, id) { cryptowrapper.
call(this, collection, id); } foorecord.prototype = { __proto__: cryptowrapper.prototype, _logname: "record.foo", ttl: foo_ttl // optional }; utils.defergetset(foorec, "cleartext", ["bar", "baz"]); the store object the store object (which extends store, as defined in services/sync/modules/engines.js) has the job of creating and maintaining a set of record objects from the underlying data.
...And 14 more matches
Menu - Archive of obsolete content
if the menu is a context menu, it is
called as beforehide(menu, context) and otherwise as beforehide(menu).
...if the menu is a context menu, it is
called as beforeshow(menu, context) and otherwise as beforeshow(menu).
...if no such target exists, the
call silently fails.
...And 14 more matches
Componentizing our Svelte app - Learn web development
first of all, we need to import it — add the following line at the top of the todos.svelte <script> section: import filterbutton from './filterbutton.svelte' now, replace the filters <div> with a
call to the filterbutton component, which takes the current filter as a prop — the below line is all you need: <filterbutton {filter} /> note: remember that when the html attribute name and variable matches, they can be replaced with {variable}, that's why we could replace <filterbutton filter={filter} /> with <filterbutton {filter} />.
...whenever the user clicks on any filter button, the child will
call the onclick handler, passing the selected filter as a parameter, back up to its parent.
... we will just declare the onclick prop assigning a dummy handler to prevent errors, like this: export let onclick = (clicked) => {} and we'll declare the following reactive statement — $: onclick(filter) — to
call the onclick handler whenever the filter variable is updated.
...And 14 more matches
Tracing JIT
the tracing jit in spidermonkey consists of a generic, low level component
called nanojit which is co-maintained between adobe and mozilla, and a spidermonkey-specific high level component
called jstracer.
...the recorder records the activity of the interpreter, using nanojit to build an efficient, native representation of the execution
called a fragment.
... the monitor then
calls into the native code stored in the fragment.
...And 14 more matches
JSAPI Cookbook
but in a jsnative the correct way to do this is: /* jsapi */ bool mynative(jscontext *cx, unsigned argc, js::value *vp) { js::
callargs args = js::
callargsfromvp(argc, vp); jsobject *global = js_getglobalforobject(cx, &args.
callee()); ...
... } defining a function // javascript function justforfun() { return null; } /* jsapi */ bool justforfun(jscontext *cx, unsigned argc, js::value *vp) { js::
callargs args = js::
callargsfromvp(argc, vp); args.rval().setnull(); return true; } ...
...* 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 person = 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.
...And 14 more matches
JSFastNative
syntax typedef jsbool (*jsfastnative)(jscontext *cx, unsigned int argc, jsval *vp); name type description cx jscontext * the context in which the fast native is being
called.
...in js_threadsafe builds, the javascript engine
calls this
callback only from within an active request on cx.
... the
callback does not need to
call js_beginrequest()).
...And 14 more matches
nsIOutputStream
a blocking output stream may suspend the
calling thread in order to satisfy a
call to close(), flush(), write(), writefrom(), or writesegments().
... a non-blocking output stream, on the other hand, must not block the
calling thread of execution.
... note: this method may be
called more than once, but subsequent
calls are ignored.
...And 14 more matches
Using js-ctypes
this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can
call the ctypes.open() method to load each native library you wish to use.
...instead, you'll need to create a shim library that uses c functions that then
call into the c++ library for you.
... examples can be found here: bugzilla :: bug 505907 - support c++
calling from jsctypes library search paths if you specify a full path, that path is used to load the library.
...And 14 more matches
Mozilla
toolbars, menu bars, progress bars, and window title bars are all examples of elements that are typi
cally part of the chrome.
... creating javascript
callbacks in components xpcom components use idl to create interfaces.
...basi
cally, the component defines an observer (or listener) interface which is implemented by some external code and this implementation is passed to the component.
...And 14 more matches
URLs - Plugins
note that npn_geturl is typi
cally asynchronous: it returns immediately and only later handles the request, such as displaying the url or creating the stream for the instance and writing the data.
... for this reason as well,
calling npn_geturlnotify may be more useful than npn_geturl; the plug-in is notified upon either successful or unsuccessful completion of the request.
...if the target parameter is set to null, the application creates a new stream and delivers the data to the plug-in instance, through
calls to npp_newstream, npp_writeready and npp_write, and npp_destroystream.
...And 14 more matches
RTCPeerConnection.setRemoteDescription() - Web APIs
this is typi
cally
called after receiving an offer or answer from another peer over the signaling server.
... keep in mind that if setremotedescription() is
called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions).
... because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by
calling setremotedescription() does not immediately take effect.
...And 14 more matches
Using Service Workers - Web APIs
if successful, the service worker is executed in a serviceworkerglobalscope; this is basi
cally a special kind of worker context, running off the main script execution thread, with no dom access.
... promises can do a variety of things, but all you need to know for now is that if something returns a promise, you can attach .then() to the end and include
callbacks inside it for success cases, or you can insert .catch() on the end if you want to include a failure
callback.
... let’s compare a traditional synchronous
callback structure to its asynchronous promise equivalent.
...And 14 more matches
Starting up and shutting down a WebXR session - Web APIs
finally, you must
call requestsession() from a user event handler, such as the handler for the click event.
... to find out if a given mode is supported, simply
call the xrsystem method issessionsupported().
...to obtain an xrsession, you
call your xrsystem's requestsession() method, which returns a promise that resolves with an xrsession if it's able to establish one successfully.
...And 14 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
line-breaks are automati
cally removed from the input value.
...line-breaks are automati
cally removed from the input value.
...since every <input> element, regardless of type, is based on the htmlinputelement interface, they techni
cally share the exact same set of attributes.
...And 14 more matches
Functions - JavaScript
generally speaking, a function is a "subprogram" that can be
called by code external (or internal in the case of recursion) to the function.
... like the program itself, a function is composed of a sequence of statements
called the function body.
...what distinguishes them from other objects is that functions can be
called.
...And 14 more matches
Array.prototype.reduce() - JavaScript
syntax arr.reduce(
callback( accumulator, currentvalue, [, index[, array]] )[, initialvalue]) parameters
callback a function to execute on each element in the array (except for the first, if no initialvalue is supplied).
... it takes four arguments: accumulator the accumulator accumulates
callback's return values.
... it is the accumulated value previously returned in the last invocation of the
callback—or initialvalue, if it was supplied (see below).
...And 14 more matches
Array.prototype.forEach() - JavaScript
syntax arr.foreach(
callback(currentvalue [, index [, array]])[, thisarg]) parameters
callback function to execute on each element.
... array optional the array foreach() was
called upon.
... thisarg optional value to use as this when executing
callback.
...And 14 more matches
Promise - JavaScript
when either of these options happens, the associated handlers queued up by a promise's then method are
called.
... if the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be
called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
... not to be confused with: several other languages have mechanisms for lazy evaluation and deferring a computation, which they also
call "promises", e.g.
...And 14 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
automati
cally starting the playback of audio (or videos with audio tracks) immediately upon page load can be an unwelcome surprise to users.
... autoplay and autoplay blocking the term autoplay refers to any feature that causes audio to begin to play without the user specifi
cally requesting that playback begin.
... autoplay availability as a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true: the audio is muted or its volume is set to 0 the user has interacted with the site (by clicking, tapping, pressing keys, etc.) if the site has been whitelisted; this may happen either automati
cally if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features if the autoplay feature policy is used to grant autoplay support to an <iframe> and its document.
...And 14 more matches
Web audio codec guide - Web media technologies
voice frequencies rtp / webrtc g.722 7 khz audio coding within 64 kbps (for telephony/voip) rtp / webrtc mp3 mpeg-1 audio layer iii mp4, adts, mpeg1, 3gp opus opus webm, mp4, ogg vorbis vorbis webm, ogg [1] when mpeg-1 audio layer iii codec data is stored in an mpeg file, and there is no video track on the file, the file is typi
cally referred to as an mp3 file, even though it's still an mpeg format file.
... depends on the codec; codecs typi
cally have an internal sample format that may or may not be the same as the original sample size.
... the effect of codec configuration on encoded audio output audio codecs typi
cally employ cleverly-designed and highly-complex mathematical algorithms to take source audio data and compress it to take substantially less space in memory or network bandwidth.
...And 14 more matches
Compiling from Rust to WebAssembly - WebAssembly
this installs a tool
called "rustup", which lets you manage multiple versions of rust.
...this is added automati
cally, but you must restart your terminal for it to take effect.
... using wasm-bindgen to communicate between rust and javascript the first part looks like this: use wasm_bindgen::prelude::*; libraries are
called "crates" in rust.
...And 14 more matches
platform/xpcom - Archive of obsolete content
implementing xpcom interfaces this module exports a class
called unknown which implements the fundamental xpcom interface nsisupports.
...ster() { observerservice.addobserver(this, this.topic, false); }, unregister: function() { observerservice.removeobserver(this, this.topic); }, observe: function observe(subject, topic, data) { console.log('star observer:', subject, topic, data); } }); var starobserver = starobserver(); starobserver.register(); implementing xpcom factories the xpcom module exports a class
called factory which implements the nsifactory interface.
... for example, this add-on defines a subclass of unknown
called helloworld that implements a function
called hello.
...And 13 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
chrome url use a file
called a “chrome manifest” to register chrome packages with firefox and start using them.
... to register a package, you use a special uri scheme
called a “chrome url” to represent the path to the file.
...it is also possible to coerce an overlay without using the xul-overlay instruction in the xul document—this is
called a “cross-package overlay” (figure 2).
...And 13 more matches
NPP_NewStream - Archive of obsolete content
stream supports random access through
calls to npn_requestread (for example, local files or http servers that support byte-range requests).
... np_normal (default): delivers stream data to the instance in a series of
calls to npp_writeready and npp_write.
... np_seek: stream data randomly accessible by the plug-in as needed, through
calls to npn_requestread.
...And 13 more matches
Old Proxy API - Archive of obsolete content
there are two kinds of proxies: object proxies var proxy = proxy.create(handler, proto); and function proxies : var proxy = proxy.createfunction(handler,
calltrap, constructtrap); where: proto is an optional object representing the proxy’s prototype (defaults to null if none is provided).
...
calltrap is a variable-argument function(args) { return any; } that reifies “proxy(args)”.
... note: the this-binding of the
calltrap function is the this-binding of the
call-site.
...And 13 more matches
How to build custom form controls - Learn web development
this process is
called ux design.
... list of options will always be on top of the down arrow */ /* this will reset the default style of the ul element */ list-style: none; margin : 0; padding: 0; box-sizing : border-box; /* if the values are smaller than the control, the list of options will be as wide as the control itself */ min-width : 100%; /* in case the list is too long, its content will overflow verti
cally (which will add a vertical scrollbar automati
cally) but never horizontally (because we haven't set a width, the list will adjust its width automati
cally.
... .widget select, .no-widget .select { /* this css selector basi
cally says: - either we have set the body class to "widget" and thus we hide the actual <select> element - or we have not changed the body class, therefore the body class is still "no-widget", so the elements whose class is "select" must be hidden */ position : absolute; left : -5000em; height : 0; overflow : hidden; } this css visually hides one of the elements, but it...
...And 13 more matches
Making asynchronous programming easier with async and await - Learn web development
previous overview: asynchronous next more recent additions to the javascript language are async functions and the await keyword, part of the so-
called ecmascript 2017 javascript edition (see ecmascript next support in mozilla).
... these features basi
cally act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards.
... you can also create an async function expression, like so: let hello = async function() { return "hello" }; hello(); and you can use arrow functions: let hello = async () => { return "hello" }; these all do basi
cally the same thing.
...And 13 more matches
Using the Places history service
this information is
called a "visit" in this document and in the code.
... adding pages to history nsiglobalhistory2.adduri: this is the basic function for adding pages to history that is
called by the docshell as you browse.
... nsiglobalhistory3.adddocumentredirect: this is
called by the docshell when a redirect occurs.
...And 13 more matches
nsINavHistoryObserver
note: the page does not necessarily have to have ever existed for this function to be
called.
...you should avoid doing any heavy-duty processing until onendupdatebatch() is
called.
...onclearhistory()
called just prior to all of history being cleared.
...And 13 more matches
nsIWebProgressListener
for any given request, onstatechange() is
called once with the state_start flag, zero or more times with the state_transferring flag or once with the state_redirecting flag, and then finally once with the state_stop flag.
...the request is complete when onstatechange() is
called for the same request with the state_stop flag set.
...when a redirect occurs, a new request is generated automati
cally to process the new request.
...And 13 more matches
Debugger - Firefox Developer Tools
the debugger object when
called as a constructor, the debugger object creates a new debugger instance.
... uncaughtexceptionhook either null or a function that spidermonkey
calls when a
call to a debug event handler, breakpoint handler, or similar function throws some exception, which we refer to asdebugger-exception here.
... exceptions thrown in the debugger are not propagated to debuggee code; instead, spidermonkey
calls this function, passingdebugger-exception as its sole argument and the debugger instance as the this value.
...And 13 more matches
Drawing shapes with canvas - Web APIs
the clearrect() function then erases a 60x60 pixel square from the center, and then strokerect() is
called to create a rectangular outline 50x50 pixels within the cleared square.
... the first step to create a path is to
call the beginpath().
...every time this method is
called, the list is reset and we can start drawing new shapes.
...And 13 more matches
console - Web APIs
the specifics of how it works varies from browser to browser, but there is a de facto set of features that are typi
cally provided.
... console.count() log the number of times this line has been
called with the given label.
...to move back out a level,
call groupend().
...And 13 more matches
FileSystemDirectoryEntry.getDirectory() - Web APIs
the filesystemdirectoryentry interface's method getdirectory() returns a filesystemdirectoryentry object corresponding to a directory contained somewhere within the directory subtree rooted at the directory on which it's
called.
... syntax filesystemdirectoryentry.getdirectory([path][, options][, success
callback][, error
callback]); parameters path optional a usvstring representing an absolute path or a path relative to the directory on which the method is
called, describing which directory entry to return.
... success
callback optional a method to be
called once the filesystemdirectoryentry has been created.
...And 13 more matches
FileSystemDirectoryEntry.getFile() - Web APIs
} the filesystemdirectoryentry interface's method getfile() returns a filesystemfileentry object corresponding to a file contained somewhere within the directory subtree rooted at the directory on which it's
called.
... syntax filesystemdirectoryentry.getfile([path][, options][, success
callback][, error
callback]); parameters path optional a usvstring specifying the path, relative to the directory on which the method is
called, describing which file's entry to return.
... success
callback optional a method to be
called once the filesystemfileentry has been created.
...And 13 more matches
HTMLBodyElement - Web APIs
windoweventhandlers.onafterprint is an eventhandler representing the code to be
called when the afterprint event is raised.
... windoweventhandlers.onbeforeprint is an eventhandler representing the code to be
called when the beforeprint event is raised.
... windoweventhandlers.onbeforeunload is an eventhandler representing the code to be
called when the beforeunload event is raised.
...And 13 more matches
PaymentRequest.show() - Web APIs
it may only be
called while handling events that represent user interactions, such as click, keyup, or the like.
...once one paymentrequest's show() method has been
called, any other
call to show() will by rejected with an aborterror until the returned promise has been concluded, either by being fulfilled with a paymentresponse indicating the results of the payment request, or by being rejected with an error.
... if your architecture doesn't necessarily have all of the data ready to go at the moment it instantiates the payment interface by
calling show(), specify the detailspromise parameter, providing a promise that is fulfilled once the data is ready.
...And 13 more matches
Using writable streams - Web APIs
as a javascript developer, programmati
cally writing data to a stream is very useful!
... the first object can contain up to four members, all of which are optional: start(controller) — a method that is
called once, immediately after the writablestream is constructed.
... 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).
...And 13 more matches
Taking still photos with WebRTC - Web APIs
yid('photo'); startbutton = document.getelementbyid('startbutton'); get the media stream the next task is to get the media stream: navigator.mediadevices.getusermedia({ video: true, audio: false }) .then(function(stream) { video.srcobject = stream; video.play(); }) .catch(function(err) { console.log("an error occurred: " + err); }); here, we're
calling mediadevices.getusermedia() and requesting a video stream (without audio).
... it returns a promise which we attach success and failure
callbacks to.
... the success
callback receives a stream object as input.
...And 13 more matches
Example and tutorial: Simple synth keyboard - Web APIs
we will be programmati
cally constructing the keyboard, because doing so gives us the flexibility to configure each key as we determine the appropriate data for the corresponding note.
... in our case, we get each key's frequency from a table, but it could be calculated algorithmi
cally as well.
...the range element will typi
cally be presented as a slider control; we configure it to allow any value between 0.0 and 1.0, stepping by 0.01 each position.
...And 13 more matches
Web Authentication API - Web APIs
in their most basic forms, both create() and get() receive a very large random number
called a challenge from the server and they return the challenge signed by the private key back to the server.
... authenticator - the credentials are created and stored in a device
called an authenticator.
...note most javascript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is
called and subsequently returns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means.
...And 13 more matches
WindowEventHandlers - Web APIs
windoweventhandlers.onafterprint is an eventhandler representing the code to be
called when the afterprint event is raised.
... windoweventhandlers.onbeforeprint is an eventhandler representing the code to be
called when the beforeprint event is raised.
... windoweventhandlers.onbeforeunload is an eventhandler representing the code to be
called when the beforeunload event is raised.
...And 13 more matches
Accessibility documentation index - Accessibility
7 aria live regions aria, accessibility, arialive using javascript, it is possible to dynami
cally change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction.
...aria live regions fill this gap and provide a way to programmati
cally expose dynamic content changes in a way that can be announced by assistive technologies.
... 11 multipart labels: using aria for labels with embedded fields inside them aria, accessibility, ben millard, firefox, guide, help, html, html 4, jaws, needscontent, aria-labelledby, label, solution, trouble shoot, troubleshoot the solution is in an aria attribute
called aria-labelledby.
...And 13 more matches
Array.prototype.reduceRight() - JavaScript
syntax arr.reduceright(
callback(accumulator, currentvalue[, index[, array]])[, initialvalue]) parameters
callback function to execute on each value in the array, taking four arguments: accumulator the value previously returned in the last invocation of the
callback, or initialvalue, if supplied.
... arrayoptional the array reduceright() was
called upon.
... initialvalueoptional value to use as accumulator to the first
call of the
callback.
...And 13 more matches
Array.prototype.some() - JavaScript
syntax arr.some(
callback(element[, index[, array]])[, thisarg]) parameters
callback a function to test for each element, taking three arguments: element the current element being processed in the array.
... arrayoptional the array some() was
called upon.
... thisargoptional a value to use as this when executing
callback.
...And 13 more matches
String - JavaScript
string literals can be specified using single or double quotes, which are treated identi
cally, or using the backtick character `.
...(the same is true of boolean and numbers.) string literals (denoted by double or single quotes) and strings returned from string
calls in a non-constructor context (that is,
called without using the new keyword) are primitive strings.
... javascript automati
cally converts primitives to string objects, so that it's possible to use string object methods for primitive strings.
...And 13 more matches
Codecs used by WebRTC - Web media technologies
unless the sdp specifi
cally signals otherwise, the web browser receiving a webrtc video stream must be able to handle video at at least 20 fps at a minimum resolution of 320 pixels wide by 240 pixels tall.
...cb is a subset of the main profile, and is specifi
cally designed for low-complexity, low-delay applications such as mobile video and videoconferencing, as well as for platforms with lower performing video processing capabilities.
... other audio codecs codec name browser compatibility g.722 chrome, firefox, safari ilbc[1] chrome, safari isac[2] chrome, safari [1] internet low bitrate codec (ilbc) is an open-source narrow-band codec developed by global ip solutions and now google, designed specifi
cally for streaming voice audio.
...And 13 more matches
ui/button/action - Archive of obsolete content
you can generate click events programmati
cally with the button's click() method.
...to set state like this,
call state() with 2 parameters: the first parameter is a window or tab object or as a shorthand, the string "window" for the currently active window, or the string "tab" for the currently active tab the second parameter is an object containing the state properties you wish to update.
...w: var { actionbutton } = require("sdk/ui/button/action"); var button = actionbutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: disableforthiswindow }); function disableforthiswindow(state) { button.state("window", { disabled: true }); } to fetch the state for a specific window or tab,
call state(), passing in the window or tab you are interested in, and it will return the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state().
...And 12 more matches
StringView - Archive of obsolete content
rawsuboffset) - nrawsuboffset : 0; } else { nrawsuboffset = nsuboffset; nrawsublen = nsublen; } if (this.encoding === "utf-16") { nrawsuboffset <<= 1; } else if (this.encoding === "utf-32") { nrawsuboffset <<= 2; } return new stringview(this.buffer, this.encoding, this.rawdata.byteoffset + nrawsuboffset, nrawsublen); }; stringview.prototype.foreachchar = function (f
callback, othat, nchroffset, nchrlen) { var asource = this.rawdata, nrawend, nrawidx; if (this.encoding === "utf-8" || this.encoding === "utf-16") { var fgetinptchrsize, fgetinptchrcode; if (this.encoding === "utf-8") { fgetinptchrsize = stringview.getutf8charlength; fgetinptchrcode = stringview.loadutf8charcode; } else if (this.encoding === "utf-16") { fgetinptch...
...this.makeindex(nchrlen, nrawidx) : asource.length; for (var nchrcode, nchridx = 0; nrawidx < nrawend; nchridx++) { nchrcode = fgetinptchrcode(asource, nrawidx); if (!othat) { f
callback(nchrcode, nchridx, nrawidx, asource); } else { f
callback.
call(othat, nchrcode, nchridx, nrawidx, asource); } nrawidx += fgetinptchrsize(nchrcode); } } else { nrawidx = isfinite(nchroffset) ?
...nchrlen + nrawidx : asource.length; for (nrawidx; nrawidx < nrawend; nrawidx++) { if (!othat) { f
callback(asource[nrawidx], nrawidx, nrawidx, asource); } else { f
callback.
call(othat, asource[nrawidx], nrawidx, nrawidx, asource); } } } }; stringview.prototype.valueof = stringview.prototype.tostring = function () { if (this.encoding !== "utf-8" && this.encoding !== "utf-16") { /* ascii, utf-32 or binarystring to domstring */ return string.fromcharcode.apply(null, this.rawdata); } var fgetcode, fgetincr, sview = ""; if (this.encoding === "utf-8") { fgetincr = stringview.getutf8charlength; fgetcode = stringview.loadutf8charcode; } else if (this.encoding === "utf-16") { ...
...And 12 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
because html was originally conceived as a language for marking up documents, specifi
cally web pages, it is inevitably lacking in functionality for marking up applications.
...as shown in listing 3, elements can be laid out horizontally using the hbox (horizontal box) element or verti
cally using the vbox (vertical box) element.
... orient whether a box's contents will be verti
cally or horizontally arrayed depends on the elements in their initial state.
...And 12 more matches
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
the final goal is to find the correct stream listener to pump the data into when necko
calls ondataavailable (e.g., we may find the html parser as the stream listener to give the data to).
...main roles nsdocshell this class corresponds, basi
cally, to a "window" object in javascript -- each frame, iframe, content area, tab, etc has its own docshell.
...there is basi
cally one of these per load (though see the section on stream converters).
...And 12 more matches
Venkman Introduction - Archive of obsolete content
the javascript debugger, also
called venkman, has been a part of the mozilla browser and the community of web and script developers there for some time.
...features such as breakpoint management,
call stack inspection, and variable/object inspection are available from the user interface and from console commands, letting you work in the way you are most accustomed to.
... starting the debugger the javascript debugger is automati
cally pre-installed in mozilla 1.x but must be installed separately in firefox and other gecko-based products, such as thunderbird and netscape 7.x.
...And 12 more matches
Tree View Details - Archive of obsolete content
the tree will query the view for each row by
calling its getlevel method to find out the level of that row.
...this function is used, specifi
cally, to draw the nesting lines along the side of the tree.
...the tree will
call this method to determine which containers are open and which are closed.
...And 12 more matches
NPClass - Archive of obsolete content
lidatefunctionptr invalidate; nphasmethodfunctionptr hasmethod; npinvokefunctionptr invoke; npinvokedefaultfunctionptr invokedefault; nphaspropertyfunctionptr hasproperty; npgetpropertyfunctionptr getproperty; npsetpropertyfunctionptr setproperty; npremovepropertyfunctionptr removeproperty; npenumerationfunctionptr enumerate; npconstructfunctionptr construct; }; warning: don't
call these routines directly.
...
called by npn_createobject() if non-null, otherwise the browser
calls malloc().
... deallocate
called by npn_releaseobject() when an object's reference count reaches zero.
...And 12 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
to get a driver's license, you typi
cally apply to a government agency, such as the department of motor vehicles, which verifies your identity, your ability to drive, your address, and other information before issuing the license.
... network interactions typi
cally take place between a client, such as browser software running on a personal computer, and a server, such as the software and hardware used to host a web site.
... 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, typi
cally on separate servers.
...And 12 more matches
Plug-in Development Overview - Gecko Plugin API Reference
to see your plug-in in action, simply display the html page that
calls it in the browser.
... to determine the mime types and file extensions that the plug-in handles, the browser loads each library and
calls into the np_getmimedescription entry point.
... npp_getvalue is
called after the plug-in is initialized to get the scripting interface while np_getvalue is
called during initialization to retrieve the plug-in's name and description, which will appear in the navigator.plugins dom object which is used to populate about:plugins.
...And 12 more matches
A first splash into JavaScript - Learn web development
variables are basi
cally containers for values (such as numbers, or strings of text).
...inside the curly braces goes all the code that we want to run whenever we
call the function.
...then go into the developer tools javascript console, and enter the following line: checkguess(); after pressing return/enter, you should see an alert come up that says "i am a placeholder"; we have defined a function in our code that creates an alert whenever we
call it.
...And 12 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 lo
cally to begin with.
... basic setup: create a new file
called main.js, in the same directory as your index.html file.
...in addition you've got a function
called randomvaluefromarray() that takes an array, and returns one of the items stored inside the array at random.
...And 12 more matches
Mozilla accessibility architecture
we
call these objects "accessible nodes".
...for example, nsaccessiblewrap implements the methods in iaccessible, but because it is also an nsaccessible, it only needs to
call the nsiaccessible methods in "this" to get at the information it needs.
...this tree traversal is accomplished via toolkit-specific
calls which end up as
calls into nsiaccessible methods getaccparent(), getaccnextsibling(), getaccprevioussibling(), getaccfirstchild(), getacclastchild(), getaccchildcount() and getchildat(childnum).
...And 12 more matches
Error codes returned by Mozilla APIs
the following tables list errors that can occur when
calling various mozilla apis.
...an error will typi
cally be displayed on the error console, but can be captured using a try-catch block in javascript.
...these components usually provide an initialization method, often
called init, which must be
called before other methods are used.
...And 12 more matches
InstallListener
iled(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) void 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.
... only
called for add-ons that need to be downloaded.
...And 12 more matches
SpiderMonkey Internals
a js-to-js function
call pushes a javascript stack frame without growing the c stack.
... but since js-to-c-to-js
call stacks are common, the interpreter is reentrant.
...it translates postfix bytecode into infix source by consulting a separate byte-sized code,
called source notes, to disambiguate bytecodes that result from more than one grammatical production.
...And 12 more matches
JSNative
jsnative is the type of many jsapi
callbacks.
... in particular, apis such as js_initclass and js_definefunctions create custom methods on javascript objects that are implemented as jsnative
callbacks provided by the application, written in c/c++ code.
... syntax typedef bool (* jsnative)(jscontext *cx, unsigned argc, js::value *vp); name type description cx jscontext * the context in which the native function is being
called.
...And 12 more matches
JS_THREADSAFE
requests must be bracketed with
calls to js_beginrequest() and js_endrequest().
... most jsapi functions require the
caller to be in a request.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...And 12 more matches
Component Internals
it gets
called during registration and unregistration of the component, and when xpcom wants to discover what interfaces or classes the module/library implements.
... components reside in modules, and those modules are defined in shared library files that typi
cally sit in the components directory of an xpcom application.
... xpcom initialization to understand why and when your component library gets
called, it is important to understand the xpcom initalization process.
...And 12 more matches
nsIEditorSpellCheck
checkcurrentdictionary()
call this after any change in installed dictionaries to ensure that the spell checker is not using a current dictionary which is no longer available.
... note: this does not clear any suggestions left over from previous
calls to checkcurrentword(), so there may be suggestions, but they will be invalid.
...typi
cally, this is an iso language code, such as "en-us".
...And 12 more matches
nsIXPConnect
nsistackframe createstackframelocation(in pruint32 alanguage, in string afilename, in string afunctionname, in print32 alinenumber, in nsistackframe a
caller); void debugdump(in short depth); void debugdumpevalinjsstackframe(in pruint32 aframenumber, in string asourcetext); void debugdumpjsstack(in prbool showargs, in prbool showlocals, in prbool showthisprops); void debugdumpobject(in nsisupports acomobj, in short depth); [noscript,notxpcom] prbool definedomquickstubs(in jscontextptr cx, in jsobjectptr p...
... void flagsystemfilenameprefix(in string afilenameprefix, in prbool awantnativewrappers); void garbagecollect(); [noscript,notxpcom] void get
caller(out jscontextptr ajscontext, out jsobjectptr aobject); jsval getcowforobject(in jscontextptr ajscontext, in jsobjectptr aparent, in jsobjectptr awrappedobj); native code only!
...al, 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 jsobjectptr anewscope); [noscript,notxpcom] void notejscontext(in jscontextptr ajscontext, in nscctraversal
callbackref acb); void releasejscontext(in jscontextptr ajscontext, in prbool nogc); void removejsholder(in voidptr aholder); native code only!
...And 12 more matches
nsIXULTemplateBuilder
the nsitemplatebuilder interface controls the display of elements using a xul template element and is automati
cally attached to an element containing a datasources attribute.
...a template builder is attached to a single dom node; this node is
called the root node and is expected to contain a xul template element as a direct child.
...the contents of the query are processed by a separate component
called a query processor.
...And 12 more matches
nsIMsgCloudFileProvider
inherits from: nsisupports method overview void init(in string aaccountkey); void uploadfile(in nsilocalfile afile, in nsirequestobserver a
callback); acstring urlforfile(in nsilocalfile afile); void cancelfileupload(in nsilocalfile afile); void refreshuserinfo(in boolean awithui, in nsirequestobserver a
callback); void deletefile(in nsilocalfile afile, in nsirequestobserver a
callback); void createnewaccount(in acstring aemailaddress, in acstring apassword, in acstring afirstname, in acstring alastname, in nsirequestobserver a
callback); void createexistingaccount(in nsire...
...questobserver a
callback); acstring providerurlforerror(in unsigned long aerror); attributes attribute type description type acstring readonly: the type is a unique string identifier which can be used by interface elements for styling.
... this should probably be
called immediately after instantiation.
...And 12 more matches
Plug-in Development Overview - Plugins
to see your plug-in in action, simply display the html page that
calls it in the browser.
... to determine the mime types and file extensions that the plug-in handles, the browser loads each library and
calls into the np_getmimedescription entry point.
... npp_getvalue is
called after the plug-in is initialized to get the scripting interface while np_getvalue is
called during initialization to retrieve the plug-in's name and description, which will appear in the navigator.plugins dom object which is used to populate about:plugins.
...And 12 more matches
Drag Operations - Web APIs
(the default image and drag effects are suitable in most situations.) drag data all drag events have a property
called datatransfer which holds the drag data (datatransfer is a datatransfer object).
...to do this,
call the setdata() method multiple times with different formats.
... you should
call it with formats in order from most specific to least specific.
...And 12 more matches
LocalFileSystem - Web APIs
creating new storage you request access to a sandboxed file system by
calling window.requestfilesystem().
... the argument of a successful
callback is the filesystem object, which has two properties: the name and root of the file system.
... you can
call the method more than once if you want to create two file systems: one that's temporary and one that's persistent.
...And 12 more matches
Adding 2D content to a WebGL context - Web APIs
together, a set of vertex and fragment shaders is
called a shader program.
... the vertex shader must perform the needed transforms on the vertex's position, make any other adjustments or calculations it needs to make on a per-vertex basis, then return the transformed vertex by saving it in a special variable provided by glsl,
called gl_position.
... our vertex shader below receives vertex position values from an attribute we define
called avertexposition.
...And 12 more matches
Concurrency model and the event loop - JavaScript
visual representation stack function
calls form a stack of frames.
... function foo(b) { let a = 10 return a + b + 11 } function bar(x) { let y = 3 return foo(x * y) } console.log(bar(7)) //returns 42 when
calling bar, a first frame is created containing bar's arguments and local variables.
... when bar
calls foo, a second frame is created and pushed on top of the first one containing foo's arguments and local variables.
...And 12 more matches
Grammar and types - JavaScript
in javascript, instructions are
called statements and are separated by semicolons (;).
... this is
called hashbang comment syntax, and is a special comment used to specify the path to a particular javascript engine that should execute the script.
...the names of variables,
called identifiers, conform to certain rules.
...And 12 more matches
Working with objects - JavaScript
object properties are basi
cally the same as ordinary javascript variables, except for the attachment to objects.
...objects are sometimes
called associative arrays, since each property is associated with a string value that can be used to access it.
...this notation is also very useful when property names are to be dynami
cally determined (when the property name is not determined until runtime).
...And 12 more matches
Strict mode - JavaScript
the entire contents of javascript modules are automati
cally in strict mode, with no statement needed to initiate it.
...in normal code the last duplicated argument hides previous identi
cally-named arguments.
...this means that, in general, in a function containing a
call to eval every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable).
...And 12 more matches
Web video codec guide - Web media technologies
some lossless codecs do exist, but they are typi
cally used for archival and storage for local playback rather than for use on a network.
... motion compression of video typi
cally works by comparing frames, finding where they differ, and constructing records containing enough information to update the previous frame to approximate the appearance of the following frame.
...for this and other reasons, the more motion there is in a video, the larger the output file will typi
cally be.
...And 12 more matches
Content Processes - Archive of obsolete content
to communicate between add-on and content processes, the sdk uses something
called content scripts.
...content scripts communicate with add-on code using something
called event emitters.
...content workers combine these ideas, allowing you to inject a content script into a content process, and automati
cally set up a communication channel between them.
...And 11 more matches
Tabbed browser - Archive of obsolete content
of course the entire application firefox is
called "a browser".
... from a sidebar basi
cally, if your extension code is a sidebar you can use: var mainwindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiint...
...erator("navigator:browser"); var tabbrowser = browserenumerator.getnext().gbrowser; // create tab var newtab = tabbrowser.addtab(url); newtab.setattribute(attrname, "xyz"); // focus tab tabbrowser.selectedtab = newtab; // focus *this* browser window in case another one is currently focused tabbrowser.ownerdocument.defaultview.focus(); } } the function can be
called like so: openandreuseonetabperattribute("myextension-myattribute", "http://developer.mozilla.org/").
...And 11 more matches
prefwindow - Archive of obsolete content
normally, you would not set this attribute as it will be set automati
cally such that the default pane is the same as the one showing when the preferences dialog was last closed.
...ef="chrome://global/skin/" type="text/css"?> <prefwindow xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <prefpane id="saveoptions" label="backups"> <preferences> <preference id="pref-backup" name="myapp.mybackups" type="bool"/> <preference id="pref-backupduration" name="myapp.mybackups.duration" type="int"/> </preferences> <checkbox label="automati
cally save backups" preference="pref-backup"/> <textbox label="duration:" preference="pref-backupduration"/> </prefpane> </prefwindow> attributes activetitlebarcolor type: color string specify background color of the window's titlebar when it is active (foreground).
...the buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automati
cally.
...And 11 more matches
NPAPI plugin reference - Archive of obsolete content
browser-side plug-in api this chapter describes methods in the plug-in api that are provided by the browser; these allow
call back to the browser to request information, tell the browser to repaint part of the window, and so forth.
... the names of all of these methods begin with npn_ to indicate that they are implemented by the browser and
called by the plug-in.
... npany
callbackstruct contains information required during embedded mode printing.
...And 11 more matches
Efficient animation for web games - Game development
there are signals at the beginning and end of animations that allow you to attach javascript
callbacks and form a rudimentary form of synchronisation (though there are no guarantees on how promptly these
callbacks will happen).
...requestanimationframe causes the browser to redraw and
call your function before that frame gets to the screen.
...requestanimationframe includes a domhighrestimestamp in its
callback function prototype, which you definitely should use (as opposed to using the date object), as this will be the time the frame began rendering, and ought to make your animations look more fluid.
...And 11 more matches
Inheritance in JavaScript - Learn web development
defining a teacher() constructor function the first thing we need to do is create a teacher() constructor — add the following below the existing code: function teacher(first, last, age, gender, interests, subject) { person.
call(this, first, last, age, gender, interests); this.subject = subject; } this looks similar to the person constructor in many ways, but there is something strange here that we've not seen before — the
call() function.
... this function basi
cally allows you to
call a function defined somewhere else, but in the current context.
... we want the teacher() constructor to take the same parameters as the person() constructor it is inheriting from, so we specify them all as parameters in the
call() invocation.
...And 11 more matches
Creating our first Vue component - Learn web development
along the way, we'll learn about a few important concepts such as
calling components inside other components, passing data to them via props, and saving data state.
... to actually render the todoitem component in the app, you need to go up into your <template> element and
call it as a <to-do-item></to-do-item> element.
...listing props as an object allows you to specify default values, mark props as required, perform basic object typing (specifi
cally around javascript primitive types), and perform simple prop validation.
...And 11 more matches
Embedding Tips
get thensiwebnavigation interface on your webbrowser and
call the loaduri method with the appropriate uri and flags.
...use the
callbacks for after-the-fact cancellation.
... if necessary you may also implement the nsiuricontentlistener::ispreferred(), returning pr_true to ensure you are always the preferred uri handler and are
called no matter what the content type.
...And 11 more matches
NetUtil.jsm
method overview nsiasyncstreamcopier asynccopy(nsiinputstream asource, nsioutputstream asink, [optional] a
callback) void asyncfetch(asource, a
callback) 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 nsiioser...
...both streams are automati
cally closed when the copy operation is completed.
... nsiasyncstreamcopier asynccopy( asource, asink, a
callback ); parameters asource the input stream from which to read the source data.
...And 11 more matches
JS_ReportErrorNumber
syntax void js_reporterrornumber(jscontext *cx, jserror
callback error
callback, void *userref, const unsigned errornumber, ...); void js_reporterrornumberuc(jscontext *cx, jserror
callback error
callback, void *userref, const unsigned errornumber, ...); bool js_reporterrorflagsandnumber(jscontext *cx, unsigned flags, jserror
callback error
callback, void *userref, const unsigned errornumber, ...); bool js_reporterrorflagsandnumberuc(jscontext *cx, unsigned flags, jserror
callback error
callback, void *userref, const unsigned errornumber, ...); void js_reporterrornumber...
...ucarray(jscontext *cx, jserror
callback error
callback, void *userref, const unsigned errornumber, const char16_t **args); // added in spidermonkey 19 name type description cx jscontext * the context in which to report the error.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...And 11 more matches
mozIStorageStatement
ned long aparamindex, in long avalue); void bindint64parameter(in unsigned long aparamindex, in long long avalue); void bindnullparameter(in unsigned long aparamindex); void bindblobparameter(in unsigned long aparamindex, [array,const,size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); mozistoragependingstatement executeasync(mozistoragestatement
callback a
callback); boolean executestep(); boolean step(); void execute(); attributes attribute type description columncount unsigned long number of columns returned.
...to initialize a statement, consumers should
call mozistorageconnection.createstatement().
...you must
call this method on every active statement before you try to
call mozistorageconnection.close().
...And 11 more matches
nsIAsyncInputStream
the
caller must then wait for the stream to have some data to read.
... if the stream implements nsiasyncinputstream, then the
caller can use this interface to request an asynchronous notification when the stream becomes readable or closed (via the asyncwait() method).
...method overview void asyncwait(in nsiinputstream
callback a
callback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult astatus); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the oninputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being
called on the stream or possibly due to some error in the und...
...And 11 more matches
nsIAsyncOutputStream
the
caller must then wait for the stream to become writable.
... if the stream implements nsiasyncoutputstream, then the
caller can use this interface to request an asynchronous notification when the stream becomes writable or closed (via the asyncwait() method).
...method overview void asyncwait(in nsioutputstream
callback a
callback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult reason); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the onoutputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being
called on the stream or possibly due to some error in the...
...And 11 more matches
nsIContentViewer
to create an instance, use: var contentviewer = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsicontentviewer); method overview void clearhistoryentry(); void close(in nsishentry historyentry); void destroy(); [noscript,notxpcom,nostd
call] nsiviewptr findcontainerview(); void getbounds(in nsintrectref abounds); native code only!
... void loadcomplete(in unsigned long astatus); void loadstart(in nsisupports adoc); void move(in long ax, in long ay); void open(in nsisupports astate, in nsishentry ashentry); void pagehide(in boolean isunload); boolean permitunload([optional] in boolean a
callercloseswindow); boolean requestwindowclose(); void resetclosewindow(); void setbounds([const] in nsintrectref abounds); native code only!
... [noscript,notxpcom,nostd
call] void setnavigationtiming(in nsdomnavigationtimingptr atiming); void setpagemode(in boolean apagemode, in nsiprintsettings aprintsettings); void show(); void stop(); void unload(); obsolete since gecko 1.8 attributes attribute type description container nsisupports domdocument nsidomdocument enablerendering boolean obsolete since gecko 2.0 historyentry nsishentry get the history entry that this viewer will save itself into when destroyed.
...And 11 more matches
nsIProtocolProxyService
to access the service use: var pps = 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 nsiprotocolproxy
callback a
callback); 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 nsiprotocolproxyfilter afilter); constants constant value description resolve_non_blocking 1<<0 this flag may be passed to the resolve method to request that it fail instead of block the
calling thread.
...so,
calling resolve without this flag may result in locking up the
calling thread for a lengthy period of time.
...And 11 more matches
Using files from web applications - Web APIs
you can do this by styling the input element with display:none and
calling the click() method on the <input> element.
...dden { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px, 1px, 1px, 1px); } /* separate rule for compatibility, :focus-within is required on modern firefox and chrome */ input.visually-hidden:focus + label { outline: thin dotted; } input.visually-hidden:focus-within + label { outline: thin dotted; } there is no need to add javascript code to
call fileelem.click().
...you can establish your input element or drop zone as discussed previously and have them
call a function such as the handlefiles() function below.
...And 11 more matches
Introduction to the File and Directory Entries API - Web APIs
it can improve performance by letting an app pre-fetch assets in the background and cache lo
cally.
...however, appcache storage isn't lo
cally mutable, and doesn't allow for fine-grained client-side management.
... video game or other apps with lots of media assets the app downloads one or several large tarballs and expands them lo
cally into a directory structure.
...And 11 more matches
HTMLFrameSetElement - Web APIs
windoweventhandlers.onafterprint is an eventhandler representing the code to be
called when the afterprint event is raised.
... windoweventhandlers.onbeforeprint is an eventhandler representing the code to be
called when the beforeprint event is raised.
... windoweventhandlers.onbeforeunload is an eventhandler representing the code to be
called when the beforeunload event is raised.
...And 11 more matches
RTCPeerConnection - Web APIs
the event is sent immediately after the
call setremotedescription() and doesn't wait for the result of the sdp negotiation.onconnectionstatechangethe rtcpeerconnection.onconnectionstatechange property specifies an eventhandler which is
called to handle the connectionstatechange event when it occurs on an instance of rtcpeerconnection.
... this happens whenever the aggregate state of the connection changes.ondatachannel the rtcpeerconnection.ondatachannel property is an eventhandler which specifies a function which is
called when the datachannel event occurs on an rtcpeerconnection.
... this event, of type rtcdatachannelevent, is sent when an rtcdatachannel is added to the connection by the remote peer
calling createdatachannel().onicecandidatethe rtcpeerconnection property onicecandidate property is an eventhandler which specifies a function to be
called when the icecandidate event occurs on an rtcpeerconnection instance.
...And 11 more matches
Streams API concepts - Web APIs
the streams api adds a very useful set of tools to the web platform, providing objects allowing javascript to programmati
cally access streams of data received over the network and process them as desired by the developer.
...examples include a file access operation via a fetch or xhr
call.
... the data is read sequentially in small pieces
called chunks.
...And 11 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
the webxr apis used for implementing augmented and virtual reality is designed specifi
cally to provide the ability to insert a human into a virtual environment.
... in this guide, we'll explore how webxr uses spaces and, more specifi
cally, reference spaces, to track the positions, orientations, and movements of objects and of the user's body in the virtual world.
...this means that most frequently, you'll be using poses within your frame rendering code, which is executed as a
callback from the xrframe method requestanimationframe().
...And 11 more matches
WritableStream.WritableStream() - Web APIs
underlyingsink can contain the following: start(controller) optional this is a method,
called immediately when the object is constructed.
... 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.
...this method will be
called only after previous writes have succeeded, and never after the stream is closed or aborted (see below).
...And 11 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
e; }; color.prototype.getcolor = function getcolor() { if (this.a | 0 === 1) return this.gethexa(); return this.getrgba(); }; /*=======================================================================*/ /*=======================================================================*/ /*========== capture mouse movement ==========*/ var setmousetracking = function setmousetracking(elem,
callback) { elem.addeventlistener('mousedown', function(e) {
callback(e); document.addeventlistener('mousemove',
callback); }); document.addeventlistener('mouseup', function(e) { document.removeeventlistener('mousemove',
callback); }); }; /*====================*/ // color picker class /*====================*/ function colorpicker(node) { this.color = new color(); this.node...
...icker.prototype.inputchangehexa = function inputchangehexa(e) { var value = e.target.value; this.color.sethexa(value); this.setcolor(this.color); }; /*************************************************************************/ // internal pub/sub /*************************************************************************/ colorpicker.prototype.subscribe = function subscribe(topic,
callback) { this.subscribers[topic] =
callback; }; colorpicker.prototype.notify = function notify(topic, value) { if (this.subscribers[topic]) this.subscribers[topic](value); }; /*************************************************************************/ // set picker properties /*************************************************************************/ colorpicker.prototype.setc...
...****/ var setpickermode = function setpickermode(topic, mode) { if (pickers[topic]) pickers[topic].setpickermode(mode); }; var setcolor = function setcolor(topic, color) { if (pickers[topic]) pickers[topic].setcolor(color); }; var getcolor = function getcolor(topic) { if (pickers[topic]) return new color(pickers[topic].color); }; var subscribe = function subscribe(topic,
callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(
callback); }; var unsubscribe = function unsubscribe(
callback) { subscribers.indexof(
callback); subscribers.splice(index, 1); }; var notify = function notify(topic, value) { if (subscribers[topic] === undefined || subscribers[topic].length === 0) return; var color = new color(va...
...And 11 more matches
Getting Started - Developer guides
its predecessor originated in internet explorer as an activex object
called xmlhttp.
...at this stage, you need to tell the xmlhttp request object which javascript function will handle the response, by setting the onreadystatechange property of the object and naming it after the function to
call when the request changes state, like this: httprequest.onreadystatechange = nameofthefunction; note that there are no parentheses or parameters after the function name, because you're assigning a reference to the function, rather than actually
calling it.
... alternatively, instead of giving a function name, you can use the javascript technique of defining functions on the fly (
called "anonymous functions") to define the actions that will process the response, like this: httprequest.onreadystatechange = function(){ // process the server response here.
...And 11 more matches
Array.prototype.find() - JavaScript
syntax arr.find(
callback(element[, index[, array]])[, thisarg]) parameters
callback function to execute on each value in the array, taking 3 arguments: element the current element in the array.
... array optional the array that find was
called on.
... thisarg optional object to use as this inside
callback.
...And 11 more matches
Promise.prototype.then() - JavaScript
it takes up to two arguments:
callback functions for the success and failure cases of the promise.
...if the promise that then is
called on adopts a state (fulfillment or rejection) for which then has no handler, the returned promise simply adopts the final state of the original promise on which then was
called.
... syntax p.then(onfulfilled[, onrejected]); p.then(value => { // fulfillment }, reason => { // rejection }); parameters onfulfilled optional a function
called if the promise is fulfilled.
...And 11 more matches
Digital audio concepts - Web media technologies
this process is
called analog to digital conversion (a/d for short).
...the number of samples taken per second is
called the sample rate.
...the size of an individual sample is
called the sample size.
...And 11 more matches
tabs - Archive of obsolete content
the stylesheet is
called "style.css" and is located in the add-on's "data" directory: var tabs = require("sdk/tabs"); var { attach, detach } = require('sdk/content/mod'); var { style } = require('sdk/stylesheet/style'); var { togglebutton } = require("sdk/ui/button/toggle"); var style = style({ uri: './style.css' }); var button = togglebutton({ id: "stylist", label: "stylist", icon: "./icon-16.png", onchan...
... onopen function a
callback function that will be registered for the 'open' event.
... onclose function a
callback function that will be registered for the 'close' event.
...And 10 more matches
widget - Archive of obsolete content
by exposing your interface as a widget, your add-on would automati
cally inherit such functionality.
... upon creation, the widget is automati
cally added to the add-on bar.
...if the content is an image, it is automati
cally scaled to be 16x16 pixels.
...And 10 more matches
ui/sidebar - Archive of obsolete content
once you've done that, you can show the sidebar by
calling the sidebar's show() method.
... you can hide the sidebar by
calling its hide() method.
...
called with no arguments, show() and hide() will operate on the currently active window.
...And 10 more matches
The Essentials of an Extension - Archive of obsolete content
the file is formatted in a special flavor of xml
called rdf.
...unix-based systems have a command line tool
called uuidgen that generates uuids.
... <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>4.0</em:minversion> <em:maxversion>10.*</em:maxversion> </description> </em:targetapplication> this node specifies the target application and target versions for the extension, specifi
cally firefox, from version 4 up to version 10.
...And 10 more matches
Creating a dynamic status bar extension - Archive of obsolete content
« previousnext » this article builds upon the article creating a status bar extension, which creates a static status bar panel in the firefox status bar, by dynami
cally updating its content with information fetched from the web every few minutes.
... specifi
cally, this sample displays a stock quote in the status bar, and, when you mouse over it, displays a tooltip containing more detailed information about the stock.
...we use the window.addeventlistener() dom function to tell firefox to
call the stockwatcher.startup() function when a new browser window is opened: window.addeventlistener("load", function(e) { stockwatcher.startup(); }, false); our new extension has two primary functions: startup() and refreshinformation().
...And 10 more matches
Drag and Drop - Archive of obsolete content
event handlers are
called when the user starts and ends dragging, and at various points in-between.
... the list below describes the event handlers that can be
called, which may be placed on any element.
... ondrag
called periodi
cally throughout the drag and drop operation.
...And 10 more matches
Space Manager Detailed Design - Archive of obsolete content
overview the space manager and related classes and structures are an important of the gecko layout system, specifi
cally block layout.
...this represents the accumulated
calls to * translate().
...erations bandrect* next() const {return (bandrect*)pr_next_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 verti
cally, 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* splitverti
cally(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...
...And 10 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
these methods can be
called from a script.
... the body element contains the script that is executed when the method is
called.
...you can
call the method by using code such as element.getmaximum(5, 10) where element is a reference to an element defined by the xbl containing the getmaximum method.
...And 10 more matches
Creating a Wizard - Archive of obsolete content
the navigation buttons are created automati
cally.
...the wizard will be formatted automati
cally, with a title across the top and a set of buttons along the bottom.
...for example: <wizard id="example-window" title="select a dog wizard" onwizardfinish="return savedoginfo();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> when the user clicks the finish button, the function savedoginfo() will be
called, which would be defined in a script file to save the information that was entered.
...And 10 more matches
Gecko info for Windows accessibility vendors
data is therefore stored and retrieved dynami
cally much faster.
...they typi
cally use standard windows controls for their user interface -- the area outside of the client content window, plus the context menu.
... k-meleon: a light, ultra-fast and more advanced (fully configurable) gecko-based web browser available on the windows platform xul-based clients (support msaa) xul-based clients make full use of the gecko architecture, not only for html content, as well as for menus, dialogs and the entire user interface via an xml language
called xul (extensible user-interface language).
...And 10 more matches
Download
this property becomes true as soon as the cancel() method is
called, though the stopped property might remain false until the cancellation request has been processed.
... launchwhensucceeded boolean if this property is true when the download finishes successfully, the target file will be opened or executed automati
cally.
... onchange function this can be set to a function that is
called after other properties change.
...And 10 more matches
AsyncTestUtils extended framework
sometimes in your tests you need to wait for an operation to complete that does not occur synchronously (that is, it is not done when the function
call you made to initiate the operation returns control to you).
...this is how asynchronous
callbacks get their chance to run again.
...this allows you to write reasonably normal looking functions instead of having to chain together a whole bunch of functions and
callbacks.
...And 10 more matches
PKCS11 FAQ
nss typi
cally holds one session read-only session per slot, in which some of the non-multipart functions are handled.
...nss continues to evolve, and periodi
cally enhances it's functionality by using a more complete list of pkcs #11 functions.
... nss
calls c_getsessioninfo to get the login/logout state.
...And 10 more matches
Invariants
when a new object is created, it is automati
cally created in cx->compartment, but its parent and prototype are often determined by examining the scope chain.
... however, there is another internal api, js::switchtocompartment, that lets you break this invariant, and of course in xpconnect we use that from time to time when we know we aren't going to be creating any new objects (other than global objects, which have no parent or prototype) or doing anything that might
call back into native code that could create objects.
...a jsnative or other
callback may move cx to another compartment, as long as it returns cx to the script's compartment before returning.
...And 10 more matches
Finishing the Component
* * users of the service manager must first obtain a pointer to the * global service manager by
calling ns_getservicemanager.
... after that, * they can request specific services by
calling getservice.
... * * a user of a service may keep references to particular services * indefinitely and only must
call release when it shuts down.
...And 10 more matches
Using XPCOM Components
the cookie manager dialog this dialog is written in xul and javascript, and uses a part of xpcom
called xpconnect to seamlessly connect to the cookiemanager component (see connecting to components from the interface below).
...when a user selects one of the cookies displayed in the list and then clicks the remove button, the remove method in the nsicookiemanager interface is
called.
... the snippet in getting the cookiemanager component in javascript shows how the remove() method from the xpcom cookiemanager component can be
called from javascript: getting the cookiemanager component in javascript // xpconnect to cookiemanager // get the cookie manager component in javascript var cmgr = components.classes["@mozilla.org/cookiemanager;1"] .getservice(); cmgr = cmgr.queryinterface(components.interfaces.nsicookiemanager); //
called as part of a largerdeleteallcookies() function function finalizecookiedeletions() { for (var c=0; c<deletedcookies.length; c++) { cmgr.remove(deletedcookies[c].host, ...
...And 10 more matches
nsICryptoHash
note: this method may be
called any time after " ..
..." is
called.
... this
call resets the object.
...And 10 more matches
nsIDOMOfflineResourceList
the nsidomofflineresourcelist interface provides access to the application cache that allows web content's resources to be cached lo
cally for use while offline.
... it includes methods for adding resources to and removing resources from the cache, as well as for enumerating the dynami
cally managed resource list.
...om: nsisupports method overview void mozadd(in domstring uri); boolean mozhasitem(in domstring uri); domstring mozitem(in unsigned long index); void mozremove(in domstring uri); void swapcache(); void update(); attributes attribute type description mozitems nsidomofflineresourcelist the list of dynami
cally-managed entries in the offline resource list.
...And 10 more matches
XPCOM
interfaces in xpcom are defined in a dialect of idl
called xpidl.
...here is how to make the same component in python using pyxpcom.fun with xbl and xpconnectgenerating guidsguids are used in mozilla programming for identifying several types of entities, including xpcom interfaces (this type of guids is
callled iid), components (cid), and legacy add-ons—like extensions and themes—that were created prior to firefox 1.5.
...that means you can
call javascript methods from c++ and vice versa.
...And 10 more matches
Working with windows in chrome code
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.
...its parameters are similar to window.open; in fact, window.open's implementation
calls nsiwindowwatcher's methods.
... techni
cally speaking, it implements a number of interfaces, including nsidomjswindow and nsidomwindow, but it also contains the user-defined properties for global variables and functions of the window.
...And 10 more matches
Memory - Plugins
use this function to allocate memory dynami
cally.
... the plug-in can
call the plug-in api npn_memalloc function instead of the standard malloc function to allocate dynamic memory.
... a
call to npn_memalloc is more likely to succeed.
...And 10 more matches
Recording a media element - Web APIs
it works by using an arrow function which
calls window.settimeout(), specifying the promise's resolution handler as the timeout handler function.
...we always record no more than the specified number of milliseconds of media, although if the media stops before that time is reached, mediarecorder automati
cally stops recording as well.
... lines 6-7 starts the recording process by
calling recorder.start(), and outputs a message to the log with the updated state of the recorder and the number of seconds it will be recording.
...And 10 more matches
RTCPeerConnection.setLocalDescription() - Web APIs
if setlocaldescription() is
called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions).
... because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by
calling setlocaldescription() does not immediately take effect.
... syntax apromise = rtcpeerconnection.setlocaldescription(sessiondescription); pc.setlocaldescription(sessiondescription, success
callback, error
callback); parameters sessiondescription optional an rtcsessiondescriptioninit or rtcsessiondescription which specifies the configuration to be applied to the local end of the connection.
...And 10 more matches
Using readable streams - Web APIs
as a javascript developer, programmati
cally reading and manipulating streams of data received over the network, chunk by chunk, is very useful!
... if done is not true, we process the new chunk we’ve read (contained in the value property of the results object) and then
call the pump() function again to read the next chunk.
... the first object can contain up to five members, only the first of which is required: start(controller) — a method that is
called once, immediately after the readablestream is constructed.
...And 10 more matches
Inputs and input sources - Web APIs
l; xrsession.addeventlistener("inputsourceschange", event => { inputsourcelist = event.session.inputsources; inputsourcelist.foreach(source => { switch(source) { case "left": lefthandsource = source; break; case "right": righthandsource = source; break; } }); }); the inputsourceschange event is also fired once when the session's creation
callback first completes execution, so you can use it to fetch the input source list as soon as it's available at startup time.
...the first entry in the list is typi
cally indicative of the precise model of the controller, or of a model with which the controller is compatible.
...this is typi
cally generated by the user squeezing the controller, making a hand gesture that mimes grabbing something, or using (squeezing) a trigger.
...And 10 more matches
Window.requestAnimationFrame() - Web APIs
the window.requestanimationframe() method tells the browser that you wish to perform an animation and requests that the browser
calls a specified function to update an animation before the next repaint.
... the method takes a
callback as an argument to be invoked before the repaint.
... note: your
callback routine must itself
call requestanimationframe() if you want to animate another frame at the next repaint.
...And 10 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.
... the object returned by getoffsetreferencespace() is an xrreferencespace if
called on an xrreferencespace, or an xrboundedreferencespace if
called on an object of that type.
... in other words, when you have an object in 3d space and need to position another object relative to that one, you can
call getoffsetreferencespace(), passing into it the position and orientation you want the second object to have relative to the position and orientation of the object on which you
call getoffsetreferencespace().
...And 10 more matches
Array.prototype.filter() - JavaScript
syntax let newarray = arr.filter(
callback(element[, index, [array]])[, thisarg]) parameters
callback function is a predicate, to test each element of the array.
... arrayoptional the array filter was
called upon.
... thisargoptional value to use as this when executing
callback.
...And 10 more matches
Array.prototype.findIndex() - JavaScript
syntax arr.findindex(
callback( element[, index[, array]] )[, thisarg]) parameters
callback a function to execute on each value in the array until the function returns true, indicating that the satisfying element was found.
... array optional the array findindex() was
called upon.
... thisarg optional optional object to use as this when executing
callback.
...And 10 more matches
Function.prototype.apply() - JavaScript
the apply() method
calls a function with a given this value, and arguments provided as an array (or an array-like object).
... syntax func.apply(thisarg, [ argsarray]) parameters thisarg the value of this provided for the
call to func.
... argsarray optional an array-like object, specifying the arguments with which func should be
called, or null or undefined if no arguments should be provided to the function.
...And 10 more matches
TypedArray.prototype.findIndex() - JavaScript
syntax typedarray.findindex(
callback[, thisarg]) parameters
callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array.
... array the typed array findindex was
called upon.
...object to use as this when executing
callback.
...And 10 more matches
timers - Archive of obsolete content
globals constructors functions settimeout(
callback, ms) schedules
callback to be
called in ms milliseconds.
... any additional arguments are passed straight through to the
callback.
... parameters
callback : function function to be
called.
...And 9 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
follow every step methodi
cally and you'll probably be alright.
... note that before actually building anything, the mozilla build system invokes a configuration process that generates the actual makefiles used for the build from makefile templates
called makefile.in.
... the actual makefiles tend to be very similar or identical to the templates, but the extra flexibility gained from having the makefiles generated dynami
cally is one of the things that makes the build system so powerful.
...And 9 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
if it cannot be easily proven that an eval()
call is benign and necessary because there are no viable alternatives, a mozilla add-ons gallery reviewer will generally reject the submission!
...basi
cally, you are executing remote code with full chrome access; that is, introducing a remote code execution vulnerability.
...settimeout("alert('" + xhr.responsetext + "');", 100); // attacker manipulated responsetext to contain "attack!'); format_computer(); alert('done" settimeout("alert('attack!'); format_computer(); alert('done');", 100); as a general rule of thumb, just don't pass code around as strings and execute it by
calling eval, settimeout and friends.
...And 9 more matches
Dehydra Function Reference - Archive of obsolete content
gcc command line -fplugin=/path/to/gcc_dehydra.so -fplugin-arg-gcc_dehydra=/path/to/your/script.js
callback functions the following functions may be provided by the analysis script and will be
called by dehydra while compiling.
...process_type(type) dehydra
calls this for each class, struct, enum, union, and typedef declaration.
... process_type is
called after process_function is
called for all the member functions.
...And 9 more matches
Treehydra Manual - Archive of obsolete content
callbacks and gcc intermediate representations like dehydra, treehydra sends program representations to the user javascript via
callbacks.
... there are 3 treehydra
callbacks.
... note that the
callbacks interact with other treehydra options.
...And 9 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
note also that when you
call methods on the install--as you do so often in installation scripts (getfolder, initinstall, addfile, and performinstall are all examples of common install object methods)--the install object is implicit; like the window object in regular web page scripts, the install object does not need to be prefixed to the method.
...in the browser.xpi installation, this function appears at line 20: var err = initinstall("netscape seamonkey", "browser", "6.0.0.2000110807"); if you
call a method on the install object before initinstall(), you will get an error.
... verifying the target the first thing the installation script does when it's executed is to check that there is adequate disk space for the software to be installed, where the verifydiskspace function is
called as a condition of the main installation block that starts at line 24).
...And 9 more matches
Adobe Flash - Archive of obsolete content
this article explains how javascript can be used to access methods from within the flash plugin, as well as how a feature
called fscommands can be used to access javascript functions from within the flash animation.
...<script type="text/javascript">identifyflash();</script> typi
cally, javascript code that determines what version of the plugin is installed looks at the mimetypes array that is part of the navigator object.
... every plugin exposes a description string that typi
cally includes the plugin's name and version number.
...And 9 more matches
Using workers in extensions - Archive of obsolete content
how this differs from previous versions this version of the stock ticker extension moves the xmlhttprequest
call that fetches updated stock information into a worker thread, which then passes that information back to the main body of the extension's code to update the display in the status bar.
... the worker the worker thread's job in this example is to issue the xmlhttprequest
calls that fetch the updated stock information.
...every 10 minutes, it
calls xmlhttprequest, and, when the results are received, sends an event back to the main thread with the received data.
...And 9 more matches
Introduction to web APIs - Learn web development
when
calling a method from a library, the developer is in control.
... with a framework, the control is inverted: the framework
calls the developer's code.
...the most obvious example is the dom (document object model) api, which allows you to manipulate html and css — creating, removing and changing html, dynami
cally applying new styles to your page, etc.
...And 9 more matches
What is JavaScript? - Learn web development
javascript is a scripting language that enables you to create dynami
cally updating content, control multimedia, animate images, and pretty much everything else.
...in the above example for instance, we ask for a new name to be entered then store that name in a variable
called name.
...so-
called application programming interfaces (apis) provide you with extra superpowers to use in your javascript code.
...And 9 more matches
Introduction to client-side frameworks - Learn web development
developers who worked with javascript wrote tools to solve the problems they faced, and packaged them into reusable packages
called libraries, so they could share their solutions with others.
...react itself is not techni
cally a framework; it's a library for rendering ui components.
... each of our goals is theoreti
cally simple in isolation.
...And 9 more matches
Focus management with Vue refs - Learn web development
specifi
cally, when a user activates the "edit" button, we remove the "edit" button from the dom, but we don't move the user's focus anywhere, so in effect it just disappears.
... for convenience, create a new method which takes no arguments
called focusoneditbutton().
... inside it, assign your ref to a variable, and then
call the focus() method on the ref.
...And 9 more matches
Handling common HTML and CSS problems - Learn web development
previous overview: cross browser testing next with the scene set, we'll now look specifi
cally at the common cross-browser problems you will come across in html and css code, and what tools can be used to prevent problems from happening, or fix problems that occur.
... the trouble with html and css some of the trouble with html and css lies with the fact that both languages are fairly simple, and often developers don't take them seriously, in terms of making sure the code is well-crafted, efficient, and semanti
cally describes the purpose of the features on the page.
... basi
cally, it is a matter of checking whether your html and css code is well formed and doesn't contain any syntax errors.
...And 9 more matches
How Mozilla's build system works
the file is generated from a file
called configure.in, which is written in m4 and processed using autoconf 2.13 to create the final configure script.
...the primary output of the configure script is an executable file in the object directory
called config.status.
... what essentially happens is the automati
cally produced config.status python script is executed as soon as configure has generated it.
...And 9 more matches
Eclipse CDT
introduction eclipse cdt (c/c++ development tools) is an open-source ide for c and c++ development with advanced code assistance (inheritance/
call graph explorer, jump to definition, refactoring, autocomplete, syntax highlighting, and so on).
...first, make sure that the directory of eclipse's eclipse binary (typi
cally /applications/eclipse.app/contents/macos/ on macos) is in your path.
...in principle, you can set the index to rebuild automati
cally by opening the workspace preferences, selecting "c/c++ > indexer", and reenabling "automati
cally update the index".
...And 9 more matches
OS.File for the main thread
it uses an atomic write to ensure that the file is not modified if, for some reason, the write cannot complete (typi
cally 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 atomic...
... 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 atomi
cally to "file.txt", using as temporary {tmppath: "file.txt.tmp", nooverwrite: true}); // buffer "file.txt.tmp".
... var img = new image(); img.onload = function() { var canvas = document.createelementns('http://www.w3.org/1999/xhtml', 'canvas'); canvas.width = img.naturalwidth; canvas.height = img.naturalheight; var ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); (canvas.toblobhd || canvas.toblob).
call(canvas, function(b) { var r = cc['@mozilla.org/files/filereader;1'].createinstance(ci.nsidomfilereader); //new filereader(); r.onloadend = function() { // r.result contains the arraybuffer.
...And 9 more matches
Optimizing Applications For NSPR
multiplatform do not
call any blocking system
call from a local thread.
... the only exception to this rule is the <tt>select()</tt> and <tt>poll()</tt> system
calls on unix, both of which nspr has overridden to make sure they are aware of the nspr local threads.
...therefore, if you
call a blocking system
call from the primordial thread, it is going to block more than just the primordial thread and the system may not function correctly.
...And 9 more matches
Introduction to NSPR
it's usually not necessary to create a global thread explicitly unless you are planning to port your code only to platforms that provide threading services with which you are familiar or unless the thread will be executing code that might directly
call blocking os functions.
...in general, an nspr thread of higher priority has a statisti
cally better chance of running relative to threads of lower priority.
... to interrupt a thread, the
caller of pr_interrupt must have the nspr reference to the target thread (prthread*).
...And 9 more matches
Rhino scopes and contexts
to associate the current thread with a context, simply
call the enter method of context: context cx = context.enter(); once you are done with execution, simply exit the context: context.exit(); these
calls will work properly even if there is already a context associated with the current thread.
... remember to put the exit()
call in a finally block if you're executing code that could throw an exception.
... 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.
...And 9 more matches
Property cache
the opcodes that take advantage of the property cache, as of june 2009, are: getprop, get{x,this,arg,local}prop, and length; name; setprop, bindname, and setname;
callprop and
callname; and {inc,dec}name and name{inc,dec}.
...(informally: objects with the same shape have the same prototype, class, and layout.) prototype chain shadowing guarantee — if at t0 the object x has shape s and a property x.p of x is found along the prototype chain on object x' of shape s', where x !== x', and the lookup
called no resolve hooks or non-native lookup ops, and at t1 the object x has shape s, the object x' has shape s', and no shape-regenerating gc occurred, then at t1 the lookup for x.p still finds the same property on x'.
... (informally: if another property shadows x'.p, the shape of x' will change.) o---->o---->o---->o ^x ^x' ^object.prototype, perhaps (----> indicates the proto relation) scope chain shadowing guarantee — if at time t0 the object x has shape s and a name lookup for p starting at scope chain head x finds p on an object x' of shape s', where x !== x'; and the lookup
called no resolve hooks or non-native lookup ops; and each object examined along the parent chain, except possibly the one along whose prototype chain x' was found, had no prototype or was a block object; and at time t1 x has shape s and x' has shape s'; and no shape-regenerating gc occurred; then at t1 the lookup for p in x still finds the same property on x'.
...And 9 more matches
SpiderMonkey 1.8.5
many jsapi types, functions, and
callback signatures have changed, though most of them still have the same names and do the same things.
... no compartment may execute js code or
call into jsapi on two os threads at the same time.
... the so-
called "slow natives" are no longer supported; as such jsfastnative has been renamed to jsnative and relevant interfaces have been updated accordingly.
...And 9 more matches
nsIChannelEventSink
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) channels will try to get this interface from a channel's notification
callbacks or, if not available there, from the loadgroup's notification
callbacks.
... these methods are
called before onstartrequest.
...starting in gecko 2.0, that method no longer exists, and instead the asynconchannelredirect() method is
called; this uses a
callback to handle redirects asynchronously.
...And 9 more matches
nsIDownloadProgressListener
inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) to use simply implement this interface in your code, then
call nsidownloadmanager.addlistener() to start listening.
... when you no longer need to listen to the download manager's state,
call nsidownloadmanager.removelistener() to stop listening.
... as the states of downloads change, the methods described here are
called by the download manager so your code can take whatever steps it needs to.
...And 9 more matches
nsIInputStream
a blocking input stream may suspend the
calling thread in order to satisfy a
call to close(), available(), read(), or readsegments().
... a non-blocking input stream, on the other hand, must not block the
calling thread of execution.
... in addition to the number of bytes available in the stream, this method also informs the
caller of the current status of the stream.
...And 9 more matches
nsINavBookmarksService
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 nsinavhistorybatch
callback a
callback, 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 s...
...
calls can be nested, observers will only be notified when all batches begin/end.
... it is extremely important that you
call endupdatebatch() for each
call to beginupdatebatch.
...And 9 more matches
nsIThreadObserver
t changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void afterprocessnextevent(in nsithreadinternal thread, in unsigned long recursiondepth); void ondispatchedevent(in nsithreadinternal thread); void onprocessnextevent(in nsithreadinternal thread, in boolean maywait, in unsigned long recursiondepth); methods afterprocessnextevent()
called by the nsithread method nsithread.processnextevent() after an event is processed.
... this method is only
called on the target thread.
... note: it is valid to change the thread's observer during a
call to this method.
...And 9 more matches
nsITransactionListener
saction); boolean willendbatch(in nsitransactionmanager amanager); boolean willmerge(in nsitransactionmanager amanager, in nsitransaction atoptransaction, in nsitransaction atransactiontomerge); boolean willredo(in nsitransactionmanager amanager, in nsitransaction atransaction); boolean willundo(in nsitransactionmanager amanager, in nsitransaction atransaction); methods didbeginbatch()
called after a nsitransactionmanager begins a batch.
...diddo()
called after a nsitransactionmanager
calls the nsitransaction.dotransaction() method of a transaction.
... didendbatch()
called after a nsitransactionmanager ends a batch.
...And 9 more matches
nsIXPCScriptable
for example,
callers must guarantee that they set the *_retval of the various methods that return a boolean to pr_true before making the
call.
...jsobjectptr objp); prbool convert(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in pruint32 type, in jsvalptr vp); void finalize(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); prbool checkaccess(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in pruint32 mode, in jsvalptr vp); prbool
call(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in pruint32 argc, in jsvalptr argv, in jsvalptr vp); prbool construct(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in pruint32 argc, in jsvalptr argv, in jsvalptr vp); prbool hasinstance(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval val, out p...
... 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.
...And 9 more matches
XPCOM Interface Reference
component; nsiprefbranchextensionmanager (toolkit)iaccessible2iaccessibleactioniaccessibleapplicationiaccessiblecomponentiaccessibleeditabletextiaccessiblehyperlinkiaccessiblehypertextiaccessibleimageiaccessiblerelationiaccessibletableiaccessibletable2iaccessibletablecelliaccessibletextiaccessiblevalueidispatchijsdebuggeramiinstall
callbackamiinstalltriggeramiwebinstallinfoamiwebinstalllisteneramiwebinstallpromptamiwebinstallerimgicacheimgicontainerimgicontainerobserverimgidecoderimgidecoderobserverimgiencoderimgiloaderimgirequestinidomutilsjsdistackframemoziasyncfaviconsmoziasynchistorymozicoloranalyzermozijssubscriptloadermozipersonaldictionarymoziplaceinfomoziplacesautocompletemoziregistrymozirepresentativecolor
callbackmozisp...
...ellcheckingenginemozistorageaggregatefunctionmozistorageasyncstatementmozistoragebindingparamsmozistoragebindingparamsarraymozistoragecompletion
callbackmozistorageconnectionmozistorageerrormozistoragefunctionmozistoragependingstatementmozistorageprogresshandlermozistorageresultsetmozistoragerowmozistorageservicemozistoragestatementmozistoragestatement
callbackmozistoragestatementparamsmozistoragestatementrowmozistoragestatementwrappermozistoragevacuumparticipantmozistoragevaluearraymozitxttohtmlconvmozithirdpartyutilmozivisitinfomozivisitinfo
callbackmozivisitstatus
callbacknsiabcardnsiaboutmodulensiabstractworkernsiaccelerometerupdatensiaccessnodensiaccessibilityservicensiaccessiblensiaccessiblecaretmoveeventnsiaccessiblecoordinatetypensiaccessibledocumentnsiaccessibleeditabletextnsiaccessibleev...
...iblevaluensiaccessiblewin32objectnsialertsservicensiannotationobservernsiannotationservicensiappshellnsiappshellservicensiappstartupnsiappstartup_mozilla_2_0nsiapplicationcachensiapplicationcachechannelnsiapplicationcachecontainernsiapplicationcachenamespacensiapplicationcacheservicensiapplicationupdateservicensiarraynsiasyncinputstreamnsiasyncoutputstreamnsiasyncstreamcopiernsiasyncverifyredirect
callbacknsiauthinformationnsiauthmodulensiauthpromptnsiauthprompt2nsiauthpromptadapterfactorynsiauthprompt
callbacknsiauthpromptprovidernsiauthpromptwrappernsiautocompletecontrollernsiautocompleteinputnsiautocompleteitemnsiautocompletelistenernsiautocompleteobservernsiautocompleteresultnsiautocompletesearchnsibadcertlistener2nsibidikeyboardnsibinaryinputstreamnsibinaryoutputstreamnsiblocklistpromptnsib...
...And 9 more matches
Address Book examples
editing contacts once you have obtained a card from an nsiabdirectory (see above), you can edit it in a two step process, firstly, change the properties that you to edit: card.setproperty("firstname", "jane"); card.setproperty("lastname", "doe"); secondly,
call modifycard to save the card in the database.
... addressbook.modifycard(card); deleting contacts once you have obtained a card(s) from an nsiabdirectory (see above) you can delete one or more simply by
calling the deletecards function: let cardstodelete = components.classes["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); cardstodelete.appendelement(card); // repeat append as necessary addressbook.deletecards(cardstodelete); how do i add and use my own properties?
... edit address book dialog addressbook is an nsiabdirectory that provides the chrome uri that is used in the
call to opendialog.
...And 9 more matches
Using COM from js-ctypes
basis and reference for this article bugzilla :: bug 738501 - implement ability to create windows shortcuts from javascript - comment 4 relavent topic bugzilla :: bug 505907 - support c++
calling from jsctypes converting com code to c code to convert com code to js-ctypes, we need to write c++ vtable pointers in c.
...pvoice = null; hresult hr = cocreateinstance(clsid_spvoice, null, clsctx_all, iid_ispvoice, (void**)&pvoice); if (succeeded(hr)) { pvoice->speak(l"hello, firefox!", spf_default, null); pvoice->release(); } } // msdn documentation says that even if coinitalize fails, counitialize // must be
called couninitialize(); return 0; } to run the code, save it as test.cpp, and run following command in the directory (needs visual studio).
... __std
call and __cdecl needs __std
call and __cdecl (
callback_abi) description here.
...And 9 more matches
ABI
general details this article describes the
calling conventions with respect to js-ctypes while programming x86 and x86-64/x64/amd64 architectures.
... a
calling convention is an implementation-level (low-level) scheme regarding how subroutines receive parameters from their
caller and how they revert.
... http://en.wikipedia.org/wiki/x86_
calling_conventions abi abi stands for "application binary interface".
...And 9 more matches
ctypes
constants abi constants these constants are used to specify the abi used to
call a native function in the library.
...you also use this for all system
calls on mac os x and linux.
... std
call_abi used for
calling functions declared with std
call on windows.
...And 9 more matches
Debugger.Source - Firefox Developer Tools
(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.
... "worker", for code loaded by
calling the web worker constructor—the worker’s main script.
... "importscripts", for code by
calling importscripts in a web worker.
...And 9 more matches
Index - Firefox Developer Tools
18 debugger when
called as a constructor, the debugger object creates a new debugger instance.
... 26 tutorial: show allocations per
call path debugger, tools, tutorial this page shows how to use the debugger api to show how many objects a web page allocates, sorted by the function
call path that allocated them.
... 42 dominators view starting in firefox 46, the memory tool includes a new view
called the dominators view.
...And 9 more matches
Transformations - Web APIs
every time the save() method is
called, the current drawing state is pushed onto the stack.
... you can
call the save() method as many times as you like.
... each time the restore() method is
called, the last saved state is popped off the stack and all saved settings are restored.
...And 9 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
the filesystemdirectoryreader interface's readentries() method retrieves the directory entries within the directory being read and delivers them in an array to a provided
callback function.
... syntax readentries(success
callback[, error
callback]); parameters success
callback a function which is
called when the directory's contents have been retrieved.
...if there are no files left, or you've already
called readentries() on this filesystemdirectoryreader, the array is empty.
...And 9 more matches
Using the Geolocation API - Web APIs
you can test for the presence of geolocation thusly: if('geolocation' in navigator) { /* geolocation is available */ } else { /* geolocation is not available */ } getting the current position to obtain the user's current location, you can
call the getcurrentposition() method.
...when the position is determined, the defined
callback function is executed.
... you can optionally provide a second
callback function to be executed if an error occurs.
...And 9 more matches
HTMLMediaElement - Web APIs
htmlmediaelement.autoplay a boolean that reflects the autoplay html attribute, indicating whether playback should automati
cally begin as soon as enough media is available to do so without interruption.
... note: automati
cally playing audio when the user doesn't expect or desire it is a poor user experience and should be avoided in most cases, though there are exceptions.
...if the media is of indefinite length (such as streamed live media, a webrtc
call's media, or similar), the value is +infinity.
...And 9 more matches
Touch events - Web APIs
this may be a finger (or elbow, ear, nose, whatever, but typi
cally a finger) or stylus.
...</canvas> <br> log: <pre id="log" style="border: 1px solid #ccc;"></pre> setting up the event handlers when the page loads, the startup() function shown below will be
called.
... var ongoingtouches = []; when a touchstart event occurs, indicating that a new touch on the surface has occurred, the handlestart() function below is
called.
...And 9 more matches
Creating a cross-browser video player - Developer guides
working example our example video player displays a clip from an open source movie
called tears of steel, and includes typical video controls.
... setup before dealing with the individual buttons, a number of initialisation
calls are required.
...most of these buttons require a simple click event listener to be added, and a media api defined method and/or attributes to be
called/checked on the video.
...And 9 more matches
The HTML autocomplete attribute - HTML: Hypertext Markup Language
the source of the suggested values is generally up to the browser; typi
cally values come from past values entered by the user, but they may also come from pre-configured values.
... in order to provide autocompletion, user-agents might require <input>/<select>/<textarea> elements to: have a name and/or id attribute be descendants of a <form> element the form to have a submit button values "off" the browser is not permitted to automati
cally enter or select a value for this field.
... it is possible that the document or application provides its own autocomplete feature, or that security concerns require that the field's value not be automati
cally entered.
...And 9 more matches
Inheritance and the prototype chain - JavaScript
each object has a private property which holds a link to another object
called its prototype.
...// this is
called property shadowing console.log(o.c); // 4 // is there a 'c' own property on o?
... var o = { a: 2, m: function() { return this.a + 1; } }; console.log(o.m()); // 3 // when
calling o.m in this case, 'this' refers to o var p = object.create(o); // p is an object that inherits from o p.a = 4; // creates a property 'a' on p console.log(p.m()); // 5 // when p.m is
called, 'this' refers to p.
...And 9 more matches
InternalError: too much recursion - JavaScript
the javascript exception "too much recursion" or "maximum
call stack size exceeded" occurs when there are too many function
calls, or a function is missing a base case.
... message error: out of stack space (edge) internalerror: too much recursion (firefox) rangeerror: maximum
call stack size exceeded (chrome) error type internalerror.
... a function that
calls itself is
called a recursive function.
...And 9 more matches
Promise() constructor - JavaScript
the signature of this function is expected to be: function(resolutionfunc, rejectionfunc){ // typi
cally, some asynchronous operation.
...the side-effect is that the promiseobj becomes "resolved." typi
cally, it works like this: the operation within executor is asynchronous and provides a
callback.
... the
callback is defined within the executor code.
...And 9 more matches
SVG documentation index - SVG: Scalable Vector Graphics
the clip-rule attribute basi
cally works as the fill-rule attribute, except that it applies to <clippath> definitions.
... 55 data-* attribute, svg the data-* svg attributes are
called custom data attributes.
... 118 kerning deprecated, svg, svg attribute the kerning attribute indicates whether the spacing between glyphs should be adjusted based on kerning tables that are included in the relevant font (i.e., enable auto-kerning) or instead disable auto-kerning and set the spacing between them to a specific length (typi
cally, zero).
...And 9 more matches
Using the WebAssembly JavaScript API - WebAssembly
next, let’s create a simple html file
called index.html in the same directory as your wasm file (can use our simple template if you haven’t got one easily available).
... now, to help us understand what is going on here, let’s look at the text representation of our wasm module (which we also meet in converting webassembly format to wasm): (module (func $i (import "imports" "imported_func") (param i32)) (func (export "exported_func") i32.const 42
call $i)) in the second line, you will see that the import has a two-level namespace — the internal function $i is imported from imports.imported_func.
... add the following to your script, below the first block: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the net result of this is that we
call our exported webassembly function exported_func, which in turn
calls our imported javascript function imported_func, which logs the value provided inside the webassembly instance (42) to the console.
...And 9 more matches
dev/panel - Archive of obsolete content
most of the firefox developer tools are hosted in a ui component
called the toolbox.
... mandatory icon string the icon to display in the toolbox toolbar, specified as a resource:// url pointing to an icon file, typi
cally in your add-on's "data" directory.
... mandatory url string a resource:// url pointing to an html file, typi
cally in your add-on's "data" directory.
...And 8 more matches
test/utils - Archive of obsolete content
to make them asynchronous, pass a third argument done, which is a function to
call when you have finished: let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testcountbookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert, done) { removeallbookmarksasync(function () { done(...
...may be asynchronous if beforefn accepts a third argument, which is a
callback.
... parameters exports : object a test file's exports object beforefn : function the function to be
called before each test.
...And 8 more matches
Preferences - Archive of obsolete content
to get an nsiprefbranch, either queryinterface() the pref service (that will give you the root branch) or
call nsiprefservice.getbranch() to get a sub-branch.
... the effect of default preferences on get methods when one of the get methods of nsiprefbranch (assuming it's a branch of the tree with current values) is
called, it does the following: checks whether the current tree has a value for the preference and whether or not the preference is locked.
... if there's a value of the expected type in the default tree, it is returned (with the only exception being that
calling getcomplexvalue() with atype parameter specified as nsipreflocalizedstring, described above).
...And 8 more matches
XPCOM Objects - Archive of obsolete content
this lower layer is
called xulrunner, and it is a very powerful platform, providing a very robust development base for web-enabled, cross-platform applications.
...the method you
call on cc["some-string"] should either be getservice or createinstance, depending on what you're asking for.
... in most cases it is very clear which one to
call, but in case of doubt, look for documentation on it.
...And 8 more matches
Style System Overview - Archive of obsolete content
the nsistyleruleprocessor interface implemented by cssruleprocessor, htmlstylesheetimpl, and htmlcssstylesheetimpl has a rulesmatching method, which is required to
call nsrulewalker::forward on any rules that match the element.
... to match rules, we do lookups in the rulehash's tables, remerge the lists of rules using stored indices, and then
call selectormatchestree to find which selectors really match.
... the rule tree as we
call nsrulewalker::forward on all the rules that are matched, we build or walk along the rule tree.
...And 8 more matches
Nanojit - Archive of obsolete content
a compiler's lir is typi
cally one of several partly-compiled representations of a program that a compiler produces on the way from raw source code to machine code.
... once the instructions are in the lirbuffer, the application
calls nanojit::compile() to produce machine code, which is stored in a nanojit::fragment.
...the result of compilation is a function that the application can
call from c via a pointer to the first instruction.
...And 8 more matches
The life of an HTML HTTP request - Archive of obsolete content
(1) the loading of the url is started in nswebshell::doloadurl (
called from some loadurl or loaduri variant in the webshell).
...[note: passes nswebshell.mobserver as nsistreamobserver and the webshell as nsicontentviewercontainer to the docloader.] (2) the document loader
calls ns_openuri with the url to begin transfering the requested file.
... (3) when data is starting to come from the webserver the nsichannel
calls the onstartrequest in the documenloader.
...And 8 more matches
PopupEvents - Archive of obsolete content
this will occur regardless of how the popup is opened, either from user interaction or from a script
calling the openpopup or openpopupatscreen methods.
...<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.
...<menu label="edit"> <menupopup onpopupshowing="if (gdisallowed) event.preventdefault();"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> in this example, a global variable gdisallowed is checked and the preventdefault method is
called.
...And 8 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
this event is only
called when the text displayed would change, thus it is not
called when the user presses non-displayable keys.
... onsearchbegin type: script code this event handler is
called when the autocomplete search begins.
... 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.
...And 8 more matches
Adding Event Handlers - Archive of obsolete content
although it does not matter what the script file is
called, usually it would be the same as the xul file with a .js extension.
...we'll define some functions in the file and we can
call them in event handlers.
...the command event is a useful event since it automati
cally handles different ways of activating the element.
...And 8 more matches
Custom Tree Views - Archive of obsolete content
the tree will
call methods of the view to get the information that it needs to display.
... in general, although the tree view has thirty or so functions that may be implemented, you only need to implement the ones that the tree will
call.
...this will be
called to display data for each cell.
...And 8 more matches
The Box Model - Archive of obsolete content
introduction to boxes the main form of layout in xul is
called the 'box model'.
...elements inside of a box will orient themselves horizontally or verti
cally.
...a box can lay out its children in one of two orientations, either horizontally or verti
cally.
...And 8 more matches
Tree Box Objects - Archive of obsolete content
the tree box object is a specialized box object used specifi
cally for trees.
...you don't need to
call the rowcountchanged() function when a row has simply changed in some way, for example if a cell's label changes.
...the simplest is to
call invalidaterow() which will redraw a specific row in the tree.
...And 8 more matches
XUL Structure - Archive of obsolete content
for this reason, mozilla provides a method of installing content lo
cally and registering the installed files as part of its chrome system.
... this allows a special url form,
called a chrome:// url, to be used.
...the extension will hook into the browser using a xul specific feature
called an overlay which allows the xul from the extension to mesh with the xul in the browser.
...And 8 more matches
panel - Archive of obsolete content
typi
cally, it will be attached to a button using the button's type attribute so that when the button is pressed, the panel will be displayed.
... the panel is closed when the user clicks outside the panel, presses escape or when the panel's hidepopup method is
called.
... consumeoutsideclicks type: boolean controls whether or not the event that caused the popup to be automati
cally dismissed (or "rolled up") should be consumed or be dispatched as a normal event.
...And 8 more matches
nsIContentPolicy - Archive of obsolete content
warning: do not block the
caller in your implementations of shouldload() or shouldprocess() (for example, by launching a dialog to prompt the user for something).") note: in reality, much of this interface is defined in the nsicontentpolicybase interface, but for now is documented here until someone has time to split things up.
... type_object 5 indicates a generic object (plugin-handled content typi
cally falls under this category).
...mozilla
callers will handle this like reject_request; third-party implementors may, for example, use this to direct their own
callers to consult the extra parameter for additional details.
...And 8 more matches
WAI-ARIA basics - Learn web development
<div class="nav">, but these were problematic, as there was no easy way to easily find a specific page feature such as the main navigation programmati
cally.
...many of these are so-
called landmark roles, which largely duplicate the semantic value of html5 structural elements e.g.
...states differ from properties in that properties don't change throughout the lifecycle of an app, whereas states can change, generally programmati
cally via javascript.
...And 8 more matches
JavaScript basics - Learn web development
these include: browser application programming interfaces (apis) built into web browsers, providing functionality such as dynami
cally creating html and setting css styles; collecting and manipulating a video stream from a user's webcam, or generating 3d graphics and audio samples.
...within the scripts folder, create a new file
called main.js, and save it.
...you did this by using a function
called queryselector() to grab a reference to your heading, and then store it in a variable
called myheading.
...And 8 more matches
Object-oriented JavaScript for beginners - Learn web development
object data (and often, functions too) can be stored neatly (the official word is encapsulated) inside an object package (which can be given a specific name to refer to, which is sometimes
called a namespace), making it easy to structure and access; objects are also commonly used as data stores that can be easily sent across the network.
...this process of creating an object instance from a class is
called instantiation — the object instance is instantiated from the class.
... constructors and object instances javascript uses special functions
called constructor functions to define and initialize objects and their features.
...And 8 more matches
Object building practice - Learn web development
the first part of the script looks like so: const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); const width = canvas.width = window.innerwidth; const height = canvas.height = window.innerheight; this script gets a reference to the <canvas> element, then
calls the getcontext() method on it to give us a context on which we can start to draw.
... next, we set constants
called width and height, and the width and height of the canvas element (represented by the canvas.width and canvas.height properties) to equal the width and height of the browser viewport (the area that the webpage appears on — this can be gotten from the window.innerwidth and window.innerheight properties).
... drawing the ball first add the following draw() method to the ball()'s prototype: ball.prototype.draw = function() { ctx.beginpath(); ctx.fillstyle = this.color; ctx.arc(this.x, this.y, this.size, 0, 2 * math.pi); ctx.fill(); } using this function, we can tell the ball to draw itself onto the screen, by
calling a series of members of the 2d canvas context we defined earlier (ctx).
...And 8 more matches
Deploying our app - Learn web development
netlify gives us hosting or more specifi
cally, a url to view your project online and to share it with your friends, family, and colleagues.
...we can commit our code and push to github and the updated code will automati
cally trigger the entire build routine.
... if all is well, we get a live change deployed automati
cally.
...And 8 more matches
Multiprocess on Windows
as you should already know from the prerequisite reading, single threaded apartments receive remote procedure
calls (rpcs) from com, via the windows message queue.
...this uses a com technology
called the interceptor.
...when an incoming rpc invokes a method on an interceptor, the interceptor dispatches a
callback that allows us to do whatever we want with that request.
...And 8 more matches
A bird's-eye view of the Mozilla framework
mozilla architectural modules are comprised of groups of related xpcom objects that provide services to and access services from each other through dynami
cally queryable interfaces.
... object model at a glance mozilla dynami
cally loads and integrates core modules and xul packages into the runtime environment on startup.
...the ability to dynami
cally integrate modules and packages at startup is a powerful benefit of the object model, which defines a module as a set of one or more xpcom objects
calledcomponents.
...And 8 more matches
Creating Sandboxed HTTP Connections
.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 channel 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.
...since this is a stream, it could be
called multiple times (depending on the size of the returned data, networking conditions, etc).
...And 8 more matches
Overview of Mozilla embedding APIs
mozilla's xpcom layer consists of a component model (
called xpcom) and the infrastructure necessary to support dynamic registration, instantiation and manipulation of xpcom components.
...much of the gecko functionality is exposed through a component
called the nswebbrowser.
...this must be the first function
call made into gecko.
...And 8 more matches
AddonListener
these notifications come in the form of
calls to methods on the listener object.
...sabled(in addon addon) void oninstalling(in addon addon, in boolean needsrestart) void oninstalled(in addon addon) void onuninstalling(in addon addon, in boolean needsrestart) void onuninstalled(in addon addon) void onoperationcancelled(in addon addon) void onpropertychanged(in addon addon, in string properties[]) methods onenabling()
called when an add-on is about to be enabled.
... void onenabling( in addon addon, in boolean needsrestart ) parameters addon the addon that is being enabled needsrestart true if an application restart is necessary for the change to take effect onenabled()
called when an add-on has been enabled.
...And 8 more matches
PopupNotifications.jsm
methods locationchange() the consumer can
call this method to let the popup notification module know that the current browser's location has changed.
... note: you shouldn't need to
call this when using the popupnotifications object in firefox windows; firefox code takes care of this automati
cally.
...
callback a javascript function to be invoked when the action is selected by the user.
...And 8 more matches
PromiseWorker.jsm
summary a promiseworker is a chromeworker except instead of
calling postmessage() to send a message, you
call post(), which returns a promise.
...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 discard) messages (optional) dump('worker: ' + args.join(' ') + '\n'); }; // connect it to message...
... post syntax promise = myworker.post(afunctionname, aargs, aclosure, atransferlist); parameters afunctionname the name of the function to be
called as it appears in the worker file.
...And 8 more matches
XPCOMUtils.jsm
// will be automati
cally returned from queryinterface if that was // generated with the generateqi helper.
... notice that the queryinterface() method implemented by the component simply
calls the generateqi() method provided by the xpcomutils code module.
...this array can of course have just one entry: var components = [mycomponent]; here, we're
calling the array components.
...And 8 more matches
Refcount tracing and balancing
refcount tracing logs
calls to addref and release, preferably for a particular set of classes, including
call-stacks in symbolic form (on platforms that support this).
... however, having an nscomptr log and using it in the creation of the balance tree allows addref and release
calls that we know are matched to be eliminated from the tree, so it makes it much easier to debug reference count leaks of objects that have a large amount of reference counting traffic.
... xpcom_mem_alloc_log for platforms that don't have stack-crawl support, xpcom supports logging at the
call site to addref/release using the usual cpp __file__ and __line__ number macro expansion hackery.
...And 8 more matches
NSPR Poll Method
the prototype of the poll method is print16 poll_method(prfiledesc *fd, print16 in_flags, print16 *out_flags); the purpose of the poll method is to allow a layer to modify that flags that will ultimately be used in the
call to the underlying network transport's select (or equivalent) function, and to indicate that a layer is already able to make progress in the manner suggested by the polling flags.
... in_flags [input argument] the in_flags argument specifies the events at the top layer of the i/o layer stack that the
caller is interested in.
...if the
caller wishes to test for read ready (that is, pr_poll_read is set in in_flags) and the layer has input data buffered, the poll method would set the pr_poll_read event in *out_flags.
...And 8 more matches
HTTP delegation
instead of improving the simple http client in nss, the nss team has decided to provide an nss api to register application
callback functions.
...in order to use the http delegation feature in your nss-based application, you need to implement several
callback functions.
... your
callback functions might be a full implementation of a http client.
...And 8 more matches
HTTP delegation
instead of improving the simple http client in nss, the nss team has decided to provide an nss api to register application
callback functions.
...in order to use the http delegation feature in your nss-based application, you need to implement several
callback functions.
... your
callback functions might be a full implementation of a http client.
...And 8 more matches
NSS_3.12_release_notes.html
eate can leave some members uninitialized bug 403910: cert_findusercertbyusage() returns wrong certificate if multiple certs with same subject available bug 404919: memory leak in sftkdb_readsecmoddb() (sftkmod.c) bug 406120: allow application to specify ocsp timeout bug 361025: support for camellia cipher suites to tls rfc4132 bug 376417: pk11_generatekeypair needs to get the key usage from the
caller.
...ls bug 327529: can't pass 0 as an unnamed null pointer argument to cert_createrdn bug 334683: extraneous semicolons cause empty declaration compiler warnings bug 335275: compile with the gcc flag -werror-implicit-function-declaration bug 354565: fipstest sha_test needs to detect sha tests that are incorrectly configured for bit oriented implementations bug 356595: on windows, rng_systeminfoforrng
calls getcurrentprocess, which returns the constant (handle)-1.
...bug 402114: fix the incorrect function prototypes of ssl handshake
callbacks bug 402308: fix miscellaneous compiler warnings in nss/cmd bug 402777: lib/util can't be built stand-alone.
...And 8 more matches
Tutorial: Embedding Rhino
in this document: runscript: a simple embedding entering a context initializing standard objects collecting the arguments evaluating a script printing the result exiting the context expose java apis using java apis implementing interfaces adding java objects using javascript objects from java using javascript variables
calling javascript functions javascript host objects defining host objects counter example counter's constructors class name dynamic properties defining javascript "methods" adding counter to runscript runscript: a simple embedding about the simplest embedding of rhino possible is the runscript example.
...the null parameter tells initstandardobjects to create and return a scope object that we use in later
calls.
...there should be a
call to exit for every
call to enter.
...And 8 more matches
GCIntegration - SpiderMonkey Redirect 1
it's better to store them in reserved slots, since those will automati
cally be traced if the object is native.
...spidermonkey uses a simple barrier commonly
called a "snapshot at the beginning" barrier.
... if a pointer is not traced via js_
call_tracer or any similar mechanism, then there's no need for a write barrier (although see below about read barriers).
...And 8 more matches
JSAutoByteString
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... str jsstring * a pointer to jsstring to get initial content by
calling js_encodestring(cx, str).
... char *encodelatin1(jscontext *cx, jsstring *str)
call js_encodestring and take ownership of the returned string, and return the string.
...And 8 more matches
JS_NewGlobalObject
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... the
caller must ensure that the jsclass remains alive throughout the lifetime of the new object, including the garbage collection cycle that finally frees it.
...it initially has no prototype either, since it is typi
cally the first object created;
call js_initstandardclasses to create all the standard objects, including object.prototype, and set the global object's prototype.
...And 8 more matches
SpiderMonkey 1.8.7
many jsapi types, functions, and
callback signatures have changed, though most of them still have the same names and do the same things.
... no compartment may execute js code or
call into jsapi on two os threads at the same time.
... the so-
called "slow natives" are no longer supported; as such jsfastnative has been renamed to jsnative and relevant interfaces have been updated accordingly.
...And 8 more matches
Components.utils.exportFunction
a function exported from privileged to less-privileged code can be
called from the less privileged code's context.
... the function has access to its surrounding closure just as if it were being
called in the privileged context.
...this does not have to be the global window object: it could be any other object in the target window, or an object created by the
caller.
...And 8 more matches
mozIAsyncFavicons
method overview void getfaviconurlforpage(in nsiuri apageuri, in nsifavicondata
callback a
callback); void getfavicondataforpage(in nsiuri apageuri, in nsifavicondata
callback a
callback); void setandfetchfaviconforpage(in nsiuri apageuri, in nsiuri afaviconuri, in boolean aforcereload, in unsigned long afaviconloadtype, [optional] in nsifavicondata
callback a
callback); void replacefavicondata(in nsiuri afaviconuri, [const,array,size_i...
...void getfaviconurlforpage( in nsiuri apageuri, in nsifavicondata
callback a
callback ); parameters apageuri uri of the page whose favicon's url we're looking up.
... a
callback once we have found the favicon's url, we invoke this
callback.
...And 8 more matches
mozIAsyncHistory
inherits from: nsisupports last changed in gecko 24.0 (firefox 24.0 / thunderbird 24.0 / seamonkey 2.21) implemented by: @mozilla.org/browser/history;1 as a service: var asynchistory = components.classes["@mozilla.org/browser/history;1"] .getservice(components.interfaces.moziasynchistory); method overview void getplacesinfo(in jsval aplaceidentifiers, in mozivisitinfo
callback a
callback); void isurivisited(in nsiuri auri, in mozivisitedstatus
callback a
callback); void updateplaces(in moziplaceinfo, [optional] in mozivisitinfo
callback a
callback); methods getplacesinfo() starts an asynchronous request to determine whether or not a given uri has been visited; you must implement a
callback to receive the result of the request.
... void getplacesinfo( in jsval aplaceidentifiers, in mozivisitinfo
callback a
callback ); parameters aplaceidentifiers the uri for which to determine the visited status.
... a
callback an object implementing the mozivisitedstatus
callback.isvisited() method.
...And 8 more matches
nsINavHistoryResultViewObserver
ondrop()
called when the user drops something onto the view being observed.
... ontoggleopenstate()
called when an item is opened or closed.
... oncycleheader()
called when a header is clicked.
...And 8 more matches
nsINavHistoryService
istoryqueryoptions options); autf8string queriestoquerystring([array, size_is(aquerycount)] in nsinavhistoryquery aqueries, in unsigned long aquerycount, in nsinavhistoryqueryoptions options); void addobserver(in nsinavhistoryobserver observer, in boolean ownsweak); void removeobserver(in nsinavhistoryobserver observer); void runinbatchmode(in nsinavhistorybatch
callback a
callback, in nsisupports aclosure); void importhistory(in nsifile file); astring getcharsetforuri(in nsiuri auri); astring setcharsetforuri(in nsiuri auri, in astring acharset); attributes attribute type description hashistoryentries boolean true if there is any history.
...it is
called by the url bar when the user types in a url.
... this can be and is
called before the page is actually added to history, since the page isn't added until it actually starts loading.
...And 8 more matches
nsIRadioInterfaceLayer
to create an instance, use: var radiointerfacelayer = components.classes["@mozilla.org/telephony/system-worker-manager;1"] .getservice(components.interfaces.nsiinterfacerequestor) .createinstance(components.interfaces.nsiradiointerfacelayer); method overview void answer
call(in unsigned long
callindex); void deactivatedata
call(in domstring cid, in domstring reason); void dial(in domstring number); void enumerate
calls(in nsiriltelephony
callback
callback); void getdata
calllist(); unsigned short getnumberofmessagesfortext(in domstring text); void hangup(in unsigned long
callindex); void register
callback(in nsiriltelephony
callback
callback); void register...
...data
callcallback(in nsirildata
callback
callback); void reject
call(in unsigned long
callindex); void sendsms(in domstring number, in domstring message, in long requestid, in unsigned long long processid); void setupdata
call(in long radiotech, in domstring apn, in domstring user, in domstring passwd, in long chappap, in domstring pdptype); void starttone(in domstring dtmfchar); void stoptone(); void unregister
callback(in nsiriltelephony
callback
callback); void unregisterdata
callcallback(in nsirildata
callback
callback); attributes attribute type description currentstate jsval read only.
... speakerenabled bool constants
call state constants constant value description
call_state_unknown 0
call_state_dialing 1
call_state_alerting 2
call_state_busy 3
call_state_connecting 4
call_state_connected 5
call_state_holding 6
call_state_held 7
call_state_resuming 8
call_state_disconnecting 9
call_state_disconnected 10
call_state_incoming 11 data
call_state_unknown 0 data
call_state_connecting 1 data
call_state_connected 2 data
call_state_disconnecting 3 data
call_state_disconnected 4
call_state_ringing 2 obsolete since gecko 14.0 methods answer
call() void answer
call( in unsigned long
callindex ); parameters
callindex missing descr...
...And 8 more matches
nsIThread
during the execution of this method
call, events for the current thread may continue to be processed.
... warning: this method may not be
called from the thread itself.
... instead, you must only
call it from another thread (usually the thread that created it, or the main application thread).
...And 8 more matches
nsITransactionManager
the listener's nsitransactionlistener.addref() method is
called.
... beginbatch() turns on the transaction manager's batch mode, forcing all transactions executed by the transaction manager's dotransaction() method to be aggregated together until endbatch() is
called.
... this mode allows an application to execute and group together several independent transactions so they can be undone with a single
call to undotransaction().
...And 8 more matches
Xray vision
xray vision helps javascript running in a privileged security context safely access objects created by less privileged code, by showing the
caller only the native version of the objects.
... the javascript code that along with the c++ core, implements the browser itself is
called chrome code and runs using system privileges.
... javascript loaded from normal web pages is
called content code.
...And 8 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.
... it can log all object allocations, yielding a stream of javascript
call stacks at which allocations have occurred.
... 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.
...And 8 more matches
Aggregate view - Firefox Developer Tools
there are three main ways to group the data: type
call stack inverted
call stack you can switch between them using the dropdown menu labeled "group by:" located at the top of the panel: there's also a box labeled "filter" at the top-right of the pane.
...if you select an item, you'll see the retaining paths panel for that item:
call stack the
call stack shows you exactly where in your code you are making heap allocations.
... because tracing allocations has a runtime cost, it must be explicitly enabled by checking "record
call stacks" before you allocate the memory in the snapshot.
...And 8 more matches
Using the CSS Painting API - Web APIs
the css paint api is designed to enable developers to programmati
cally define images which can then be used anywhere a css image can be invoked, such as css background-image, border-image, mask-image, etc.
... to programmati
cally create an image used by a css stylesheet we need to work through a few steps: define a paint worklet using the registerpaint() function register the worklet include the paint() css function to elaborate over these steps, we're going to start by creating a half-highlight background, like on this header: css paint worklet in an external script file, we employ the registerpaint() function to name our css paint worklet.
...the 2d rendering context is a subset of the html5 canvas api; the version available to houdini (
called the paintrenderingcontext2d) is a further subset containing most of the features available in the full canvas api with the exception of the canvasimagedata, canvasuserinterface, canvastext, and canvastextdrawingstyles apis.
...And 8 more matches
LockManager.request() - Web APIs
the requested lock is passed to a
callback, while the function itself returns a promise that resolves with undefined.
... syntax lockmanager.request(var promise = name[, {options}],
callback) parameters name an identifier for the lock you want to request.
...if it cannot be granted, the
callback will be invoked with null instead of a lock instance.
...And 8 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.
... dom observation does not begin immediately; the observe() method must be
called first to establish which portion of the dom to watch and what kinds of changes to watch for.
... 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.
...And 8 more matches
Using the Notifications API - Web APIs
typi
cally, system notifications refer to the operating system's standard notification mechanism: think for example of how a typical desktop system or mobile device broadcasts notifications.
...it stores data lo
cally using indexeddb and notifies users when tasks are due using system notifications.
...this is a common requirement when an api tries to interact with something outside a web page — at least once, the user needs to specifi
cally grant that application permission to present notifications, thereby letting the user control which apps/sites are allowed to display notifications.
...And 8 more matches
RTCPeerConnection.addTrack() - Web APIs
see starting negotiation in signaling and video
calling for details.
...since streams are specific to each peer, specifying one or more streams means the other peer will create a corresponding stream (or streams) automati
cally on the other end of the connection, and will then automati
cally add the received track to those streams.
... here's an example showing a function that uses getusermedia() to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track: async open
call(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track); } } the result is a set of tracks being sent to the remote peer, with no stream associations.
...And 8 more matches
Using the Screen Capture API - Web APIs
capturing screen contents capturing screen contents as a live mediastream is initiated by
calling navigator.mediadevices.getdisplaymedia(), which returns a promise that resolves to a stream containing the live screen contents.
... using the captured stream the promise returned by getdisplaymedia() resolves to a mediastream that contains at least one video stream that contains the screen or screen area, and which is adjusted or filtered based upon the constraints specifed when getdisplaymedia() was
called.
... user agents which take privacy seriously should obfuscate content that is not actually visible onscreen, unless authorization has been given to share that content specifi
cally.
...And 8 more matches
Background audio processing using AudioWorklet - Web APIs
an audio context's audio worklet is a worklet which runs off the main thread, executing audio processing code added to it by
calling the context's audioworklet.addmodule() method.
...
calling addmodule() loads the specified javascript file, which should contain the implementation of the audio processor.
... access the audio context's audioworklet through its audioworklet property, and
call the audio worklet's domxref("worklet.addmodule", "addmodule()")}} method to install the audio worklet processor module.
...And 8 more matches
Synchronous and asynchronous requests - Web APIs
asynchronous request if you use an asynchronous xmlhttprequest, you receive a
callback when the data has been received.
...the
callback routine is
called whenever the state of the request changes.
... function xhrsuccess() { this.
callback.apply(this, this.arguments); } function xhrerror() { console.error(this.statustext); } function loadfile(url,
callback /*, opt_arg1, opt_arg2, ...
...And 8 more matches
ARIA annotations - Accessibility
role="insertion" and role="deletion" — semanti
cally denote html elements whose contents represent an insertion to or deletion from the overall document.
... these are semanti
cally equivalent to the html <ins> and <del> elements.
... role="mark" — semanti
cally denotes html elements containing text that is marked/highlighted for reference purposes.
...And 8 more matches
HTML5 Parser - Developer guides
calls to innerhtml are a lot faster.
...
calling document.write() during parsing prior to html5, gecko and webkit allowed
calls to document.write() during parsing to insert content into the source stream.
...if the
call happened after the parser was done, the inserted content replaced the document.
...And 8 more matches
TypedArray.prototype.filter() - JavaScript
syntax typedarray.filter(
callback[, thisarg]) parameters
callback function to test each element of the typed array.
... thisarg optional value to use as this when executing
callback.
... 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 8 more matches
TypedArray.prototype.find() - JavaScript
syntax typedarray.find(
callback[, thisarg]) parameters
callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array.
... array the array find was
called upon.
...object to use as this when executing
callback.
...And 8 more matches
WebAssembly Concepts - WebAssembly
a set of web apis that the web app can
call to control web browser/device functionality and make things happen (dom, cssom, webgl, indexeddb, web audio api, etc.).
... histori
cally, the vm has been able to load only javascript.
...it has many advantages — it is dynami
cally typed, requires no compile step, and has a huge ecosystem that provides powerful frameworks, libraries, and other tools.
...And 8 more matches
jpm - Archive of obsolete content
installing jpm globally npm install jpm --global depending on your setup, you might need to run this as an administrator: sudo npm install jpm --global installing jpm lo
cally if you do not wish to, or are unable to, install jpm globally, you may instead install it lo
cally: cd $home && npm install jpm to run jpm from a terminal when installed lo
cally, you must add the directory "$home/node_modules/.bin/" to your terminal's path first.
... -p --profile= profile by default, jpm uses a clean temporary firefox profile each time you
call jpm run.
...the command: looks for a directory
called "test" within the current directory (or --addon-dir).
...And 7 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
prior to firefox 10, the chrome.manifest file you rely on wasn't loaded automati
cally for restartless add-ons.
... step 4: manually handle default preferences normal extensions load default preferences from a standardized file automati
cally.
...the big culprits are jsm files and locale files (namely property files), though in some situations this is true for dynami
cally loaded image files too.
...And 7 more matches
XPJS Components Proposal - Archive of obsolete content
we will have one native module -
called the xpjsmanager - which holds this system together.
...each .js file (let's
call it a module) is started up and run in the context of a relatively 'raw' js global object.
... when a xpjs component module is first installed - or at autoregistration time - the xpjsmanager will load the .js file into a fresh js environment, let its top level script run to do whatever initialization it wants to do, and then it will
call the module's nsregisterself function (passing the filespec of the .js file).
...And 7 more matches
XUL Events - Archive of obsolete content
if you
call event.preventdefault() within the listener the window will not close.
... attribute: onclose command this event handler is
called when an element is activated.
...you should always use the command event instead of click because it will be
called in all of the needed cases.
...And 7 more matches
Template Builder Interface - Archive of obsolete content
the processes of creating a builder for an element applies both when an element is created when the window is loaded and when an element is inserted dynami
cally.
...rebuilding and refreshing a template the main purpose of accessing the builder for an element is to
call its 'rebuild' method.
...the builder is accessible to unprivileged code, so the rebuild and refresh methods may be
called by remote code.
...And 7 more matches
Adding Properties to XBL-defined Elements - Archive of obsolete content
you can also add methods that can be
called.
... that way, all you need is to get a reference to the element (using document.getelementbyid or a similar function) and then get or set the additional properties and
call the methods on it.
...or, you may want the value to be calculated dynami
cally as it's asked for.
...And 7 more matches
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.
...because the component measures the wall clock time it takes for blocking plugin
calls to execute, the value includes both cpu time, the wait time between allocation of cpu time to the process as well as any disk i/o time.
... it is therefore techni
cally incorrect to say that the runtime is a measure of cpu use, however, it is a good representation of overall resources being consumed by the plugin.
...And 7 more matches
NPN_SetValue - Archive of obsolete content
this
call is used to inform the browser of variable information controlled by the plugin.
... variable values the function can set: nppvpluginwindowbool: sets windowed/windowless mode for plugin display; true=windowed, false=windowless nppvplugintransparentbool: sets transparent mode for display of a plugin; true=transparent, false=opaque nppvjavaclass nppvpluginwindowsize nppvplugintimerinterval nppvpluginscriptableinstance nppvpluginscriptableiid nppvjavascriptpush
callerbool: specifies whether you are pushing or popping the jscontext off the stack nppvpluginkeeplibraryinmemory: tells browser that the plugin dll should live longer than usual nppvpluginneedsxembed nppvpluginscriptablenpobject nppvformvalue nppvplugindrawingmodel value the value of the specified variable to be set.
...to set windowless operation,
call npn_setvalue with nppvpluginwindowbool as the variable parameter and false as the value parameter.
...And 7 more matches
RDF in Mozilla FAQ - Archive of obsolete content
datasource); if (remote.loaded) { alert("the datasource was already loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); // rdf/xml datasources are all nsirdfxmlsinks var sink = ds.queryinterface(components.interfaces.nsirdfxmlsink); // attach the observer to the datasource-as-sink sink.addxmlsinkobserver(observer); // now observer's methods will be
called-back as // the load progresses.
... } note that the observer will remain attached to the rdf/xml datasource unless removexmlsinkobserver is
called.
...an implementation of this interface will typi
cally combine the statements from several datasources together as a collective.
...And 7 more matches
Dealing with files - Learn web development
when you are working on a website lo
cally on your computer, you should keep all the related files in a single folder that mirrors the published website's file structure on the server.
...inside your chosen place, create a new folder
called web-projects (or similar).
...
call it test-site (or something more imaginative).
...And 7 more matches
Looping code - Learn web development
const cats = ['bill', 'jeff', 'pete', 'biggles', 'jasmin']; let info = 'my cats are
called '; const para = document.queryselector('p'); for (let i = 0; i < cats.length; i++) { info += cats[i] + ', '; } para.textcontent = info; this gives us the following output: hidden code 2 <!doctype html> <html> <head> <meta charset="utf-8"> <title>basic for loop example</title> <style> </style> </head> <body> <p></p> <script> const cats = ['bill', 'jeff...
...', 'pete', 'biggles', 'jasmin']; let info = 'my cats are
called '; const para = document.queryselector('p'); for (let i = 0; i < cats.length; i++) { info += cats[i] + ', '; } para.textcontent = info; </script> </body> </html> note: you can find this example code on github too (also see it running live).
... one small problem we are left with is that the final output sentence isn't very well-formed: my cats are
called bill, jeff, pete, biggles, jasmin, ideally, we want to change the concatenation on the final loop iteration so that we haven't got a comma on the end of the sentence.
...And 7 more matches
Fetching data from the server - Learn web development
you can
call this object anything you like, but we'll
call it request to keep things simple.
... fetch the fetch api is basi
cally a modern replacement for xhr; it was introduced in browsers recently to make asynchronous http requests easier to do in javascript, both for developers and other apis that build on top of fetch.
... this function is automati
cally given the response from the server as a parameter when the fetch() promise resolves.
...And 7 more matches
Storing the information you need — Variables - Learn web development
declaring a variable to use a variable, you've first got to create it — more accurately, we
call this declaring the variable.
... to do this, we type the keyword var or let followed by the name you want to
call your variable: let myname; let myage; here we're creating two variables
called myname and myage.
...this works basi
cally fine in most cases, but it has some issues in the way it works — its design can sometimes be confusing or downright annoying.
...And 7 more matches
Object prototypes - Learn web development
what happens if you
call a method on person1, which is actually defined on object.prototype?
... for example: person1.valueof() valueof() returns the value of the object it is
called on.
...so the method is
called, and all is good!
...And 7 more matches
Application cache implementation overview
the association happens in nscontentsink::processofflinemanifest()
called from the html parser every time <html> tag has been parsed.
...the inheritapplicationcache flag instructs the channel to do getinterface on its
callbacks for nsiapplicationcachecontainer.
...when the update is about to actually start, the scheduling service
calls nsofflinecacheupdate::begin() method, that switches the update to checking state (+invokes onchecking event) and starts fetch of the manifest file.
...And 7 more matches
Chrome registration
toolbars, menu bars, progress bars, and window title bars are all examples of elements that are typi
cally part of the chrome.
... chrome providers a supplier of chrome for a given window type (e.g., for the browser window) is
called a chrome provider.
...it will typi
cally be a xul file, since xul is designed for describing the contents of windows and dialogs.
...And 7 more matches
Creating localizable web applications
define the locale and the direction in the html generate the lang attribute dynami
cally, depending on the current locale.
... in most of the cases though, you should use gettext whenever techni
cally possible (i.e.
...good: function num_format($num, $decimals) { $locale_info = localeconv(); return number_format($num, $decimals, $locale_info['decimal_point'], $locale_info['thousands_sep']); } printf(_("%s mb"), num_format($size, 1)); wrap as few html tags as possible when wrapping the localizable content with the gettext function
calls, put all the code that irrelevant to localization outside the function
call.
...And 7 more matches
Power profiling overview
xeon) typi
cally have two or more packages.
... each core typi
cally has hyper-threading, which means it contains two logical cpus.
... the part of the package outside the cores is
called the uncore or system agent.
...And 7 more matches
Exact Stack Rooting
the private field is frequently used to store things that are not gcpointers, so the gc cannot automati
cally handle this slot.
...instead, spidermonkey has a convenient suite of c++ raii classes to do this for you,
called js::rootedt: rootedstring str1(cx, js_valuetostring(cx, val)); rootedstring str2(rt, js_valuetostring(cx, val)); note 1: c++ insists that an initializing assignment (e.g., the default constructor followed by operator=) must have a copy constructor available, even if it is not used.
... any single gcthing is likely to get passed through a fairly deep
call-stack before getting used.
...And 7 more matches
Self-hosted builtins in SpiderMonkey
most importantly, it's possible to invoke any function within the scope of any object using the syntax
callfunction(fun, receiver, ...args) (or
callcontentfunction, see below), which causes fun to be
called within the scope of receiver with ...args as its arguments.
... in contrast to function.prototype.
call, this syntax makes it impossible for other code to interfere and gets compiled to bytecode that doesn't have any overhead compared to a normal function invocation.
... otoh, normal method
calls are forbidden in self-hosted code.
...And 7 more matches
JSObjectPrincipalsFinder
jsobjectprincipalsfinder is the type of a security
callback that can be configured using js_setobjectprincipalsfinderjsapi 1.8 and earlier or js_setruntimesecurity
callbacksadded in spidermonkey 1.8.1.
...
callback syntax typedef jsprincipals * (* jsobjectprincipalsfinder)(jscontext *cx, jsobject *obj); name type description cx jscontext * the context in which to find principals.
... description the javascript engine
calls this
callback to obtain principals for a jsprincipals.subsume check.
...And 7 more matches
JS_AddExternalStringFinalizer
syntax int js_addexternalstringfinalizer(jsstringfinalizeop finalizer); name type description finalizer jsstringfinalizeop pointer to a
callback function, described below.
... the js engine will automati
cally
call this function each time a string created by js_newexternalstring is garbage-collected.
...
callback syntax typedef void (*jsstringfinalizeop)(jscontext *cx, jsstring *str); name type description cx jscontext * pointer to a jscontext which the finalizer may use for certain very limited operations (not documented).
...And 7 more matches
JS_ConvertArguments
syntax bool js_convertarguments(jscontext *cx, const js::
callargs &args, const char *format, ...); // added in spidermonkey 31 bool js_convertarguments(jscontext *cx, unsigned argc, jsval *argv, const char *format, ...); // obsolete since jsapi 30 name type description cx jscontext * the context in which to perform any necessary conversions.
... cx also affects the interpretation of format, if js_addargumentformatter has been
called.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...And 7 more matches
JS_PropertyStub
default implementations of the required
callbacks in jsclass.
...eded); // obsolete since jsapi 37 bool js_enumeratestub(jscontext *cx, js::handleobject obj); // obsolete since jsapi 37 bool js_convertstub(jscontext *cx, js::handleobject obj, jstype type, js::mutablehandlevalue vp); // obsolete since jsapi 37 void js_finalizestub(jscontext *cx, jsobject *obj); // obsolete since jsapi 14 description the stub functions are not designed to be
called directly by a jsapi application.
... rather, they are convenient stand-ins anywhere the jsapi requires
callbacks of certain types.
...And 7 more matches
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 automati
cally do account confirmation steps for you.
... note that the testfile is not a path, it should only be the filename from services/sync/tests/tps/ runtps --debug --testfile %test_file_name% --binary %firefox_binary_path% additionally, omitting a --testfile parameter will cause it to run all tps tests listed in services/sync/tests/tps/all_tests.json an example on osx, for running just the test_sync.js testfile against a lo
cally built firefox (where the mozconfig set the objdir to obj-ff-artifact): runtps --debug --testfile test_sync.js --binary obj-ff-artifact/dist/nightly.app/contents/macos/firefox running tps against stage, or dev fxa tps can be configured using the $tps_venv_path/config.json file.
...typi
cally there are two profiles used, but any number of profiles could be used in theory (other than 0).
...And 7 more matches
Setting up an update server
the goal of this document is to provide instructions for installing a lo
cally-served firefox update.
... building a mar building a mar lo
cally is more complicated.
...if you want to use a lo
cally-built mar, the copy of firefox being updated will need to be built to allow un-signed mars.
...And 7 more matches
Accessing the Windows Registry Using XPCOM
second, you must
call open() on the key before attempting to read a value.
... notice in the open()
call that the root key to use is specified using the named constants available on the nsiwindowsregkey interface, in this case root_key_local_machine, which corresponds to hkey_local_machine in the windows registry.
...note that it is not an error to
call create() on an existing key, and doing so has the same result as
calling open().
...And 7 more matches
mozIStorageAggregateFunction
last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void onstep(in mozistoragevaluearray afunctionarguments); nsivariant onfinal(); methods onstep() this is
called for each row of results returned by the query.
... note this
callback is executed on the thread that the statement or trigger is executing on.
... if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this
callback will run on a different thread from the rest of your code.
...And 7 more matches
mozIStorageFunction
last changed in gecko 1.9.1.4 (firefox 3.5.4) inherits from: nsisupports method overview nsivariant onfunction
call(in mozistoragevaluearray afunctionarguments); methods onfunction
call() the implementation of the function.
... this is
called by the database engine when the function registered with mozistorageconnection.createfunction() is used in an executing sql statement or trigger.
... note this
callback is executed on the thread that the statement or trigger is executing on.
...And 7 more matches
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 do any bookkeeping.
... it is
called after the container has been moved.
... oncontainernodeclosed() this method is
called when the given container has just been collapsed so that the service can do any necessary cleanup.
...And 7 more matches
nsIFaviconService
rpage(in nsiuri apageuri); obsolete since gecko 22.0 nsiuri getfaviconlinkforicon(in nsiuri afaviconuri); boolean isfailedfavicon(in nsiuri afaviconuri); void removefailedfavicon(in nsiuri afaviconuri); void setandloadfaviconforpage(in nsiuri apageuri, in nsiuri afaviconuri, in boolean aforcereload, in unsigned long afaviconloadtype, [optional] in nsifavicondata
callback a
callback); obsolete since gecko 22.0 void setfavicondata(in nsiuri afaviconuri, [const,array,size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, in prtime aexpiration); obsolete since gecko 22.0 void setfavicondatafromdataurl(in nsiuri afaviconuri, in astring adataurl, in prtime aexpiration); obsolete since gecko 22.0 void setfa...
...an async request will be created for this uri and if the data is available, it will asynchronously get saved in the database without any further work from the
caller.
...icons that fail to load will automati
cally be added to the failed favicon cache.
...And 7 more matches
nsIFeedProgressListener
toolkit/components/feeds/public/nsifeedlistener.idlscriptable this interface defines
callbacks used during the processing of an rss or atom feed.
... programs using the feed content access api do not have to implement any of these
callbacks; they are optional, but allow you to provide feedback during the parsing process.
... changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void handleentry(in nsifeedentry entry, in nsifeedresult result); void handlefeedatfirstentry(in nsifeedresult result); void handlestartfeed(in nsifeedresult result); void reporterror(in astring errortext, in long linenumber, in boolean bozo); methods handleentry()
called after each entry or item is processed.
...And 7 more matches
nsIFilePicker
stance, use: var filepicker = components.classes["@mozilla.org/filepicker;1"] .createinstance(components.interfaces.nsifilepicker); method overview void appendfilter(in astring title, in astring filter); void appendfilters(in long filtermask); void init(in nsidomwindow parent, in astring title, in short mode); void open(in nsifilepickershown
callback afilepickershown
callback); short show(); obsolete since gecko 57.0 attributes attribute type description addtorecentdocs boolean if true, the file is added to the operating system's "recent documents" list (if the operating system has one; nothing happens if there is no such concept on the user's platform).
...on some platforms, this is automati
cally appended to filenames the user enters, if required.
...this should be set before
calling open() or show().
...And 7 more matches
nsILoginManager
note: this method is provided for use only by the formfillcontroller, which
calls it directly.
...
called when only the number of logins is needed, and not the actual logins (which avoids prompting the user for a master password, as the logins don't need to be decrypted).
...
called when looking for logins that might be applicable to a given form or authentication request.
...And 7 more matches
nsIProcessScriptLoader
process scripts are loaded as soon as loadprocessscript() is
called.
... if this function is
called on a chromemessagebroadcaster, : it will load the process script into all child processes.
... if aallowdelayedload is true, then the script will also be loaded into any new child processes created after the loadprocessscript()
call.
...And 7 more matches
nsISupports proxies
xpcom proxies were a technology which allowed code to make asynchronous or synchronous xpcom
calls to a different thread on arbitrary xpcom interfaces.
...for more information about alternatives, see making cross-thread
calls using runnables.
... about xpcom proxies a proxy, in this context, is a stub object which enables a method of any class which is derived from nsisupports and has a typelib to be
called on any in-process thread.
...And 7 more matches
nsIWebSocketListener
netwerk/protocol/websocket/nsiwebsocketlistener.idlscriptable implement this interface to receive websocket traffic events asynchronously after
calling nsiwebsocketchannel.asyncopen().
...binarymessageavailable(in nsisupports acontext, in acstring amsg); void onmessageavailable(in nsisupports acontext, in autf8string amsg); void onserverclose(in nsisupports acontext, in unsigned short acode, in autf8string areason); void onstart(in nsisupports acontext); void onstop(in nsisupports acontext, in nsresult astatuscode); methods onacknowledge()
called to acknowledge a message sent via nsiwebsocketchannel.sendmsg() or nsiwebsocketchannel.sendbinarymsg().
... onbinarymessageavailable()
called when a binary message has been received.
...And 7 more matches
nsIZipWriter
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) once all the operations you wish to perform are added to the queue, a
call to processqueue() will perform the operations in the order they were added to the queue.
...will be performed when processqueue() is
called.
...zw.addentryfile(saveinzipas, ci.nsizipwriter.compression_none, filetoaddtozip, false); this example creates a folder in the zip
called "sub folder" and then adds "c:\add this file.txt" to it, but it will be
called "blah.txt".
...And 7 more matches
Weak reference
to do that, it will
call a method on the observer, so it needs a pointer.
... and the
call would fail if the pointer were allowed to dangle, therefore, the pointer should be a owning reference.
...when the referent is destroyed, the weak reference automati
cally becomes nsnull.
...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).
...mozilla does this by
calling the old plugin api
call npp_getvalue with the new enumeration value that has been added to the nppvariable enumeration.
...the threading model for this api is such that all
calls through this api are synchronous and
calls from a plugin to methods in this api must come from the thread on which the plugin was initiated, and likewise all
calls to methods in this api by the browser are guaranteed to come from the same thread.
...And 7 more matches
Manipulating video using canvas - Web APIs
initializing the chroma-key player the doload() method is
called when the xhtml document initially loads.
...= document.getelementbyid('video'); this.c1 = document.getelementbyid('c1'); this.ctx1 = this.c1.getcontext('2d'); this.c2 = document.getelementbyid('c2'); this.ctx2 = this.c2.getcontext('2d'); let self = this; this.video.addeventlistener('play', function() { self.width = self.video.videowidth / 2; self.height = self.video.videoheight / 2; self.timer
callback(); }, false); }, this code grabs references to the elements in the xhtml document that are of particular interest, namely the video element and the two canvas elements.
... then addeventlistener() is
called to begin watching the video element so that we obtain notification when the user presses the play button on the video.
...And 7 more matches
Document.requestStorageAccess() - Web APIs
grant the document access to cookies and other site storage and store that fact for the purposes of future
calls to document.hasstorageaccess() and requeststorageaccess().
... assuming all of the requirements above are satisfied, firefox will automati
cally grant storage access to the requesting origin on up to a threshold number of first-party origins in the current session for the duration of user’s session, up to a maximum of 24 hours.
... after the requesting origin has exceeded the maximum allowable number of storage access grants, any future
call to requeststorageaccess() during the same browsing session will prompt the user.
...And 7 more matches
MediaDevices.getUserMedia() - Web APIs
if one cannot be included for any reason, the
call to getusermedia() will result in an error.
...whereas plain values and a keyword
called ideal are not.
... securityerror user media support is disabled on the document on which getusermedia() was
called.
...And 7 more matches
MutationObserver.observe() - Web APIs
the mutationobserver method observe() configures the mutationobserver
callback to begin receiving notifications of changes to the dom that match the given options.
... to stop the mutationobserver (so that none of its
callbacks will be triggered any longer),
call mutationobserver.disconnect().
... options a mutationobserverinit object providing options that describe which dom mutations should be reported to mutationobserver’s
callback.
...And 7 more matches
Using the Payment Request API - Web APIs
on buildshoppingcartdetails() { // hardcoded for demo purposes: return { id: 'order-123', displayitems: [ { label: 'example item', amount: {currency: 'usd', value: '1.00'} } ], total: { label: 'total', amount: {currency: 'usd', value: '1.00'} } }; } starting the payment process once the paymentrequest object has been created, you
call the paymentrequest.show() method on it to initiate the payment request.
...in the code above, you'll see that we've
called the paymentresponse.complete() method to signal that the interaction has finished — you'd use this to carry out finishing steps, like updating the user interface to tell the user the transaction is complete, etc.
...for example, redirect to // the legacy web form checkout: window.location.href = '/legacy-web-form-checkout'; }); // every click on the checkout button should use a new instance of // paymentrequest object, because paymentrequest.show() can be //
called only once per instance.
...And 7 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
the senders for a given connection can be obtained by
calling rtcpeerconnection.getsenders().
...a connection's receivers can be obtained by
calling rtcpeerconnection.getreceivers().
...among the simplest things you can do is to implement a "hold" feature, wherein a participant in a
call can click a button and turn off their microphone, begin sending music to the other peer instead, and stop accepting incoming audio.
...And 7 more matches
Web Locks API - Web APIs
the lock is automati
cally released when the task completes.
...it takes a lock name, an optional set of options, and a
callback.
... the
callback is invoked when the lock is granted.
...And 7 more matches
XRSession.requestAnimationFrame() - Web APIs
the xrsession method requestanimationframe(), much like the window method of the same name, schedules a
callback to be executed the next time the browser is ready to paint the session's virtual environment to the xr display.
... the specified
callback is executed once before the next repaint; if you wish for it to be executed for the following repaint, you must
call requestanimationframe() again.
... this can be done from within the
callback itself.
...And 7 more matches
Constraint validation - Developer guides
intrinsic and basic constraints in html5, basic constraints are declared in two ways: by choosing the most semanti
cally appropriate value for the type attribute of the <input> element, e.g., choosing the email type automati
cally creates a constraint that checks whether the value is a valid e-mail address.
... typemismatch constraint violation <input type="email"> the value must be a syntacti
cally valid email address, which generally has the format username@hostname.tld.
...the constraint validation is done in the following ways: by a
call to the checkvalidity() or reportvalidity() method of a form-associated dom interface, (htmlinputelement, htmlselectelement, htmlbuttonelement, htmloutputelement or htmltextareaelement), which evaluates the constraints only on this element, allowing a script to get this information.
...And 7 more matches
<input type="email"> - HTML: Hypertext Markup Language
the input value is automati
cally validated to ensure that it's either empty or a properly-formatted e-mail address (or list of addresses) before the form can be submitted.
... the :valid and :invalid css pseudo-classes are automati
cally applied as appropriate to visually denote whether the current value of the field is a valid e-mail address or not.
...mstring representing an e-mail address, or empty events change and input supported common attributes autocomplete, list, maxlength, minlength, multiple, name,pattern, placeholder, readonly, required, size, and type idl attributes list and value methods select() value the <input> element's value attribute contains a domstring which is automati
cally validated as conforming to e-mail syntax.
...And 7 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
autoplay a boolean attribute; if specified, the video automati
cally begins to play back as soon as it can do so without stopping to finish loading the data.
... note: sites that automati
cally play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible.
... if you must offer autoplay functionality, you should make it opt-in (requiring a user to specifi
cally enable it).
...And 7 more matches
Closures - JavaScript
lexical scoping consider the following example code: function init() { var name = 'mozilla'; // name is a local variable created by init function displayname() { // displayname() is the inner function, a closure alert(name); // use variable declared in the parent function } displayname(); } init(); init() creates a local variable
called name and a function
called displayname().
...the code is attached as a
callback (a single function that is executed in response to the event).
... emulating private methods with closures languages such as java allow you to declare methods as private, meaning that they can be
called only by other methods in the same class.
...And 7 more matches
Expressions and operators - JavaScript
this behavior generally results in comparing the operands numeri
cally.
... logical operators logical operators are typi
cally used with boolean (logical) values; when they are, they return a boolean value.
...obj = {h: 4}; // create object with property h delete x; // returns true (can delete if created implicitly) delete y; // returns false (cannot delete if declared with var) delete math.pi; // returns false (cannot delete non-configurable properties) delete myobj.h; // returns true (can delete user-defined properties) deleting array elements since arrays are just objects, it's techni
cally possible to delete elements from them.
...And 7 more matches
Memory Management - JavaScript
in contrast, javascript automati
cally allocates memory when objects are created and frees it when they are not used anymore (garbage collection).
... allocation in javascript value initialization in order to not bother the programmer with allocations, javascript will automati
cally allocate memory when values are initially declared.
... var n = 123; // allocates memory for a number var s = 'azerty'; // allocates memory for a string var o = { a: 1, b: null }; // allocates memory for an object and contained values // (like object) allocates memory for the array and // contained values var a = [1, null, 'abra']; function f(a) { return a + 2; } // allocates a function (which is a
callable object) // function expressions also allocate an object someelement.addeventlistener('click', function() { someelement.style.backgroundcolor = 'blue'; }, false); allocation via function
calls some function
calls result in object allocation.
...And 7 more matches
Arrow function expressions - JavaScript
an arrow function expression is a syntacti
cally 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.
... undefined in strict mode function
calls.
...And 7 more matches
Object - JavaScript
when
called in a non-constructor context, object behaves identi
cally to new object().
... object.prototype.__nosuchmethod__ allows a function to be defined that will be executed when an undefined object member is
called as a method.
... object.prototype.isprototypeof() returns a boolean indicating whether the object this method is
called upon is in the prototype chain of the specified object.
...And 7 more matches
TypedArray.prototype.every() - JavaScript
syntax typedarray.every(
callback[, thisarg]) parameters
callback function to test for each element, taking three arguments: currentvalue the current element being processed in the typed array.
... array the typed array every was
called upon.
...value to use as this when executing
callback.
...And 7 more matches
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.
... array the array foreach() was
called upon.
...value to use as this when executing
callback.
...And 7 more matches
eval() - JavaScript
do not
call eval() to evaluate an arithmetic expression; javascript evaluates arithmetic expressions automati
cally.
...you can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then
calling eval() at a later point in your script.
...this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being
called.
...And 7 more matches
yield - JavaScript
description the yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's
caller.
... yield can only be
called directly from the generator function that contains it.
... it cannot be
called from nested functions or from
callbacks.
...And 7 more matches
panel - Archive of obsolete content
if you want to close an existing panel without opening a new one, you can
call the hide() or the destroy() method.
...in the sdk these scripts are
called "content scripts" because they're explicitly used for interacting with web content.
...function handleclick(state) { textentrypanel.show(); } // when the panel is displayed it generated an event
called // "show": we will listen for that event and when it happens, // send our own "show" event to the panel's script, so the // script can prepare the panel for display.
...And 6 more matches
core/promise - Archive of obsolete content
instead of structuring our programs into logical black boxes: function blackbox(a, b) { var c = assemble(a); return combine(b, c); } we're forced into continuation passing style, involving lots of machinery: function sphagetti(a, b,
callback) { assemble(a, function continuewith(error, c) { if (error)
callback(error); else combine(b, c,
callback); }); } this style also makes doing things in sequence hard: widget.on('click', function onclick() { promptuserfortwitterhandle(function continuewith(error, handle) { if (error) return ui.displayerror(error); twitter.gettweetsfor(handle, funtion continuewith(error, ...
... promises consider another approach, instead of continuation via
callbacks, a function returns an object that represents a eventual result, either successful or failed.
...we can
call a function on the promise to observe either its fulfillment or rejection.
...And 6 more matches
places/bookmarks - Archive of obsolete content
the module does not automati
cally sync up a bookmark instance with ongoing changes to that item in the database from the same add-on, other add-ons, or the user.
... save(bookmarks).on("data", function (saved, input) { // a data event is
called once for each item saved, as well // as implicit items, like `group` console.log(input === group || ~bookmarks.indexof(input)); // true }).on("end", function (saves, inputs) { // like the previous example, the "end" event returns an // array of all of our updated saves.
... updating items: for an item referenced from a previous save() or from the result of a search() query, changing the properties and
calling save() will update the item on the server.
...And 6 more matches
system/unload - Archive of obsolete content
experimental register
callbacks that are
called when a module is unloaded.
... globals functions ensure(object, name)
calling ensure() on an object does two things: it replaces a destructor method with a wrapper method that will never
call the destructor more than once.
... it ensures that this wrapper method is
called when the object's module is unloaded.
...And 6 more matches
cfx - Archive of obsolete content
cfx init create a new directory
called "my-addon", change into it, and run cfx init.
...
called with no options it looks for a file
called package.json in the current directory, loads the corresponding add-on, and runs it under the version of firefox it finds in the platform's default install path.
...
called with no options this command will look for a file
called package.json in the current directory.
...And 6 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
here we
call the event myextensionevent.
...so to trigger the right event on the right page we have to tell the extension which page to
call.
... the code containing the
callback could look like this: in the extension: var myextension = { mylistener: function(evt) { alert("received from web page: " + evt.target.getattribute("attribute1") + "/" + evt.target.getattribute("attribute2")); /* the extension answers the page*/ evt.target.setattribute("attribute3", "the extension"); var doc = evt.target.ownerdocument; var answer...
...And 6 more matches
Appendix D: Loading Scripts - Archive of obsolete content
because there are such a diverse array of add-ons, and because the needs of developers have grown organi
cally over time, the gecko runtime provides a number of means to dynami
cally load and execute javascript files.
...these tags are generally inserted into xul overlay files or other xul documents, after which they are automati
cally loaded into the context of the xul window in question and executed immediately and synchronously.
...this is easily resolved by deferring the work to a dynami
cally added onload hander.
...And 6 more matches
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
techni
cally, there are 13 total stylesheets used at any one time.
...as a very welcome side benefit, we also believe the accessibility of wired news will dramati
cally improve without the clutter of nested layout tables.
...but adding a third column to the mix created too many width variables for some browsers to dynami
cally calculate a total.
...And 6 more matches
Commands - Archive of obsolete content
you don't need to use commands, since you can just
call a script to handle things.
... any buttons and menu items hooked up to it will be disabled automati
cally.
...you can also invoke a command by
calling the docommand method either of the command element or an element attached to the command such as a button.
...And 6 more matches
Document Object Model - Archive of obsolete content
function gettext(){ return "message"; } alert(gettext()); alert(window.gettext()); thus, if you want to access variables or
call a function declared in a script used by another window, you just need to access it using the other window's window object.
... for example, if we combined the last two examples into a single file, we might want to
call the gettext() function from within the other window (for example, the test.xul window).
...in this example, we retrieve the opener window and
call the gettext() function declared in a script used there.
...And 6 more matches
Skinning XUL Files by Hand - Archive of obsolete content
in the very near future, it will be possible to skin xul files dynami
cally and completely -- by pressing a button, selecting a skin from a menu, or by accepting a skin from over the web.
...also, most of the behavior that buttons exhibit comes from styles and an event model based on javascript that dynami
cally switches between these styles.
...the ability to apply styles to elements of a type, to specifi
cally identified elements, and to classes of elements creates the potential for redundancies or conflicts in the style information.
...And 6 more matches
NPN_RequestRead - Archive of obsolete content
this initiates a read operation; the actual data is received through subsequent
calls to npp_writeready() and npp_write().
...the plug-in
calls npn_requestread() to request data from a seekable stream.
...these requests result in subsequent
calls to npp_writeready() and npp_write().
...And 6 more matches
Debug - Archive of obsolete content
its properties and methods are
called off the debug class.
... constants async
callback status codes contant description value debug.ms_async_
callback_status_assign_delegate the synchronous work item assigned a
callback or continuation to be run by an asynchronous operation.
... 0 debug.ms_async_
callback_status_join the synchronous work item satisfied part of a join asynchronous operation.
...And 6 more matches
XForms Custom Controls - Archive of obsolete content
we will also show you how to create custom controls that work with the xforms model and are automati
cally updated just like xforms controls.
... </body> </method> <constructor> // we should redirect
calls of input's 'refresh' method to custom control 'refresh' method.
...there are two main groups of interfaces ->
callback interfaces that must be implemented by the custom controls and the interfaces that custom controls can use to access the mozilla xforms engine.
...And 6 more matches
Windows Media in Netscape - Archive of obsolete content
javascript will dynami
cally write out what browser you are running, and what kind of windows media player technology you may have.
...= 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/download/default.asp } if (player) { // windows media player control exists } currently, dynami
cally writing out markup using document.write after using detection mechanisms won't work owing to a bug in netscape 7.1.
...) { 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 property, only in 7 and 9 var versionstring = player.versioninfo; alert(versionstring); } only geckoactivexobject allows for the use of the windows media player classid as an argument.
...And 6 more matches
Flexbox - Learn web development
the following simple layout requirements are either difficult or impossible to achieve with such tools, in any kind of convenient, flexible way: verti
cally centering a block of content inside its parent.
...as rows across the page, or columns down the page.) the start and end of this axis are
called the main start and main end.
...the start and end of this axis are
called the cross start and cross end.
...And 6 more matches
The web and web standards - Learn web development
brief history of the web we'll keep this very brief, as there are many (more) detailed accounts of the web's history out there, which we'll link to later on (also try searching for "history of the web" in your favorite search engine and see what you get, if you are interested in more detail.) in the late 1960s, the us military developed a communication network
called arpanet.
... in 1980, tim berners-lee (often referred to as timbl) wrote a notebook program
called enquire, which featured the concept of links between different nodes.
... by late 1990, timbl had created all the things needed to run the first version of the web — http, html, the first web browser, which was
called worldwideweb, an http server, and some web pages to look at.
...And 6 more matches
Introduction to events - Learn web development
a series of fortunate events as mentioned above, events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automati
cally taken (that is, some code running) when the event occurs.
...note: event handlers are sometimes
called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together.
...in: 10px }; the javascript looks like so: const btn = document.queryselector('button'); function random(number) { return math.floor(math.random() * (number+1)); } btn.onclick = function() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } in this code, we store a reference to the button inside a constant
called btn, using the document.queryselector() function.
...And 6 more matches
Making decisions in your code — conditionals - Learn web development
in this article, we'll explore how so-
called conditional statements work in javascript.
... a condition to test, placed inside the parentheses (typi
cally "is this value bigger than this other value?", or "does this value exist?").
... when this function is run, we first set a variable
called choice to the current value selected in the <select> element.
...And 6 more matches
Manipulating documents - Learn web development
you can see here that each element and bit of text in the document has its own entry in the tree — each one is
called a node.
...the above queryselector()
call will match the first <a> element that appears in the document.
... if you wanted to match and do things to multiple elements, you could use document.queryselectorall(), which matches every element in the document that matches the selector, and stores references to them in an array-like object
called a nodelist.
...And 6 more matches
Third-party APIs - Learn web development
this typi
cally involves first linking to a javascript library available on the server via a <script> element, as seen in our mapquest example: <script src="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.js"></script> <link type="text/css" rel="stylesheet" href="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.css"/> you can then start using the objects available in that library.
...these are
called restful apis — we'll show an example later on.
...(at the time of writing, it was
called a "consumer key" on the site, and the key creation process also asked for an optional "
callback url".
...And 6 more matches
Video and Audio APIs - Learn web development
the htmlmediaelement api part of the html5 spec, the htmlmediaelement api provides features to allow you to control video and audio players programmati
cally — for example htmlmediaelement.play(), htmlmediaelement.pause(), etc.
...
call it custom-player.js.
... if it hasn't yet been set, we add the active class to the rwd button using classlist.add(), pause the video using htmlmediaelement.pause(), then set the intervalrwd variable to equal a setinterval()
call.
...And 6 more matches
JavaScript object basics - Learn web development
object basics an object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are
called properties and methods when they are inside objects.) let's work through an example to understand what they look like.
...next you write a dot, then the item you want to access — this can be the name of a simple property, an item of an array property, or a
call to one of the object's methods, for example: person.age person.interests[1] person.bio() sub-namespaces it is even possible to make the value of an object member another object.
...instead of using these: person.age person.name.first you can use person['age'] person['name']['first'] this looks very similar to how you access the items in an array, and it is basi
cally the same thing — instead of using an index number to select an item, you are using the name associated with each member's value.
...And 6 more matches
Ember interactivity: Events, classes and state - Learn web development
note: a decorator is basi
cally a wrapper function, which wraps and
calls other functions or properties, providing additional functionality along the way.
... for example, the @tracked decorator (see slightly later on) runs code it is applied to, but additionally tracks it and automati
cally updates the app when values change.
...ember
calls these constructs services, and they live for the entire lifetime of the page (a page refresh will clear them; persisting the data for longer is beyond the scope of this tutorial).
...And 6 more matches
Componentizing our React app - Learn web development
the following commands make a components directory and then, within that, a file
called todo.js.
...open it up and give it its first line: import react from "react"; since we're going to make a component
called todo, you can start adding the code for that to todo.js too, as follows.
...in app.js, add the following line near the top of the file to import todo: import todo from "./components/todo"; with this component imported, you can replace all of the <li> elements in app.js with <todo /> component
calls.
...And 6 more matches
Adding a new event
typi
cally, events in this header file never cross process boundary.
...this method is basi
cally used for duplicating an internal event class instance of a dom event when the dom event is stored by content.
...first, this method should
call its super class's this method.
...And 6 more matches
mach
you can add the command to your .profile so it will run automati
cally when you start the shell: source /path/to/mozilla-central/python/mach/bash-completion.sh this will enable tab completion of mach command names, and in the future it may complete flags and other arguments too.
... for zsh, you can
call the built-in bashcompinit function before sourcing: autoload bashcompinit bashcompinit source /path/to/mozilla-central/python/mach/bash-completion.sh frequently asked questions why should i not use mach?
...those makepkg scripts named pkgbuild are (typi
cally) simple bash scripts that are easy to maintain and modify.
...And 6 more matches
Cross Process Object Wrappers
so chrome code can't directly interact with web content: instead, it must factor out the code that interacts with web content into separate scripts that are
called frame scripts.
...as a migration aid, the messaging framework enables frame scripts to make content objects available to chrome through a wrapper
called a cross process object wrapper, also known as a cpow.
...the chrome script can get and set the wrapped object's properties and
call its functions: // chrome script windowmm.addmessagelistener("my-e10s-extension-message", handlemessage); function handlemessage(message) { let wrapper = message.objects.clicked; console.log(wrapper.innerhtml); wrapper.innerhtml = "<h2>modified by chrome!</h2>" wrapper.setattribute("align", "center"); } auto-generated cpows add-ons that have not declared themselves multiprocess compati...
...And 6 more matches
IPDL Best Practices
this one is easy to miss, as the corresponding recv__delete__ function has a stub implementation automati
cally generated in the base class.
... simply
calling delete on a pointer to an actor is not enough.
...reference counting protocol actors is tricky here is the easiest way to get it right the first time (lessons learned from the http channel and geolocation protocols): allocpprotocol
calls addref deallocpprotocol
calls release this ensures that the actor will not disappear from under ipdl, and that you won't get bizarre crashes at other times if ipdl deletes the protocol tree.
...And 6 more matches
Add-on Repository
these searches are asynchronous; results are passed to the provided search
callback object when the search is completed.
... results passed to the search
callback object only include add-ons that are compatible with the current application and are not already installed or in the process of being installed.
... to import the add-on repository code module, use: components.utils.import("resource://gre/modules/addonrepository.jsm"); method overview string getrecommendedurl() string getsearchurl(in string searchterms) void cancelsearch() void retrieverecommendedaddons(in integer maxresults, in search
callback
callback) void searchaddons(in string searchterms, in integer maxresults, in search
callback
callback) properties property type description homepageurl string the url of the repository site's home page.
...And 6 more matches
Interfacing with the Add-on Repository
when the user clicks a toolbar button to initiate the query, the following code gets run to start the request: addonrepository.retrieverecommendedaddons(10, this); this asks the repository to fetch up to 10 add-ons, using the object this as the target for
callbacks.
... the
callback object needs to implement the search
callback interface, providing the methods that get
called when a search either fails or completes successfully.
... handling failed requests the
callback object must have a searchfailed() method; this gets
called when a repository search fails to execute.
...And 6 more matches
Task.jsm
if you specify a generator function or the iterator returned by a generator function, then task.spawn() is implicitly
called, and the yield operator works on the returned promise.
... this reduces the syntax overhead of
calling task.spawn() explicitly when you want to recurse into other task functions.
... if you specify a function that is not a generator, it is
called with no arguments, and the yield operator returns the return value of the function.
...And 6 more matches
Localizing with Koala
for the purposes of this tutorial, the locale code that we will use will be
called "x-testing".
...translating to x-testing will basi
cally consist of converting any strings to uppercase, for example "file" in original version (en-us) will become "file" in x-testing.
... note that you don't have to edit the location field, it automati
cally fills in when you check the "mercurial" checkbox: "c:\mozilla\l10n\application\firefox\3.6".
...And 6 more matches
Investigating leaks using DMD heap scan mode
however, in that case it may be easier to use refcount logging, or rr with a conditional breakpoint set on
calls to release() for the leaking object, to see what object actually does the release that causes the leaked object to go away.
...first, in toolkit/components/terminator/nsterminator.cpp, delete everything in runwatchdog but the
call to ns_setcurrentthreadname.
...secondly, you may need to comment out the
call to moz_crash("nss_shutdown failed"); in xpcom/build/xpcominit.cpp, as this also seems to trigger when shutdown is extremely slow.
...And 6 more matches
Memory reporting
each reporter implements a collectreports function which takes a nsimemoryreporter
callback argument; for each measurement the reporter must pass in several values, including: a path (which identifies the report); an amount (the most important thing); a unit (most commonly bytes, but sometimes a unitless count or percentage); a description of what is measured.
... the size is not computed analyti
cally.
...this is a good thing, because computing sizes analyti
cally doesn't count slop, and it is much more error-prone than using moz_malloc_usable_size.
...And 6 more matches
Rhino overview
the deprecated features are the __proto__ and __parent__ properties, and the constructors with, closure, and
call.
...the value of this property can be determined at runtime by
calling the issecuritydomainrequired method of context.
... setting this property to true requires that any
calls that compile or evaluate javascript must supply a security domain object of any object type that will be used to identify javascript code.
...And 6 more matches
Functions
(but note that objects of other classes can be
callable and can even have typeof obj == "function".) script functions functions written in javascript and compiled to bytecode.
...a nested function is algol-like if it is only ever defined and
called, and it isn't accessed in any other way (and it is not a generator-function).
... such a function is guaranteed never to be
called again after the enclosing function exits.
...And 6 more matches
JS::CompileOptions
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...
callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports.
... noscriptrval bool false means that the
caller needs the return value of the script.
...And 6 more matches
JSDeletePropertyOp
in js_threadsafe builds, the javascript engine
calls this
callback only from within an active request on cx.
... the
callback does not need to
call js_beginrequest()).
... description jsdeletepropertyop
callback is a hook that applications may install to be
called at some point during property access.
...And 6 more matches
JS_BeginRequest
indicates to the js engine that the
calling thread is entering a region of code that may
call into the jsapi but does not block.
... syntax void js_beginrequest(jscontext *cx); void js_endrequest(jscontext *cx); name type description cx jscontext * the context in which the
calling thread intends to
call jsapi functions.
... description when your multithreaded application wants to use a jscontext, it must use js_beginrequest and js_endrequest to bracket maximal non-blocking hunks of native code that
call the jsapi.
...And 6 more matches
JS_IterateCompartments
this article covers features introduced in spidermonkey 17 iterate over compartments and
call the specified
callback function on every compartment.
... syntax void js_iteratecompartments(jsruntime *rt, void *data, jsiteratecompartment
callback compartment
callback); name type description cx jsruntime * the runtime of the compartments to iterate over.
... data void * this will be passed as the data parameter of the jsiteratecompartment
callback.
...And 6 more matches
SpiderMonkey 31
after this method is
called, normal jsapi operations are permitted.
...many jsapi types, functions, and
callback signatures have changed, though most functions that have changed still have the same names and implement essentially unchanged functionality.
...here is a list of the most significant changes: many of the garbage collector changes require type signature changes to jsapi methods: specifi
cally introducing js::rooted, js::handle, and js::mutablehandle types.
...And 6 more matches
Split object
the script in a might have opened tb by
calling window.open, which returns a direct reference to tb's window.
...if page a gets a reference to that function, then by
calling it, it is indirectly accessing tab tb's window.
...to further complicate matters, a and b are in the same security domain, so security checks between them automati
cally succeed.
...And 6 more matches
Places utilities for JavaScript
there are several predefined versions of this for common
calls.
... load_in_sidebar_anno - this annotation is associated with bookmarks or items that should load in the sidebar automati
cally.
...they can save you time
calling the service and searching for a particular folder on your own.
...And 6 more matches
nsIAuthPrompt2
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is usually acquired using getinterface on notification
callbacks or similar.
...to create an instance, use: var authprompt2 = components.classes["@mozilla.org/login-manager/prompter;1"] .createinstance(components.interfaces.nsiauthprompt2); method overview nsicancelable asyncpromptauth(in nsichannel achannel, in nsiauthprompt
callback a
callback, in nsisupports acontext, in pruint32 level, in nsiauthinformation authinfo); boolean promptauth(in nsichannel achannel, in pruint32 level, in nsiauthinformation authinfo); constants constant value description level_none 0 the password will be sent unencrypted.
...this has largely the same semantics as nsiauthprompt.promptusernameandpassword(), but must return immediately after
calling and return the entered data in a
callback.
...And 6 more matches
nsIBrowserSearchService
if you need to write code that is executed during startup and makes use of nsibrowsersearchservice, you should make sure that this code is executed from the
callback to init().
... method overview void addengine(in astring engineurl, in long datatype, in astring iconurl, in boolean confirm, [optional] in nsisearchinstall
callback
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 astring aenginename); void getengines([optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines); void getvisibleengine...
...if a confirmation dialog is shown, it will offer the option to begin using the newly added engine right away; if no confirmation dialog is shown, the new engine will be used right away automati
cally.
...And 6 more matches
nsIDOMGeoGeolocation
service(components.interfaces.nsidomgeogeolocation); note: if nsidgeogeolocation throws an exception when importing, try using this: var geolocation = components.classes["@mozilla.org/geolocation;1"] .getservice(components.interfaces.nsisupports); method overview void clearwatch(in unsigned short watchid); void getcurrentposition(in nsidomgeoposition
callback success
callback, [optional] in nsidomgeopositionerror
callback error
callback, [optional] in nsidomgeopositionoptions options); unsigned short watchposition(in nsidomgeoposition
callback success
callback, [optional] in nsidomgeopositionerror
callback error
callback, [opti...
... methods clearwatch() when the clearwatch() method is
called, the watch() process stops
calling for new position identifiers and cease invoking
callbacks.
...if this fails, error
callback is invoked with an nsidomgeopositionerror argument.
...And 6 more matches
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().
... lists are built in real-time during the sequence of build
calls, make sure to check for errors on each individual step.
...a list of these items is returned by a
call to initlistbuild().
...And 6 more matches
nsISHEntry
boolean hasdetachededitor(); violates the xpcom interface guidelines boolean hasdynami
callyaddedchild(); boolean isdynami
callyadded(); void seteditordata(in nsdocshelleditordataptr adata); violates the xpcom interface guidelines void setissubframe(in boolean aflag); void setscrollposition(in long x, in long y); void settitle(in astring atitle); void setuniquedocidentifier(); void seturi(in nsiuri auri); void setviewerbounds(in nsintrect bounds); native code only!
...in practice, two entries a and b will have the same docidentifier if we arrived at b by clicking an anchor link in a or if b was created by a's
calling history.pushstate().
...this is typi
cally loadhistory except when reload is pressed, it has the appropriate reload flag.
...And 6 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.
...onhistorygoforward()
called when navigating to a next session history entry, for example due to an nsiwebnavigation.goforward()
call.
...And 6 more matches
nsIScriptableInputStream
exceptions thrown ns_base_stream_closed if
called after the stream has been closed.
...note: the close method may be
called more than once, but subsequent
calls are ignored.
...note: the init method may be
called more than once, allowing a nsiscriptableinputstream instance to be reused.
...And 6 more matches
nsIWindowWatcher
this component must be initialized at application startup by
calling setwindowcreator().
... nsiwebbrowserchrome getchromeforwindow( in nsidomwindow awindow ); parameters awindow the nsidomwindow whose chrome window the
caller needs.
...it will automati
cally be added to our list.
...And 6 more matches
nsIXmlRpcClient
8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports method overview void init(in string serverurl); void setauthentication(in string username, in string password); void clearauthentication(in string username, in string password); void setencoding(in string encoding); void setencoding(in unsigned long type, out nsiidref uuid, out nsqiresult result); void async
call (in nsixmlrpcclientlistener listener, in nsisupports ctxt, in string methodname, in nsisupports arguments, in pruint32 count); attributes attribute type description serverurl readonly nsiurl the url of the xml-rpc server inprogress readonly boolean whether or not a
call is in progress fault readonly nsixmlrpcfault the most recent xml-rpc fault from returned from this server.
... null if the last
call didn't return an xml-rpc fault.
... result readonly nsisupports the most recent xml-rpc
call result returned from this server.
...And 6 more matches
js-ctypes reference
the library object is used mostly to declare native functions provided by the library so that js-ctypes knows how to
call them.
... once you have finished working with a library,
call library.close().
...
calling conventions see abi.
...And 6 more matches
DevTools API - Firefox Developer Tools
in terms of user interface, each registered tool lives in its own tab (we
call one tab a panel).
... these tabs are located in a box we
call a toolbox.
...an instance of a tool is
called a toolpanel.
...And 6 more matches
Dominators view - Firefox Developer Tools
starting in firefox 46, the memory tool includes a new view
called the dominators view.
...the first two are
call and window objects, and retain about 21% and 8% of the total size of the memory snapshot, respectively.
...
call stack in the toolbar at the top of the tool is a dropdown
called "label by": by default, this is set to "type".
...And 6 more matches
Intensive JavaScript - Firefox Developer Tools
leaving the radio button set to "use blocking
call in main thread", make a recording: press the "start animations" button start recording a performance profile press "do pointless computations!" two or three times stop recording the profile exactly what you see will vary from one machine to another, but it will be something like this: the top half of this is the waterfall overview.
...by switching to the flame chart view we can find out: this shows us the js
call stack at this point in the execution.
... at the top of the stack is a function
called calculateprimes(), and we can see its filename and line number.
...And 6 more matches
BaseAudioContext.decodeAudioData() - Web APIs
the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a
callback or promise.
... syntax older
callback syntax: baseaudiocontext.decodeaudiodata(arraybuffer, success
callback, error
callback); 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.
... success
callback a
callback function to be invoked when the decoding successfully finishes.
...And 6 more matches
FileSystemDirectoryEntry.removeRecursively() - Web APIs
the filesystemdirectoryentry interface's method removerecursively() removes the directory as well as all of its content, hierarchi
cally iterating over its entire subtree of descendant files and directories.
... syntax filesystemdirectoryentry.removerecursively(success
callback[, error
callback]); parameters success
callback a function to
call once the directory removal process has completed.
... the
callback has no parameters.
...And 6 more matches
FileSystemDirectoryEntry - Web APIs
basic concepts you can create a new directory by
calling getdirectory().
... example in the following code snippet, we create a directory
called "documents." // taking care of the browser-specific prefixes.
... getdirectory() returns a filesystemdirectoryentry object representing a directory located at a given path, relative to the directory on which the method is
called.
...And 6 more matches
FileSystemFlags - Web APIs
the filesystemflags dictionary defines a set of values which are used when specifying option flags when
calling certain methods in the file and directory entries api.
... exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the
call.
... instead, it must be possible for it to be created newly at
call time.
...And 6 more matches
File and Directory Entries API - Web APIs
the asynchronous api will not block and functions and the api will not return values; instead, you will need to supply a
callback function to handle the response whenever it arrives.
... getting access to a file system there are two ways to get access to file systems defined in the current specification draft: when handling a drop event for drag and drop, you can
call datatransferitem.webkitgetasentry() to get the filesystementry for a dropped item.
... if the result isn't null, then it's a dropped file or directory, and you can use file system
calls to work with it.
...And 6 more matches
MediaRecorder - Web APIs
mediarecorder.requestdata() requests a blob containing the saved data received thus far (or since the last time requestdata() was
called.
... after
calling this method, recording continues, but in a new blob.
... event handlers mediarecorder.ondataavailable
called to handle the dataavailable event, which is periodi
cally triggered each time timeslice milliseconds of media have been recorded (or when the entire media has been recorded, if timeslice wasn't specified).
...And 6 more matches
Navigator.getUserMedia() - Web APIs
if permission is granted, a mediastream whose video and/or audio tracks come from those devices is delivered to the specified success
callback.
... if permission is denied, no compatible input devices exist, or any other error condition occurs, the error
callback is executed with a mediastreamerror object describing what went wrong.
... if the user instead doesn't make a choice at all, neither
callback is executed.
...And 6 more matches
Using Pointer Events - Web APIs
this may be a finger (or elbow, ear, nose, whatever, but typi
cally a finger), stylus, mouse, or any other method for specifying a single point on the surface.
...</canvas> <br> <button onclick="startup()">initialize</button> <br> log: <pre id="log" style="border: 1px solid #ccc;"></pre> setting up the event handlers when the page loads, the startup() function shown below should be
called by our <body> element's onload attribute (but in the example we use a button to trigger it, due to limitations of the mdn live example system).
... 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.
...And 6 more matches
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
you can disable the attribute array by
calling disablevertexattribarray().
... either way, since attributes cannot be used unless enabled, and are disabled by default, you need to
call enablevertexattribarray() to enable individual attributes so that they can be used.
...if you know the name of the attribute but not its index, you can get the index by
calling getattriblocation().
...And 6 more matches
WebGLRenderingContext.vertexAttribPointer() - Web APIs
also, we have to
call gl.enablevertexattribarray() to tell webgl that this attribute should be filled with data from our array buffer.
... the maximum number of vertex attributes depends on the graphics card, and you can
call gl.getparameter(gl.max_vertex_attribs) to get this value.
...in this case, you
call gl.bindattriblocation() to connect a named attribute from the vertex shader to the index you want to use.
...And 6 more matches
Using bounded reference spaces - Web APIs
introduction a bounded reference space is one which represents an xr environment in which the user is able to move around physi
cally in the real world while being tracked by the xr hardware, with their movements being then transposed into the simulation.
...by their very nature, bounded reference spaces have special hardware requirements, since they need to allow for the user to physi
cally move around in space while their movements are tracked.
...orts a bounded-floor reference space if available by using code such as the following: async function onactivatexrbutton(event) { if (!xrsession) { 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.
...And 6 more matches
Using the Web Animations API - Web APIs
and unlike pure, declarative css, javascript also lets us dynami
cally set values from properties to durations.
...it will automati
cally divide the animation into equal parts based on the number of keys you give it.
... the animate() method can be
called on any dom element that could be animated with css.
...And 6 more matches
Using XMLHttpRequest - Web APIs
note: you need to add the event listeners before
calling open() on the request.
...in this case, the progress event is automati
cally fired when the load event occurs for that packet.
... note: as of gecko 12.0, if your progress event is
called with a responsetype of "moz-blob", the value of response is a blob containing the data received so far.
...And 6 more matches
Web Accessibility: Understanding Colors and Luminance - Accessibility
because of the current domination of the rgb color space in measuring color output, most calculations in this document are presumed to be in the rgb color space, and very specifi
cally, in the srgb color space.
... for digital concerns, much of the technology has histori
cally resided in the rgb color space.
... in speaking specifi
cally to relative luminance, wcag's definition of relative luminance notes: "note 2: almost all systems used today to view web content assume srgb encoding.
...And 6 more matches
writing-mode - CSS: Cascading Style Sheets
the writing-mode css property sets whether lines of text are laid out horizontally or verti
cally, as well as the direction in which blocks progress.
... vertical-rl for ltr scripts, content flows verti
cally from top to bottom, and the next vertical line is positioned to the left of the previous line.
... for rtl scripts, content flows verti
cally from bottom to top, and the next vertical line is positioned to the right of the previous line.
...And 6 more matches
<input type="url"> - HTML: Hypertext Markup Language
the input value is automati
cally validated to ensure that it's either empty or a properly-formatted url before the form can be submitted.
... the :valid and :invalid css pseudo-classes are automati
cally applied as appropriate to visually denote whether the current value of the field is a valid url or not.
... value the <input> element's value attribute contains a domstring which is automati
cally validated as conforming to url syntax.
...And 6 more matches
HTML elements reference - HTML: Hypertext Markup Language
a footer typi
cally contains information about the author of the section, copyright data or links to related documents.
... <header> the html <header> element represents introductory content, typi
cally a group of introductory or navigational aids.
... <ol> the html <ol> element represents an ordered list of items — typi
cally rendered as a numbered list.
...And 6 more matches
HTTP Index - HTTP
8 identifying resources on the web domain, http, path, scheme, syntax, uri, url, url syntax, web, fragment, port, query, resources the target of an http request is
called a "resource", whose nature isn't defined further; it can be a document, a photo, or anything else.
...it allows web developers to have more control over the data stored lo
cally by a browser for their origins.
...when this policy is enabled,
calls to getcurrentposition() and watchposition() will cause those functions'
callbacks to be invoked with a positionerror code of permission_denied.
...And 6 more matches
Iterators and generators - JavaScript
specifi
cally, an iterator is any object which implements the iterator protocol by having a next() method that returns an object with two properties: value the next value in the iteration sequence.
... once created, an iterator object can be iterated explicitly by repeatedly
calling next().
...after a terminating value has been yielded additional
calls to next() should simply continue to return {done: true}.
...And 6 more matches
Array.from() - JavaScript
mapfn optional map function to
call on every element of the array.
... polyfill notes: this algorithm is exactly as specified in ecma-262 6th edition (assuming object and typeerror have their original values and that
callback.
call() evaluates to the original value of function.prototype.
call()).
...symbol.iterator : 'symbol(symbol.iterator)'; } catch { symboliterator = 'symbol(symbol.iterator)'; } var tostr = object.prototype.tostring; var is
callable = function (fn) { return ( typeof fn === 'function' || tostr.
call(fn) === '[object function]' ); }; var tointeger = function (value) { var number = number(value); if (isnan(number)) return 0; if (number === 0 || !isfinite(number)) return number; return (number > 0 ?
...And 6 more matches
Set.prototype.forEach() - JavaScript
syntax myset.foreach(
callback[, thisarg]) parameters
callback function to execute for each element, taking three arguments: currentvalue, currentkey the current element being processed in the set.
... set the set object which foreach() was
called upon.
... thisarg value to use as this when executing
callback.
...And 6 more matches
TypedArray.prototype.some() - JavaScript
syntax typedarray.some(
callback[, thisarg]) parameters
callback function to test for each element, taking three arguments: currentvalue the current element being processed in the typed array.
... array the typed array some was
called upon.
...value to use as this when executing
callback.
...And 6 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.
... 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
import - JavaScript
bindings imported are
called live bindings because they are updated by the module that exported the binding.
...for example, if the module imported above includes an export doalltheamazingthings(), you would
call it like this: mymodule.doalltheamazingthings(); import a single export from a module given an object or value named myexport which has been exported from the module my-module either implicitly (because the entire module is exported) or explicitly (using the export statement), this inserts myexport into the current scope.
...the following are some reasons why you might need to use dynamic import: when importing stati
cally significantly slows the loading of your code and there is a low likelihood that you will need the code you are importing, or you will not need it until a later time.
...And 6 more matches
Image file type and format guide - Web media technologies
note: you should typi
cally avoid using bmp for web site content, as it's not a generally-accepted use of the format.
... bmp theoreti
cally supports a variety of internal data representations.
... theoreti
cally, several compression algorithms are supported, and the image data can also be stored in jpeg or png format within the bmp file.
...And 6 more matches
Performance fundamentals - Web Performance
text and images reflow automati
cally, ui elements automati
cally receive the system theme, and the system provides "built-in" support for some use cases developers may not think of initially, like different-resolution displays or right-to-left languages.
...pixel buffers painted by both gecko "automati
cally" and applications to canvas "manually" minimize copies when being drawn to the display framebuffer.
...javascript is a dynami
cally-typed language, and the web platform allows loading code, html, css, images, and other resources dynami
cally.
...And 6 more matches
console - Archive of obsolete content
console.trace() logs a stack trace at the point the function is
called.
... at a given logging level, only
calls to the corresponding functions and functions with a higher severity will have any effect.
... for example, if the logging level is set to "info", then
calls to info(), log(), warn(), and error() will all result in output being written.
...And 5 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
hat you know are the result of the doawesomedomstuff() function, you can wrap it as follows: { let originaldoawesomedomstuff = doawesomedomstuff; doawesomedomstuff = function _doawesomedomstuff() { let res = originaldoawesomedomstuff.apply(this, arguments); doawesomerdomstuff(res, arguments); return res; }; } now, whenever doawesomedomstuff() is
called, the original function will be
called, followed by your own doawesomerdomstuff() function, which can then further modify the dom as needed.
... variations on this method include modifying the arguments passed to the wrapped function, modifying its return value, and making changes both before and after the original method is
called.
... * @param {function(event)}
callback the function which is to be
called * when matching nodes become available.
...And 5 more matches
Connecting to Remote Content - Archive of obsolete content
prequest;1"] .createinstance(components.interfaces.nsixmlhttprequest); request.onload = function(aevent) { window.alert("response text: " + aevent.target.responsetext); }; request.onerror = function(aevent) { window.alert("error status: " + aevent.target.status); }; request.open("get", url, true); request.send(null); in this example we demonstrate how to make a xmlhttprequest
call in asynchronous mode.
... following initialization, onload and onerror handlers are registered to a
callback function to handle the response returned from the remote server.
...in the onload
callback function, the responsetext parameter contains the server response as text.
...And 5 more matches
Java in Firefox Extensions - Archive of obsolete content
if you are in need of
calling java code from within a firefox extension, you can make use of liveconnect.
...if you wish to
call java code from within javascript code that implements some xpcom components, at this time, you need a different technique (refer to the complete java firefox extension).
... a good reason for
calling java from within an xpcom component rather than from xul is to maintain a singleton (some singular java object) across all firefox windows.
...And 5 more matches
New Skin Notes - Archive of obsolete content
--
callek i tried this, but it gets totally screwed up in ie for some reason.
...devmo skin vs cavendish skin --
callek i can probably pull-off this patch if needed (quickly), so dria or others do not have to hunt up "how".
... --
callek add "what not to do" css class to stylesheet, as discussed on talk:core javascript 1.5 reference.
...And 5 more matches
Writing to Files - Archive of obsolete content
try { var file = io.getfile("desktop", "myinfo.txt"); var stream = io.newoutputstream(file, "text"); } catch (ex) { alert(ex); } this example retrieves a file object on the desktop
called 'myinfo.txt' using nsiscriptableio.getfile().
...nsiscriptableio.newoutputstream() is
called to create a new output stream, which will be used to write to the file.
...when writing text files, characters are writing using a chosen character set, encoded automati
cally.
...And 5 more matches
appendNotification - Archive of obsolete content
« xul reference home appendnotification( label , value , image , priority , buttons, event
callback ) return type: element create a new notification and display it.
... event
callback optional - a javascript function to
call to notify you of interesting things that happen with the notification box.
...each description is an object with the following properties: accesskey - the accesskey to appear on the button
callback - function to be
called when the button is activated.
...And 5 more matches
MenuItems - Archive of obsolete content
the "accel" modifier key varies on each platform, but is the key typi
cally used for shortcut keys.
...you do not need to update the checked attribute as the menuitem will update this automati
cally before the command event is fired.
... there may be times when you do not want the checkbox state to be updated automati
cally when the menuitem is activated.
...And 5 more matches
Sorting Results - Archive of obsolete content
for ascending or descending sorts, this doesn't matter, since it will ignore whether results are containers and just sort by a value, alphabeti
cally or numeri
cally depending on the type of data.
...the user can change the sort column and direction by clicking the column headers, however, you can programmati
cally change the sort as well.
...the tree will change both attributes as necessary automati
cally when the column headers are clicked or the tree is sorted by other means.
...And 5 more matches
Template and Tree Listeners - Archive of obsolete content
you would implement this object with these two methods if you wish to be notified when the template is rebuilt using the builder's rebuild
call.
...re
call that when a template is rebuilt, all of the existing content will be removed and generated fresh.
... the willrebuild method of any listeners will be
called before the content is removed, and didrebuild method will be
called when the content has been regenerated.
...And 5 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
the sessions can be set using the searchsessions attribute or by
calling the addsession method.
...nt="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> onerrorcommand type: script code this event handler is
called when an error occurs when selecting a result from the popup.
...this event is only
called when the text displayed would change, thus it is not
called when the user presses non-displayable keys.
...And 5 more matches
Broadcasters and Observers - Archive of obsolete content
in addition, if you place the disabled attribute on the command element, any elements hooked up to it will also become disabled automati
cally.
... broadcasters there is a similar element
called a broadcaster.
... <broadcasterset> <broadcaster id="isoffline" label="offline"/> </broadcasterset> any elements that are watching the broadcaster will be modified automati
cally whenever the broadcaster has its label attribute changed.
...And 5 more matches
Creating an Installer - Archive of obsolete content
this mechanism is
called xpinstall (cross platform install).
... the jar file installers typi
cally have the extension .xpi (pronounced zippy) to distinguish them from other archives.
...this script will
call install functions which will indicate which files from the archive should be installed.
...And 5 more matches
Focus and Selection - Archive of obsolete content
example 2 : source view <script> function displayfocus(){ var elem=document.getelementbyid('sbar'); elem.setattribute('value','enter your phone number.'); } </script> <textbox id="tbox1"/> <textbox id="tbox2" onfocus="displayfocus();"/> <description id="sbar" value=""/> the focus event, when it occurs, will
call the displayfocus function.
...typi
cally, you will use focus and blur events to update parts of the interface as the user selects elements.
...you can also add event handlers dynami
cally using the dom function addeventlistener.
...And 5 more matches
Keyboard Shortcuts - Archive of obsolete content
we've already seen in the section on menus that we can define an attribute
called accesskey which specifies the key which a user can press to activate the menu or menu item.
...if this value is used, typi
cally the key combination conflicts with system wide shortcut keys.
...an example is shown below: <keyset> <key id="copy-key" modifiers="accel" key="c" oncommand="docopy();"/> </keyset> the function docopy will be
called when the user presses the keys specified by the key element, which in this example, are the keys for copying to the clipboard (such as control + c).
...And 5 more matches
Manifest Files - Archive of obsolete content
note: starting in gecko 2.0, only the file named chrome.manifest is read automati
cally; if you need to read multiple manifest files, use the manifest command in that file to import additional manifests.
...for example, on a windows machine, you might use c:\testfiles create a new ascii1 file
called test.manifest in the chrome directory.
... it doesn't actually matter what the file is
called as long as it has the .manifest extension.
...And 5 more matches
Updating Commands - Archive of obsolete content
all we need to do is get the needed controller and
call the command.
...also, we could just
call docommand without checking if the command was enabled or not, although we probably shouldn't do that.
...if you include the script 'chrome://global/content/globaloverlay.js' in a xul file, you can
call the godocommand method which executes the command passed as the argument.
...And 5 more matches
Writing Skinnable XUL and CSS - Archive of obsolete content
in our particular mozilla skin, there is a special package
calledglobal.
... this package contains a special skin
called theglobal skin.
...this may seem obvious, but many of the nastiest problems we're seeing are being caused by people writing buggy or syntacti
cally incorrect css.
...And 5 more matches
XUL element attributes - Archive of obsolete content
for boxes that have horizontal orientation, it specifies how its children will be aligned verti
cally.
...for a verti
cally oriented element, this will make its children all have the height of the tallest child.
... orient type: one of the values below used to specify whether the children of the element are oriented horizontally or verti
cally.
...And 5 more matches
XUL accessibility guidelines - Archive of obsolete content
it can also be set programmati
cally with the tabindex attribute if needed, but this should be done sparingly and thoroughly tested whenever it is used.
...do not specifi
cally code them to open on a click of the right mouse button.
...other elements, such as arrowscrollbox and listbox, are made to scroll automati
cally.
...And 5 more matches
NPN_GetURLNotify - Archive of obsolete content
notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify()
call, which passes this value (see description below).
... description npn_geturlnotify() works just like npn_geturl(), with one exception: npn_geturlnotify() notifies the plug-in instance upon successful or unsuccessful completion of the request by
calling the plug-in's npp_urlnotify() function and passing it the notifydata value.
... npn_geturlnotify() typi
cally handles the url request asynchronously.
...And 5 more matches
Using IO Timeout And Interrupt On NT - Archive of obsolete content
due to a limitation of the present implementation of nspr io on nt, programs must follow the following guideline: if a thread
calls an nspr io function on a file descriptor and the io function fails with <tt>pr_io_timeout_error</tt> or <tt>pr_pending_interrupt_error</tt>, the file descriptor must be closed before the thread exits.
...a thread
calling an io function is blocked until the io operation finishes, either due to a successful io completion or an error.
...if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt>
call, the io function returns with <tt>pr_pending_interrupt_error</tt>.
...And 5 more matches
Parsing microformats in JavaScript - Archive of obsolete content
methods datetimegetter() specifi
cally retrieves a date from a microformat node.
...emailgetter() specifi
cally retrieves an email address from a microformat node.
... return value an object containing a function you can
call to get the string and the html.
...And 5 more matches
Building up a basic demo with the PlayCanvas engine - Game development
next, we'll set the canvas to fill the window, and automati
cally change its resolution to be the same as the canvas size.
...for the camera z position) are unitless, and can basi
cally be anything you deem suitable for your scene — milimeters, meters, feet, or miles — it's up to you.
... material the basic playcanvas material is
called phongmaterial — add the following lines below the previous code.
...And 5 more matches
Fundamental text and font styling - Learn web development
these are the so-
called web safe fonts.
... courier new monospace some oses have an alternative (possibly older) version of the courier new font
called courier.
... georgia serif times new roman serif some oses have an alternative (possibly older) version of the times new roman font
called times.
...And 5 more matches
Client-side form validation - Learn web development
this is
called client-side form validation, and helps ensure data submitted matches the requirements set forth in the various form controls.
... this is
called form validation.
...validation done in the browser is
called client-side validation, while validation done on the server is
called server-side validation.
...And 5 more matches
Video and audio content - Learn web development
the paragraph inside the <video> tags this is
called fallback content — this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers.
...formats like mp3, mp4 and webm are
called container formats.
... for example: a webm container typi
cally packages vorbis or opus audio with vp8/vp9 video.
...And 5 more matches
Arrays - Learn web development
arrays are generally described as "list-like objects"; they are basi
cally single objects that contain multiple values stored in a list.
... if we didn't have arrays, we'd have to store every item in a separate variable, then
call the code that does the printing and adding separately for each item.
... note that an array inside an array is
called a multidimensional array.
...And 5 more matches
Adding features to our bouncing balls demo - Learn web development
it should also define a new property
called exists, which is used to track whether the balls exist in the program (have not been eaten by the evil circle).
...) constructor
call — the exists parameter should be the 5th parameter, and should be given a value of true.
... you should do this something like shape.
call(this, x, y, 20, 20, exists); it should also define its own properties, as follows: color — 'white' size — 10 again, remember to define your inherited properties as parameters in the constructor, and set the prototype and constructor properties correctly.
...And 5 more matches
Working with JSON - Learn web development
note: converting a string to a native object is
called deserialization, while converting a native object to a string so it can be transmitted across the network is
called serialization.
... a json object can be stored in its own file, which is basi
cally just a text file with an extension of .json, and a mime type of application/json.
... "damage resistance", "superhuman reflexes" ] }, { "name": "eternal flame", "age": 1000000, "secretidentity": "unknown", "powers": [ "immortality", "heat immunity", "inferno", "teleportation", "interdimensional travel" ] } ] } if we loaded this object into a javascript program, parsed in a variable
called superheroes for example, we could then access the data inside it using the same dot/bracket notation we looked at in the javascript object basics article.
...And 5 more matches
Website security - Learn web development
finally, there are publi
cally available vulnerability scanner tools that can help you find out if you've made any obvious mistakes.
... note: xss vulnerabilities have been histori
cally more common than any other type of security threat.
...many web frameworks automati
cally sanitize user input from html forms by default.
...And 5 more matches
Framework main features - Learn web development
javascript lets us use the + operator to concatenate strings together, so this function would techni
cally still work if a and b were strings — it just might not give you the result you'd expect.
...l probably be inside another component): <authorcredit src="./assets/zelda.png" alt="portrait of zelda schiff" byline="zelda schiff is editor-in-chief of the library times." /> this will ultimately render the following <figure> element in the browser, with its structure as defined in the authorcredit component, and its content as defined in the props included on the authorcredit component
call: <figure> <img src="assets/zelda.png" alt="portrait of zelda schiff" > <figcaption> zelda schiff is editor-in-chief of the library times.
...the code will be initially rendered like so in the browser: <button>clicked 0 times</button> the usestate()
call keeps track of the count value in a robust way across the app, without you needing to write code to do that yourself.
...And 5 more matches
Getting started with React - Learn web development
react uses an html-in-javascript syntax
called jsx (javascript and xml).
... line 7
calls react’s reactdom.render() function with two arguments: the component we want to render, <app /> in this case.
...props are written inside component
calls, and use the same syntax as html attributes — prop="value".
...And 5 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
to start with, we want to
call setediting() with a value of true when a user presses the "edit" button in our viewtemplate, so that we can switch templates.
... editing from the ui much of what we're about to do will mirror the work we did in form.js: as the user types in our new input field, we need to track the text they enter; once they submit the form, we need to use a
callback prop to update our state with the new name of the task.
...={props.id} classname="todo-text" type="text" value={newname} onchange={handlechange} /> finally, we need to create a function to handle the edit form’s onsubmit event; add the following just below the previous function you added: function handlesubmit(e) { e.preventdefault(); props.edittask(props.id, newname); setnewname(""); setediting(false); } remember that our edittask()
callback prop needs the id of the task we're editing as well as its new name.
...And 5 more matches
Deployment and next steps - Learn web development
in the file package.json you can see that the dev and start scripts are just
calling rollup: "scripts": { "build": "rollup -c", "dev": "rollup -c -w", "start": "sirv public" }, in the dev script we are passing the -w argument, which tells rollup to watch files and rebuild on changes.
...cks when not in production dev: !production, // we'll extract any component css out into // a separate file - better for performance css: css => { css.write('public/build/bundle.css'); } }), later on in the same file you'll also see how rollup minimizes our scripts in production mode and launches a local server in development mode: // in dev mode,
call `npm run start` once // the bundle has been generated !production && serve(), // watch the `public` directory and refresh the // browser on changes when not in production !production && livereload('public'), // if we're building for production (npm run build // instead of npm run dev), minify production && terser() ], there are many plugins for rollup that all...
...vercel is a cloud platform specifi
cally tailored for static sites, which has out-of-the-box support for most common front-end tools, svelte being one of them.
...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 lo
cally, and get it prepared to start building our example.
...editing this file typi
cally only occurs in advanced use cases.
...this object is where you lo
cally register components, define component inputs (props), handle local state, define methods, and more.
...And 5 more matches
Strategies for carrying out testing - Learn web development
educated guesses you could
call these "assumptions", or "gut feelings".
... browser support stats one helpful measure you can
call on to inform your browser testing choices is browser support stats.
... note: some efforts have been made to create publi
cally accessible device labs — see open device labs.
...And 5 more matches
Client-side tooling overview - Learn web development
safety net tooling should also help you either prevent mistakes or correct mistakes automati
cally without having to build your code from scratch each time.
... code formatters code formatters are somewhat related to linters, except that rather than point out errors in your code, they usually tend to make sure your code is formatted correctly, according to your style rules, ideally automati
cally fixing errors that they find.
... parcel is a particularly clever tool that fits into this category — it can do the above tasks, but also helps to package assets like html, css, and image files into convenient bundles that you can then go on to deploy, and also adds dependencies for you automati
cally whenever you try to use them.
...And 5 more matches
Accessible Toolkit Checklist
often these kinds of toolkits don't use a separate window for each control; in that case remember to generate a unique 32 bit child id for each control so that the msaa event system can
call back for the right iaccessible for each event.
... tab order must wrap, not have invisible items in tab order dynami
cally added items must not corrupt the tab cycle or make it disorderly tab cycle must be identical backwards and forwards the f6 and shift+f6 key combinations should cycle through panes in a window making focus visible on any widget, and focus must always be visible shift+f10 or context menu key should work like right click on focused item, and context menu should show just und...
...if you don't, some screen readers won't automati
cally read the dialog when it receives focus.
...And 5 more matches
Browser chrome tests
you can collect common utils and helpers in a file
called head.js, that must live in the same folder as the browser-chrome tests.
...notice that any function
call in head.js main scope will run before the main test() method.
...
call waitforexplicitfinish() from test() if you want to delay reporting a result until after test() has returned.
...And 5 more matches
Downloads.jsm
this download method does not provide user interface or the ability to cancel or restart the download programmati
cally.
...there is one download list for each type, and this method always retrieves a reference to the same download list when
called with the same argument.
...
calling this function may cause the download list to be reloaded from the previous session, if it wasn't loaded already.
...And 5 more matches
Examples
let lastpromise = newpromise.then(null, components.utils.reporterror); in this case, if the file existence check succeeds, the onfulfill
callback is invoked.
... when the
callback finishes execution, newpromise will be fulfilled with an undefined fulfillment value, because the
callback does not return any value.
... when newpromise is fulfilled, nothing happens, because no fulfillment
callback is specified and the return value of the last then method is ignored.
...And 5 more matches
Application Translation with Mercurial
by pressing the windows key and r on the keyboard or by
calling the "run..." command from the windows "start" button, and then typing cmd and pressing the enter key.
... on windows, you can paste the url by
calling the paste command from the window menu in the upper left corner of the window.
...for a windows user, it looks like c:\users\myname , depending on your windows version: cd /c/users/myname now list all the files here: ls -a if there is no file
called .hgrc , create it with > .hgrc this file stores your general mercurial settings (mercurial is the tool which manages the source code and its history of changes).
...And 5 more matches
gettext
first in the ngettext()
call, where it will be used to determine which form of the string will be returned.
...the second time the $num variable is passed in the printf()
call, which at this point of interpretation looks something like printf("%d user likes this.", $num);.
...in the po file, msgctxt looks like this: msgctxt "button label" msgid "log in" msgstr "" msgctxt "dialog title" msgid "log in" msgstr "" you can add context to your strings by passing an additional argument to the gettext function
call and then having xgettext extract it as the context.
...And 5 more matches
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).
...the output is a large html file that hyperlinks ancestor and descendent libraries, classes, and functions that
call into one another, attributing malloc blame up and down each graph.
... bloatblame accumulates allocation counts and ignores free
calls.
...And 5 more matches
Midas
it also has a property
called contentwindow that refers to the window object inside the inline frame.
...see: more about security preferences note: the shortcut key will automati
cally trigger this command (typi
cally accel-c) with or without the signed js or any code on the page to handle it.
...see: more about security preferences note: the shortcut key will automati
cally trigger this command (typi
cally accel-x) with or without the signed js or any code on the page to handle it.
...And 5 more matches
How to embed the JavaScript engine
run the helloworld executable at the command line: ./helloworld how to
call c functions from javascript say the c function is named doit and it would like at least two actual parameters when
called (if the
caller supplies fewer, the js engine should ensure that undefined is passed for the missing ones): #define doit_minargs 2 // [spidermonkey 24] use jsbool instead of bool.
... static bool doit(jscontext *cx, unsigned argc, jsval *vp) { js::
callargs args =
callargsfromvp(argc, vp); /* * look in argv for argc actual parameters, set *rval to return a * value to the
caller.
...and say: ok = js_definefunctions(cx, global, my_functions); how to
call javascript functions from c first, create arguments for the
call, here i create arguments with 2 items: // [spidermonkey 24] js::autovaluearray is not defined.
...And 5 more matches
JSObjectOps.defaultValue
the javascript engine
calls the jsobjectops.defaultvalue and jsclass.convert
callbacks to convert objects to primitive values.
...on success, the
callback must store the converted value here.
... description the jsobjectops.defaultvalue
callback corresponds to the [[defaultvalue]] method defined in ecma 262-3 §8.6.2.6.
...And 5 more matches
JS_DefineFunction
syntax jsfunction * js_definefunction(jscontext *cx, js::handle<jsobject*> obj, const char *name, jsnative
call, unsigned nargs, unsigned attrs); jsfunction * js_defineucfunction(jscontext *cx, js::handle<jsobject*> obj, const char16_t *name, size_t namelen, jsnative
call, unsigned nargs, unsigned attrs); jsfunction * js_definefunctionbyid(jscontext *cx, js::handle<jsobject*> obj, js::handle<jsid> id, jsnative
call, unsigned nargs, unsigned attrs); // added in spidermonkey 17 name type description cx jscontext * the context in which to define the funct...
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...added in spidermonkey 17
call jsnative the native c/c++ function to be wrapped by the new function.
...And 5 more matches
SavedFrame
it represents a javascript
call stack at a past moment of execution.
... asynccause if this stack frame is the asyncparent of other stack frames, then this is a string representing the type of asynchronous
call by which this frame invoked its children.
... for example, if this frame’s children are
calls to handlers for a promise this frame created, this frame’s asynccause would be "promise".
...And 5 more matches
Redis Tips
techni
cally, this is true: it's a database that doesn't use sql.
... but obviously,
calling ice cream a nowhale food doesn't give you any sense of how good the ice cream is, or what sets it apart from other kinds of food that aren't made from whale meat but that are also very unlike ice cream -- it just gives the whaling industry a way to lump together people who don't use their products.
... redis data types include: strings hashes lists sets ordered sets (
called zsets in redis) transactions publishers and subscribers this table lists some common programming tasks and data structures, and suggests some redis functions or data structures for them: dictionary lookup set, get, setnx, etc.
...And 5 more matches
Gecko Roles
used by msaa only, this is supported automati
cally by microsoft windows.
...assistive technologies typi
cally respond to the role by reading the entire onscreen contents of containers advertising this role.
...the role is supported automati
cally by microsoft windows.
...And 5 more matches
XPCOM changes in Gecko 2.0
prior to gecko 2, during component registration, all binary and javascript component files were loaded and
called, asking them to register themselves.
...const nsgetfactory = xpcomutils.generatensgetfactory([mycomponent]); a component may implement backwards compatibility with gecko 1.9.2 by dynami
cally detecting which symbols are exported by xpcomutils.jsm and exporting the correct function: /** * xpcomutils.generatensgetfactory was introduced in mozilla 2 (firefox 4, seamonkey 2.1).
...typi
cally, extensions observed app-startup because in the past, you needed to load for app-startup in order to be able to register to observe profile-after-change in the first place.
...And 5 more matches
Interfacing with the XPCOM cycle collector
periodi
cally the collector wakes up and examines any suspicious pointers that have been sitting in its buffer for a while.
... it does not suspect any pointers by default; objects must suspect themselves, typi
cally by using an nscyclecollectingautorefcnt rather than a nsautorefcnt.
... (we
call nsibar the canonical isupports type for nsfoo.) add a line ns_interface_map_entries_cycle_collection(nsfoo) to the interface map of nsfoo in nsfoo.cpp.
...And 5 more matches
imgIRequest
status_size_available 0x1 we received enough image data from the network or filesystem that we know the width and height of the image, and have thus
called setsize() on the container.
...note that cancel() is asynchronous, which means that some time after you
call it, the listener/observer will get an onstoprequest().
... this means that, if you're the observer, you can not
call cancel() from your destructor.
...And 5 more matches
nsIAccessibleRole
it is used by msaa only, supported automati
cally by ms windows.
...assistive technologies typi
cally respond to the role by reading the entire on screen contents of containers advertising this role.
...the role is supported automati
cally by ms windows.
...And 5 more matches
nsIBrowserHistory
it is
called by history importing code and is used in the history migration tool.
...it is
called by the url bar when the user types in a url.
... this can be and is
called before the page is actually added to history, since the page isn't added until it actually starts loading.
...And 5 more matches
nsIDOMEvent
defaultprevented boolean used to indicate whether preventdefault() has been
called for this event.
...this method may only be
called before the event has been dispatched via the dispatchevent method, though it may be
called multiple times during that phase if necessary.
... if
called multiple times the final invocation takes precedence.
...And 5 more matches
nsIDocShell
called by the focus manager when the user tabs to the frame rather than an element.
... kcharsetfromautodetection 6 the character set was automati
cally detected.
... top should be true for the toplevel docshell that is being restored; it will be set to false when this method is
called for child docshells.
...And 5 more matches
nsIFocusManager
flag_bymovefocus 0x4000 focus is changing due to a
call to movefocus().
... this flag will be implied when movefocus() is
called except when one of the other mechanisms (mouse or key) is specified, or when the type is movefocus_root or movefocus_caret.
...
called when content has been removed.
...And 5 more matches
nsIGeolocationProvider
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) this must be
called on the main thread interface provides location information to the nsgeolocator via the nsidomgeolocation
callback interface.
... after startup() is
called, any geo location change should
call callback.update().
...after the provider has been initialized, any changes to location should
call callback.onrequest().
...And 5 more matches
nsIMemoryMultiReporter
xpcom/base/nsimemoryreporter.idlscriptable reports multiple memory measurements using a
callback function that gets
called once for each measurement.
...the
callback, which must implement the nsimemorymultireporter
callback interface, receives values that match the fields in the nsimemoryreporter object.
... in order for a multi-reporter to gather and generate reports, you need to
call collectreports().
...And 5 more matches
nsISelectionPrivate
void startbatchchanges(); wstring tostringwithformat(in string formattype, in unsigned long flags, in print32 wrapcolumn); attributes attribute type description cancacheframeoffset boolean frame offset cache can be used just during
calling nseditor::endplaceholdertransaction.
... endplaceholdertransaction will give rise to reflow/refreshing view/scroll, and
call times of nstextframe::getpointfromoffset whose return value is to be cached.
...eselection_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().
...And 5 more matches
nsITextInputProcessorNotification
dom/interfaces/base/nsitextinputprocessor
callback.idlscriptable this interface of a request or notification to ime 1.0 66 introduced gecko 38 inherits from: nsisupports last changed in gecko 38.0 (firefox 38.0 / thunderbird 38.0 / seamonkey 2.35) this interface tells details of a request or notification to ime.
...so, nsitextinputprocessor
callback won't be changed for keeping backward compatibility.
... when this is requested, the
callback should commit composition synchronously, i.e., nsitextinputprocessor.commitcomposition() should be
called.
...And 5 more matches
nsIWindowsRegKey
key hkey this attribute exposes the native hkey and is available to provide c++ consumers with the flexibility of making other windows registry api
calls that are not exposed via this interface.
...this method will always return false if startwatching() was not
called.
...iswatching() this method returns true if the key is being watched for changes (that is, if startwatching() was
called).
...And 5 more matches
Using nsIDirectoryService
second, you must acquire the implementation and
call get() passing the known string key.
...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.
...apart from this interface there is a function, registerprovider which will allow you to register a nsidirectoryserviceprovider, which implements the getfile
callback function: var provider = { getfile : function(prop, persistant) { // return an nsifile }, } components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsidirectoryservice).registerprovider(provider); when the
callback is
called, it will be passed the string key, and should return an nsifile.
...And 5 more matches
Using the clipboard
for reading from the clipboard you can
call the init method of the transferable with null as nsiloadcontext, but you have to
call it.
...we will use the interface nsisupportsstring which can be used to represent strings (specifi
cally, unicode strings).
...then, the function settransferdata is
called which copies the data from the string into the transferable.
...And 5 more matches
Standard OS Libraries
the alternative to standard libraries is creating your own dll (for windows) or so (for linux) file with c functions that can be
called from your add-on with js-ctypes.
...t 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.reporterror(point); lib.close(); resources for winapi githubgists :: noitidart / search · winapi - winapi js-ctypes snippets that can be copied an...
... on linux, libraries will be typi
cally found as .so files.
...And 5 more matches
UI Tour - Firefox Developer Tools
the ui is split verti
cally into three panels source list pane source pane the contents of the third pane depend on the current state of the debugger and may include the following sections: toolbar watch expressions breakpoints
call stack scopes xhr breakpoints event listener breakpoints dom mutation breakpoints source list pane the source list pane lists all the javascript source files loaded into the page, and enables you to select one to debug.
... there are several context menu options available for individual files and folders or groups; typi
cally viewed by right-clicking on the item.
... download file opens a file dialog so you can save the file lo
cally.
...And 5 more matches
Allocations - Firefox Developer Tools
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 periodi
cally samples allocations that are made over the recording.
...click this to see the places this function was
called from: here you can see that signallater() was
called from two places: removeinner() and setselectioninner().
... in this way you can walk back up the
call stack, and understand better the context for these allocations.
...And 5 more matches
Web Console remoting - Firefox Developer Tools
the onattachconsole
callback receives a new instance of the webconsoleclient object.
...you can only get cached messages for page errors and console api
calls.
...], "from": "conn0.console9" } each message in the array is of the same type as when we send typical page errors and console api
calls.
...And 5 more matches
Applying styles and colors - Web APIs
er gridline position—if it hadn't, we would see pixels with half coverage at the endpoints (but note also that this behavior depends on the current linecap style whose default value is butt; you may want to compute consistent strokes with half-pixel coordinates for odd-width lines, by setting the linecap style to square, so that the outer border of the stroke around the endpoint will be automati
cally extended to cover the whole pixel exactly).
... note also that only start and final endpoints of a path are affected: if a path is closed with closepath(), there's no start and final endpoint; instead, all endpoints in the path are connected to their attached previous and next segment using the current setting of the linejoin style, whose default value is miter, with the effect of automati
cally extending the outer borders of the connected segments to their intersection point, so that the rendered stroke will exactly cover full pixels centered at each endpoint if those connected segments are horizontal and/or vertical).
... here's a little demo in which you can set miterlimit dynami
cally and see how this effects the shapes on the canvas.
...And 5 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
you will learn how to create, access and control, and remove html elements dynami
cally.
... example: creating an html table dynami
cally (sample1.html) html <input type="button" value="generate a table." onclick="generate_table()"> javascript function generate_table() { // get the reference for the body var body = document.getelementsbytagname("body")[0]; // creates a <table> element and a <tbody> element var tbl = document.createelement("table"); var tblbody = document.createelement("tbody"); // creating all c...
...when
called, it returns an array with all of the element's descendants matching the tag name.
...And 5 more matches
Guide to the Fullscreen API - Web APIs
activating full-screen mode given an element that you'd like to present in full-screen mode (such as a <video>, for example), you can present it in full-screen mode by simply
calling its requestfullscreen() method.
...et's consider this <video> element: <video controls id="myvideo"> <source src="somevideo.webm"></source> <source src="somevideo.mp4"></source> </video> we can put that video into full-screen mode as follows: var elem = document.getelementbyid("myvideo"); if (elem.requestfullscreen) { elem.requestfullscreen(); } this code checks for the existence of the requestfullscreen() method before
calling it.
... presentation differences it's worth noting a key difference here between the gecko and webkit implementations at this time: gecko automati
cally adds css rules to the element to stretch it to fill the screen: "width: 100%; height: 100%".
...And 5 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
as time passed, of course, we know that computers have evolved into powerful multi-core systems, and javascript has become one of the most prolifi
cally-used languages in the computing world.
... when greetuser()
calls localgreeting(), another context is created to run that function.
... when greetuser()
calls localgreeting(), another context is created to run that function.
...And 5 more matches
IntersectionObserver.IntersectionObserver() - Web APIs
the rootmargin, if specified, is checked to ensure it's syntacti
cally correct, the thresholds are checked to ensure that they're all in the range 0.0 and 1.0 inclusive, and the threshold list is sorted in ascending numeric order.
... 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.
... the
callback receives as input two parameters: entries an array of intersectionobserverentry objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.
...And 5 more matches
MediaDevices.ondevicechange - Web APIs
the mediadevices.ondevicechange property is an eventhandler which specifies a function to be
called when the devicechange event occurs on a mediadevices instance.
... example in this example, we create a function
called updatedevicelist(), which is
called once when mediadevices.getusermedia() successfully obtains a stream, and then is
called any time the device list changes.
...this method is
called any time we want to fetch the current list of media devices and then update the displayed lists of audo and video devices using that information.
...And 5 more matches
Navigator.msLaunchUri() - Web APIs
syntax navigator.mslaunchuri(uri, success
callback, nohandler
callback); parameters uri a domstring specifying the url containing including the protocol of the document or resource to be displayed.
... success
callbackoptional a function matching the signature of mslaunchuri
callback to be executed if the protocol handler is present.
... nohandler
callbackoptional a function matching mslaunchuri
callback to be executed if the protocol handler is not present.
...And 5 more matches
Node - Web APIs
nodelist being live means that if the children of the node change, the nodelist object is automati
cally updated.
... node.contains() returns a boolean value indicating whether or not a node is a descendant of the
calling node.
...*/ removeallchildren(document.body) recurse through child nodes the following function recursively
calls a
callback function for each node contained by a root node (including the root itself): function eachnode(rootnode,
callback) { if (!
callback) { const nodes = [] eachnode(rootnode, function(node) { nodes.push(node) }) return nodes } if (false ===
callback(rootnode)) { return false } if (rootnode.haschildnodes()) { const nodes = rootnode.childnodes for (let i = 0, l = ...
...And 5 more matches
RTCDataChannel - Web APIs
to create a data channel and ask a remote peer to join you,
call the rtcpeerconnection's createdatachannel() method.
...stream read only the deprecated (and never part of the official specification) read-only rtcdatachannel property stream returns an id number (between 0 and 65,535) which uniquely identifies the rtcdatachannel.event handlersalso inherits event handlers from: eventtargetonbufferedamountlow the rtcdatachannel.onbufferedamountlow property is an eventhandler which specifies a function the browser
calls when the bufferedamountlow event is sent to the rtcdatachannel.
... this event, which is represented by a simple event object, is sent when the amount of data buffered to be sent falls to or below the threshold specified by the channel's bufferedamountlowthreshold.onclose the rtcdatachannel.onclose property is an eventhandler which specifies a function to be
called by the browser when the close event is received by the rtcdatachannel.
...And 5 more matches
RTCPeerConnection.createAnswer() - Web APIs
syntax apromise = rtcpeerconnection.createanswer([options]); rtcpeerconnection.createanswer(success
callback, failure
callback[, options]); parameters options optional an object which contains options which customize the answer; this is based on the rtcansweroptions dictionary.
... deprecated parameters in older code and documentation, you may see a
callback-based version of this function.
... success
callback an rtcsessiondescription
callback which will be passed a single rtcsessiondescription object describing the newly-created answer.
...And 5 more matches
RTCPeerConnection.createOffer() - Web APIs
syntax apromise = mypeerconnection.createoffer([options]); mypeerconnection.createoffer(success
callback, failure
callback, [options]) parameters options optional an rtcofferoptions dictionary providing options requested for the offer.
...also, emergency
calls should never cut audio when quiet.
... deprecated parameters in older code and documentation, you may see a
callback-based version of this function.
...And 5 more matches
ReadableStream.ReadableStream() - Web APIs
underlyingsource can contain the following: start(controller) this is a method,
called immediately when the object is constructed.
... pull(controller) optional this method, also defined by the developer, will be
called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark.
... if pull() returns a promise, then it won't be
called again until that promise fulfills; if the promise rejects, the stream will become errored.
...And 5 more matches
SVGSVGElement - Web APIs
svgsvgelement.suspendredraw() takes a time-out value which indicates that redraw shall not occur until: the corresponding unsuspendredraw()
call has been made, an unsuspendredrawall()
call has been made, or its timer has timed out.
...
calls to suspendredraw() and unsuspendredraw() should, but need not be, made in balanced pairs.
... to suspend redraw actions as a collection of svg dom changes occur, precede the changes to the svg dom with a method
call similar to: const suspendhandleid = suspendredraw(maxwaitmilliseconds) and follow the changes with a method
call similar to: unsuspendredraw(suspendhandleid) note that multiple suspendredraw()
calls can be used at once, and that each such method
call is treated independently of the other suspendredraw() method
calls.
...And 5 more matches
User Timing API - Web APIs
starttime - set to the timestamp when mark() was
called.
... removing performance marks to remove a specific mark from the performance timeline,
call performance.clearmarks(name) where name is the name of the mark(s) you want removed.
... if this method is
called with no arguments, all mark type entries will be removed from the performance timeline.
...And 5 more matches
Using textures in WebGL - Web APIs
xture_2d, gl.texture_wrap_s, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_wrap_t, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); } }; image.src = url; return texture; } function ispowerof2(value) { return (value & (value - 1)) == 0; } the loadtexture() routine starts by creating a webgl texture object texture by
calling the webgl createtexture() function.
...the function we assign to image.onload will be
called once the image has finished downloading.
... at that point we again
call teximage2d() this time using the image as the source for the texture.
...And 5 more matches
WebGL model view projection - Web APIs
it explains the three core matrices that are typi
cally used when composing a 3d scene: the model, view and projection matrices.
...these composed matrices ultimately move the original model data around into a special coordinate space
called clip space.
... clip space in a webgl program, data is typi
cally uploaded to the gpu with its own coordinate system and then the vertex shader transforms those points into a special coordinate system known as clip space.
...And 5 more matches
Writing WebSocket servers - Web APIs
depending on your platform, this may be handled for you automati
cally.
...you can use this header for security (checking for same origin, automati
cally allowing or denying, etc.) and send a 403 forbidden if you don't like what you see.
...however, extracting information from these so-
called "frames" of data is a not-so-magical experience.
...And 5 more matches
Window.open() - Web APIs
return value a windowproxy object, which is basi
cally a thin wrapper for the window object representing the newly created window, and has all its features available.
...otherwise the
call to window.open() will just create a new window.
... to open a new window on every
call of window.open(), use the special value _blank for windowname.
...And 5 more matches
XMLHttpRequest - Web APIs
it must be
called before any other method
calls.
... xmlhttprequest.onreadystatechange an eventhandler that is
called whenever the readystate attribute changes.
... xmlhttprequest.timeout is an unsigned long representing the number of milliseconds a request can take before automati
cally being terminated.
...And 5 more matches
XRReferenceSpace - Web APIs
for xr systems that allow the user to physi
cally move around, such as those that track movement with a real-world camera, this boundary establishes the edges of the area the user is able to move around in, whether due to physical obstacles or due to limitations of the xr hardware.
... 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 5 more matches
Box-shadow generator - CSS: Cascading Style Sheets
) { setvalue(topic, e.target.value | 0); }); subscribe(topic, function(value) { node.children[0].value = value; }); } var increment = function increment(topic) { var slider = sliders[topic]; if (slider === null || slider === undefined) return; if (slider.value + slider.step <= slider.max) { slider.value += slider.step; setvalue(slider.topic, slider.value) notify.
call(slider); } }; var decrement = function decrement(topic) { var slider = sliders[topic]; if (slider === null || slider === undefined) return; if (slider.value - slider.step >= slider.min) { slider.value -= slider.step; setvalue(topic, slider.value) notify.
call(slider); } } // this = slider object var updateslider = function updateslider(e) { var node = this.node; v...
... if (pos > width) pos = width; var value = pos * delta / width | 0; var precision = value % this.step; value = value - precision + this.min; if (precision > this.step / 2) value = value + this.step; if (this.snap) pos = (value - this.min) * width / delta; this.pointer.style.left = pos - offset/2 + "px"; this.value = value; node.setattribute('data-value', value); notify.
call(this); } var setvalue = function setvalue(topic, value) { var slider = sliders[topic]; if (value > slider.max || value < slider.min) return; var delta = slider.max - slider.min; var width = slider.node.clientwidth; var offset = slider.pointer.clientwidth; var pos = (value - slider.min) * width / delta; slider.value = value; slider.pointer.style.left = pos - offset / 2 + "...
...px"; slider.node.setattribute('data-value', value); notify.
call(slider); } var setmousetracking = function setmousetracking(elem,
callback) { elem.addeventlistener("mousedown", function(e) {
callback(e); document.addeventlistener("mousemove",
callback); }); document.addeventlistener("mouseup", function(e) { document.removeeventlistener("mousemove",
callback); }); } var subscribe = function subscribe(topic,
callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(
callback); } var unsubscribe = function unsubscribe(topic,
callback) { subscribers[topic].indexof(
callback); subscribers[topic].splice(index, 1); } var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i...
...And 5 more matches
DOM onevent handlers - Developer guides
in order to allow multiple handlers to be installed for the same event on a given object, you can
call its addeventlistener() method, which manages a list of handlers for the given event on the object.
... a handler can then be removed from the object by
calling its removeeventlistener() function.
... when an event occurs that applies to an element, each of its event handlers is
called to allow them to handle the event, one after another.
...And 5 more matches
<input type="password"> - HTML: Hypertext Markup Language
it is not as semanti
cally useful as other ways to explain your form, and can cause unexpected technical issues with your content.
... <label for="userpassword">password: </label> <input id="userpassword" type="password"> allowing autocomplete to allow the user's password manager to automati
cally enter the password, specify the autocomplete attribute.
... for passwords, this should typi
cally be one of the following: on allow the browser or a password manager to automati
cally fill out the password field.
...And 5 more matches
<textarea> - HTML: Hypertext Markup Language
autocapitalize this is a non-standard attribute supported by webkit on ios (therefore nearly all browsers running on ios, including safari, firefox, and chrome), which controls whether and how the text value should be automati
cally capitalized as it is entered/edited by the user.
... sentences: automati
cally capitalize the first letter of sentences.
... words: automati
cally capitalize the first letter of words.
...And 5 more matches
Object.prototype.toString() - JavaScript
description every object has a tostring() method that is automati
cally
called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected.
...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.
... examples overriding the default tostring method you can create a function to be
called in place of the default tostring() method.
...And 5 more matches
Promise.prototype.catch() - JavaScript
it behaves the same as
calling promise.prototype.then(undefined, onrejected) (in fact,
calling obj.catch(onrejected) internally
calls obj.then(undefined, onrejected)).
... syntax p.catch(onrejected); p.catch(function(reason) { // rejection }); parameters onrejected a function
called when the promise is rejected.
... return value internally
calls promise.prototype.then on the object upon which it was
called, passing the parameters undefined and the received onrejected handler.
...And 5 more matches
handler.apply() - JavaScript
the handler.apply() method is a trap for a function
call.
... thisarg the this argument for the
call.
... argumentslist the list of arguments for the
call.
...And 5 more matches
Reflect.apply() - JavaScript
the static reflect.apply() method
calls a target function with arguments as specified.
... syntax reflect.apply(target, thisargument, argumentslist) parameters target the target function to
call.
... thisargument the value of this provided for the
call to target.
...And 5 more matches
TypedArray.prototype.reduceRight() - JavaScript
syntax typedarray.reduceright(
callback[, initialvalue]) parameters
callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously returned in the last invocation of the
callback, or initialvalue, if supplied (see below).
... array the typed array reduce was
called upon.
...object to use as the first argument to the first
call of the
callback.
...And 5 more matches
super - JavaScript
the super keyword is used to access and
call functions on an object's parent.
... syntax super([arguments]); //
calls the parent constructor.
...the super keyword can also be used to
call functions on a parent object.
...And 5 more matches
Media container formats (file types) - Web media technologies
see codecs used by webrtc for information about codecs commonly used for making webrtc
calls, as well as browser compatibility information around codec support in webrtc.
... index of media container formats (file types) to learn more about a specific container format, find it in this list and click through to the details, which include information about what the container is typi
cally useful for, what codecs it supports, and which browsers support it, among other specifics.
... 3gp the 3gp or 3gpp media container is used to encapsulate audio and/or video that is specifi
cally intended for transmission over cellular networks for consumption on mobile devices.
...And 5 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
for web developers, it is now fairly common to be
called upon to create a web site or app that changes its user interface depending on the browser or device accessing the site to provide an optimized experience.
... we've written a simple-but-fun prototype for an application
called snapshot, which takes a video stream from your webcam (using getusermedia()) then allows you to capture stills from that video stream (using html5 <canvas>), and save them to a gallery.
... border-box sizing the padding does not affect the overall width and height of the containers because we have set the box-sizing of all elements to border-box: *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } this basi
cally means that width and height will now set the dimensions of an element all the way up to and including the border, not just the content.
...And 5 more matches
Paths - SVG: Scalable Vector Graphics
the "move to" command is
called with the letter m.
...the most generic is the "line to" command,
called with l.
...="100" height="100" xmlns="http://www.w3.org/2000/svg"> <path d="m 10 10 h 90 v 90 h 10 l 10 10"/> <!-- points --> <circle cx="10" cy="10" r="2" fill="red"/> <circle cx="90" cy="90" r="2" fill="red"/> <circle cx="90" cy="10" r="2" fill="red"/> <circle cx="10" cy="90" r="2" fill="red"/> </svg> we can shorten the above path declaration a little bit by using the "close path" command,
called with z.
...And 5 more matches
Web Components
tutorials using custom elements a guide showing how to use the features of custom elements to create simple web components, as well as looking into lifecycle
callbacks and some other more advanced features.
... life cycle
callbacks special
callback functions defined inside the custom element's class definition, which affect its behavior: connected
callback: invoked when the custom element is first connected to the document's dom.
... disconnected
callback: invoked when the custom element is disconnected from the document's dom.
...And 5 more matches
Content Scripts - Archive of obsolete content
instead, sdk add-ons need to factor the code that gets access to web content into separate scripts that are
called content scripts.
... note that tab.attach() doesn't accept contentscriptwhen, because it's generally
called after the page has loaded.
...age-worker you use pageworker.port.on(): // main.js var self = require("sdk/self"); var pageworker = require("sdk/page-worker").page({ contentscriptfile: self.data.url("content-script.js"), contenturl: "http://en.wikipedia.org/wiki/internet" }); pageworker.port.on("first-para", function(firstpara) { console.log(firstpara); }); to emit user-defined messages from your add-on you can just
call pageworker.port.emit(): // main.js var self = require("sdk/self"); var pageworker = require("sdk/page-worker").page({ contentscriptfile: self.data.url("content-script.js"), contenturl: "http://en.wikipedia.org/wiki/internet" }); pageworker.port.on("first-para", function(firstpara) { console.log(firstpara); }); pageworker.port.emit("get-first-para"); // content-script.js self.port.on(...
...And 4 more matches
Modules - Archive of obsolete content
for instance, it does not know how to handle relative urls, which is cumbersome if you want to organize your project hierarchi
cally.
...if the loading script has chrome privileges, then so will any methods
called by the loading script, even if that method was installed by a malicious script.
...a wrapper behaves exactly like the wrapped object, with one difference: for each property access/function it performs an access check to make sure that the
calling script is actually allowed to access/
call that property/function.
...And 4 more matches
Working with Events - Archive of obsolete content
adding listeners you can add a listener to an event emitter by
calling its on(type, listener) method.
...this is a function which will be
called whenever the event occurs.
...if you do this, the listener will be
called for any event emitted by that object, and its argument will be the name of the event: var ui = require("sdk/ui"); var panels = require("sdk/panel"); var self = require("sdk/self"); var panel = panels.panel({ contenturl: self.data.url("panel.html") }); panel.on("*", function(e) { console.log("event " + e + " was emitted"); }); var button = ui.actionbutton({ id: "my-button", label: "m...
...And 4 more matches
page-mod - Archive of obsolete content
the sdk
calls these scripts "content scripts".
... if you supply the scripts as separate files in the "data" directory, you specify them using with a url, typi
cally constructed using the url() method of the self module's data object: var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: data.url("my-script.js") }); var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: [data.url(...
... to stop a page-mod from making any more modifications,
call its destroy() method.
...And 4 more matches
remote/parent - Archive of obsolete content
usage in multiprocess firefox: the browser ui runs in one process, sometimes
called the chrome process or the parent process web content runs in one or more other processes, sometimes
called content processes or remote processes or child processes.
...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.
...the event handler is
called with a process representing the new process.
...And 4 more matches
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 = { onitemadded: function(a...
...it duplicates the previous code, but with a few changes: import emit(), on(), once(), and off() from event/core replace listener functions with
calls to emit(), passing the appropriate event type export its own event api.
...And 4 more matches
File I/O - Archive of obsolete content
an exception is thrown only when methods that require the file to exist are
called, e.g., isdirectory(), moveto(), and so on.
... queryinterface(components.interfaces.nsilocalfile).path); } creating folders fileutils.getdir() can create a folder automati
cally if it doesn't exist yet: components.utils.import("resource://gre/modules/fileutils.jsm"); var dir = fileutils.getdir("profd", ["dir"], true); the above example creates a folder
called "dir" in the user's profile folder.
...you can tell files from folders by
calling nsifile.isdirectory() and nsifile.isfile() methods on each entry.
...And 4 more matches
Enhanced Extension Installation - Archive of obsolete content
installation initiation when an item is installed from the web, xpinstall is invoked and it
calls into the extension system when it discovers that the xpi file contains an install.rdf manifest.
...code in the extension system can quickly locate an install location for an item using the getinstalllocation method which basi
cally reads this value from the datasource and retrieves the install location from the hash of registered install locations.
...if updated compatibility information is found this is written into the in-memory representation of the the temporary install manifest and the install function is
called recursively, supplying this updated install manifest as the source for _getinstalldata.
...And 4 more matches
Install Manifests - Archive of obsolete content
the file must be
called install.rdf and live at the top level of an add-on's xpi file.
...if you do not provide an id, the add-ons site will generate an id for your add-on automati
cally.
... note: extensions compatible with firefox 3.5 should specify a maxversion of 3.5.*, so that they are automati
cally compatible with security and stability updates.
...And 4 more matches
Installing Extensions and Themes From Web Pages - Archive of obsolete content
users can save the xpi file to disk easily by right clicking on the link and choosing "save link as..." when the link is clicked it
calls the function install passing the event object as the parameter.
... the install first creates a parameter block: var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } }; this specifies the display name (foo) for use in the confirmation dialog, the url to the extension (which is the link href, re
call), the icon url to display in the confirmation dialog, a hash of the xpi file contents (to protect against corrupted downloads), and a tostring function which will allow this code to work with versions of firefox 0.8 and earlier.
... installtrigger.install is then
called to install the item with the parameter block.
...And 4 more matches
Jetpack Processes - Archive of obsolete content
privileged apis when script is evaluated in a jetpack process via a
call to nsijetpack.evalscript(), the script's global scope is endowed with the following privileged apis: sendmessage(amessagename [, v1 [, v2 [, ...]]]) similar to nsijetpack.sendmessage(), this function asynchronously sends a message to the chrome process.
...
callmessage(amessagename [, v1 [, v2 [, ...]]]) this function is like sendmessage() but sends the message synchronously.
...registerreceiver(amessagename, areceiver) similar to nsijetpack.registerreceiver(), this function registers a
callback that is triggered when the chrome process sends a message with the given name.
...And 4 more matches
Listening to events in Firefox extensions - Archive of obsolete content
simple dom events registering for a dom event is done using with code such as the following: function
callback(evt) { // do your processing here.
...} b.addeventlistener("event",
callback, false) where b is the browser or tabbrowser you wish to watch for events from.
...the pageshow event uses a boolean property
called persisted that is set to false on the initial load.
...And 4 more matches
Adding windows and dialogs - Archive of obsolete content
in general, windows should not be resizable unless they display dynami
cally generated content from a datasource, such as lists or trees that may need resizing to have a better view of the content.
...this means the opendialog function
call will not return until the dialog has been closed by the user.
...it's ok to use this function if you're just debugging some problem and want to see if the program reaches a specific line of code, or to inspect the value of a variable, but your final extension should not have alert
calls anywhere.
...And 4 more matches
JavaScript Object Management - Archive of obsolete content
if your add-on is
called sergeant pepper, for instance, then sgtpepper would be a good namespace name.
...〈namespace〉.hello.init(); 〈namespace〉.hello["init"](); this is very useful in cases where you have to set attributes or functions with dynami
cally generated names.
... notice the way we send
callback functions as parameters, and the use of an alternate reference for this which we always name that.
...And 4 more matches
The Box Model - Archive of obsolete content
with xul you can define verti
cally oriented as well as horizontally oriented interfaces, providing greater flexibility in interface design.
...however, one of the fundamental differences between xul and html has been the fact that xul boxes can be oriented verti
cally or horizontally (this behavior is being introduced into html standards).
...a vbox is oriented verti
cally by default, its child nodes displayed one below the other from top to bottom.
...And 4 more matches
JXON - Archive of obsolete content
the parker convention the functions listed above for the conversion of an xml document to json (often
called "jxon algorithms") are more or less freely based on the parker convention (especially regarding the transformation of tags names into object properties names, the recognition of the typeof of all the collected text content of each tag and the absorption of solitary text and/or cdatasection nodes into primitive values).
... it is
called “parker convention” in opposition to “badgerfish convention”, after the comic parker & badger by cuadrado.
...point 5 is automati
cally managed by the javascript method json.stringify().
...And 4 more matches
Notes on HTML Reflow - Archive of obsolete content
the html formatting objects are
called frames : a frame corresponds to the geometric information for (roughly) a single element in the content model; the frames are arranged into a hierarchy that parallels the containment hierarchy in the content model.
...elements later "in the flow" typi
cally do not affect the geometry of elements that are earlier "in the flow", so layout can proceed left-to-right, top-to-bottom through the document.
...incremental reflow although all of the reflow in gecko attempts to re-use as much existing state as possible (and is in therefore some sense "incremental") an incremental reflow corresponds to a reflow that is specifi
cally targeted at an individual frame in the frame hierarchy.
...And 4 more matches
Getting Started - Archive of obsolete content
the folder containing seamonkey is
called folder_with_seamonkey in this manual.
... extract theme while you can hypotheti
cally begin with any theme already designed for seamonkey 2, for the sake of consistency we'll speak as though everyone is editing classic (default seamonkey theme).
...opening the .jar files in your archive manager of choice should result in the file being automati
cally detected as being a zip archive.
...And 4 more matches
Building accessible custom components in XUL - Archive of obsolete content
(techni
cally, it draws the border inside the element instead of outside.) <code> grid.spreadsheet description:focus, grid.spreadsheet label:focus { outline: 1px dotted black; outline-offset: -2px; } </code> however, neither of those are our biggest problem.
...the individual cells, row headers, and column headers are not in the tab order, but we can still set focus to them programmati
cally using javascript whenever the user clicks a specific cell.
...the only remaining issue is that when the spreadsheet regains focus (by pressing shift-tab, or cycling all the way around the tab order and coming back into the spreadsheet), we need to programmati
cally reset the focus to the previously focused cell.
...And 4 more matches
Menus - Archive of obsolete content
no special code needs to be written to open or close a menu or submenu, and, in addition, the menus are placed on screen in the appropriate locations automati
cally.
...other user interfaces
call this type of widget a combobox.
...another way is to add shortcut keys
called access keys for each menu element to make it easier to access the menu commands.
...And 4 more matches
RDF Modifications - Archive of obsolete content
no extra code needs to be written to do this; it happens automati
cally.
...the first is when the modification functions on the datasource are
called.
...for instance, an assert
call looks like the following: var source = rdf.getresource("http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg"); var predicate = rdf.getresource("http://purl.org/dc/elements/1.1/description"); var target = rdf.getliteral("one of the thirty or so egyptian obelisks"); datasource.assert(source, predicate, target, true); the assert
call adds a new triple to the rdf datasource.
...And 4 more matches
Install Scripts - Archive of obsolete content
the installer script must be
called install.js and must be placed at the top level of the installer archive.
... the script will contain javascript code which
calls a number of install functions.
...that means that you can
call the methods of the window object with the qualifier before it, which means that window.open() can simply be written open().
...And 4 more matches
Trees - Archive of obsolete content
in a tree, all of the data to be displayed is supplied by a separate object,
called a tree view.
... when it comes time to display a cell, the tree widget will
call out to this tree view to determine what to display, which in turn will be drawn by the tree.
...these functions will be
called by the tree as necessary to retrieve data and state about the tree.
...And 4 more matches
notificationbox - Archive of obsolete content
typi
cally the element will be a browser, but any element may be used.
... the notification element is used for each notification, and will be created automati
cally for each item.
... finding the current notification box within a firefox extension, you can retrieve the current notification box for a specific tab by
calling the global function getnotificationbox(): notifybox = chromewin.getnotificationbox(notifywindow) notifybox = getnotificationbox(notifywindow) // applies to current context's window object here, chromewin is the xul window (usually just window), and notifywindow is the web content window for the tab you want to find the notification box for.
...And 4 more matches
Archived Mozilla and build documentation - Archive of obsolete content
automated testing tips and tricks automatic mozilla configurator ankh8 automati
cally handle failed asserts in debug builds as of 2004-12-8, it is now possible to automati
cally handle failed asserts in debug builds of mozilla for windows.
... bookmark keywords practi
cally every web surfer has bookmarks, of course, and power surfers usually have hundreds stuffed into folders within folders.
... java in firefox extensions if you are in need of
calling java code from within a firefox extension, you can make use of liveconnect.
...And 4 more matches
Extentsions FAQ - Archive of obsolete content
these two links should give you a starting point: http://www..xulplanet.com/tutorials/...u/advmenu.html http://www.xulplanet.com/tutorials/x...dommodify.html request for a thunderbird extension that can automati
cally detect the default domain when composing e-mails via autodetect.
... the person was missing a method
call to getservice.
... the problem with most js frameworks is that they bootstrap by dynami
cally appending script elements, which doesn't work in xul, last i checked.
...And 4 more matches
NPWindow - Archive of obsolete content
ws_info unix: contains information about the plug-in's unix window environment; points to an npsetwindow
callbackstruct.
... the browser
calls npp_setvalue whenever the drawable changes.
...for windowed plug-ins, the browser
calls the npp_setwindow method with an npwindow structure that represents a drawable (a pointer to an npwindow allocated by the browser).
...And 4 more matches
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.
...in addition, all data sent over an encrypted ssl connection is protected with a mechanism for detecting tampering-that is, for automati
cally determining whether the data has been altered in transit.
...it is typi
cally supported in case a client and server have none of the other ciphers in common.
...And 4 more matches
Handling different text directions - Learn web development
in recent years however, css has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as japanese) — these different directionalities are
called writing modes.
... a writing mode in css refers to whether the text is running horizontally or verti
cally.
...the text now runs verti
cally.
...And 4 more matches
How does the Internet work? - Learn web development
deeper dive a simple network when two computers need to communicate, you have to link them, either physi
cally (usually with an ethernet cable) or wirelessly (for example with wifi or bluetooth systems).
... to solve this problem, each computer on a network is connected to a special tiny computer
called a router.
... such a network comes very close to what we
call the internet, but we're missing something.
...And 4 more matches
What is a web server? - Learn web development
we
call it "static" because the server sends its hosted files as-is to your browser.
...we
call it "dynamic" because the application server updates the hosted files before sending content to your browser via the http server.
...typi
cally, these kinds of sites are composed of only a few html templates and a giant database, rather than thousands of static html documents.
...And 4 more matches
Tips for authoring fast-loading HTML pages - Learn web development
tools such as html tidy can automati
cally strip leading whitespace and extra blank lines from valid html source.
... a cdn is a geographi
cally distributed network of servers that work together to shorten the distance between the user and your website.
...most web servers automati
cally append the last-modified header to static pages (e.g.
...And 4 more matches
General asynchronous programming concepts - Learn web development
mac users, for example, sometimes experience this as the spinning rainbow-colored cursor (or "beachball" as it is often
called).
...this is
called blocking; the browser is blocked from continuing to handle user input and perform other tasks until the web app returns control of the processor.
... threads a thread is basi
cally a single process that a program can use to complete tasks.
...And 4 more matches
Test your skills: Strings - Learn web development
you already have half of a famous quote inside a variable
called quotestart; we would like you to: look up the other half of the quote, and add it to the example inside a variable
called quoteend.
...save the result inside a variable
called finalquote.
...we would like you to: retrieve the length of the quote, and store it in a variable
called quotelength.
...And 4 more matches
Test your skills: Object-oriented JavaScript - Learn web development
create a new instance of the shape class
called square.
...
call your calcperimeter() method on the instance, to see whether it logs the calculation result to the browser devtools' console as expected.
... create a new instance of shape
called triangle, with a name of triangle and a sidelength of 3.
...And 4 more matches
Client-Server Overview - Learn web development
the first part is
called the header, and contains useful information about the request, in the same way that an html head contains useful information about an html document (but not the actual content itself, which is in the body): get https://developer.mozilla.org/search?q=client+server+overview&topic=apps&topic=html&topic=css&topic=js&topic=api&topic=webdev http/1.1 host: developer.mozilla.org connection: keep-alive...
... the web application dynami
cally creates an html page by putting the data (from the database) into placeholders inside an html template.
...it can instead dynami
cally create and return other types of files (text, pdf, csv, etc.) or even data (json, xml, etc.).
...And 4 more matches
Getting started with Svelte - Learn web development
then we will learn how to setup our development environment, create a sample app, understand the structure of the project, and see how to run it lo
cally and build it for production.
...svelte will watch for file updates, and automati
cally recompile and refresh the app for you when changes are made to the source files.
... at this point you can try updating your app.svelte component — for example change the <h1> element on line 6 of app.svelte so that it reads like this: <h1>hello {name} from mdn!</h1> just save your changes and the app running at localhost:5000 will be automati
cally updated.
...And 4 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
dynami
cally generating the todos from the data at the moment, our displayed todo items are all static.
...at the bottom of the todos.svelte <script> section, add the removetodo() function like so: function removetodo(todo) { todos = todos.filter(t => t.id !== todo.id) } we'll
call it via the delete button.
...in our app, the todos array value is updated directly every time a todo is toggled or deleted, and so svelte will update the dom automati
cally.
...And 4 more matches
Software accessibility: Where are we today?
many, including those who were blind or physi
cally disabled, were unable to use applications which were written for microsoft operating systems.
... physi
cally disabled: users have amputations, paralysis, repetitive stress, cerebral palsy, muscular dystrophy, parkinson's or other problems limiting mobility.
... refreshable braille displays of various sizes a braille embosser audio- and braille- based user interfaces are concepts that software designers are histori
cally untrained for.
...And 4 more matches
Theme concepts
if you have a lightweight theme it will be converted to this new theme format automati
cally before lightweight themes are deprecated.
...you can, however, programmati
cally include a theme in an extension using the theme api.
... add the theme image file to the folder: <mytheme> <your_header_image>.<type> create a file
called manifest.json in the folder and edit its content as follows: { "manifest_version": 2, "version": "1.0", "name": "<your_theme_name>", "theme": { "images": { "theme_frame": "<your_header_image>.<type>" }, "colors": { "frame": "#ffffff", "tab_background_text": "#000" } } } where: "frame": is the heading area background color for your theme.
...And 4 more matches
Debugging OpenGL
if you start up firefox with this variable defined, the following behavior changes occur: each time you issue an opengl
call, a check is performed to ensure that the gl context is current, using a thread-local static variable to keep track of this.
... if the context isn't current, the
call aborts.
... every time an opengl
call completes, glfinish() gets run automati
cally.
...And 4 more matches
Debugging on Windows
microsoft child process debugging power tool allows automati
cally attaching to child processes, such as web content process, gpu process, etc.
... in vc 7 and 8 this option is
called project > properties > debugging > command arguments.
... vc++ 7.0 automati
cally finds additional dlls.
...And 4 more matches
Configuring Build Options
(it is possible to manually
call configure with command-line options, but this is not recommended).
... setting the mozconfig path: export mozconfig=$home/mozilla/mozconfig-firefox
calling the file .mozconfig (with a leading dot) is also supported, but this is not recommended because it may make the file harder to find.
...if you do not specify a moz_objdir, it will be automati
cally set to @topsrcdir@/obj-@config_guess@.
...And 4 more matches
Frame script loading and lifetime
l: // 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.
... if allowdelayedload is false, the script will only be loaded into frames which are open when the
call was made.
...passing allowdelayedload is a way to ensure that the script is loaded correctly, in case the tab is not ready when making the
call.
...And 4 more matches
Storage access policy: Block cookies from trackers
specifi
cally, we check the exact hostname of the resource against the list, as well as the last four hostnames formed by starting with the last five components and successively removing the leading component.
...specifi
cally, firefox does this by imposing the following restrictions: cookies: block cookie request headers and ignore set-cookie response headers.
... return an empty string for
calls to document.cookie and ignore requests to set cookies via document.cookie.
...And 4 more matches
UpdateListener
an updatelistener receives messages from an update check for a single add-on, though it is possible to pass the same updatelistener to as many
calls to findupdates() as you like.
... for each individual update check, the following methods will be
called on the listener: either oncompatibilityupdateavailable() or onnocompatibilityupdateavailable(), depending on whether compatibility information for the requested application version was seen.
... method overview void oncompatibilityupdateavailable(in addon addon) void onnocompatibilityupdateavailable(in addon addon) void onupdateavailable(in addon addon, in addoninstall install) void onnoupdateavailable(in addon addon) void onupdatefinished(in addon addon, in integer error) methods oncompatibilityupdateavailable()
called when the update check found compatibility information for the application and platform version that the update check was being performed for.
...And 4 more matches
Add-on Manager
many functions in the add-on manager interface operate asynchronously returning results through
callbacks passed to the functions.
... the
callbacks may be
called immediately while the initial function is still executing or shortly after, depending on when the requested data becomes available.
...all of its functions are asynchronous, meaning that a
callback function must be passed to receive the addon instances.
...And 4 more matches
DeferredTask.jsm
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.
...multiple
calls don't introduce further delays.
...multiple "arm"
calls within the same tick of the event loop are guaranteed to result in a single execution of the task.
...And 4 more matches
Bootstrapping a new locale
hg allows localizers to work lo
cally on their machines and then "push" changes to their official mozilla repository.
... you will need to "hg clone" the existing release branch for mozilla so you have all the files lo
cally for you to begin localization.
...we'll first navigate to the directory
called "browser" by running the following commands one after the other from your command line: $ cd [ab-cd]/browser/chrome/browser to see what is contained in "browser" type $ ls and, you should see the following output from your terminal: aboutcerterror.dtd pageinfo.dtd aboutdialog.dtd pageinfo.properties aboutprivatebrowsing.dtd pagereportfirsttime.dtd aboutrobots.d...
...And 4 more matches
NSPR's Position On Abrupt Thread Termination
in that environment, exit() may be
called and any time, and results in the
calling thread's immediate termination.
...nspr has defined a function,
callable by any thread within a process at any time,
called pr_processexit().
...when
called, the process exits, closing files and reclaiming the process' storage.
...And 4 more matches
Date and Time
a time instant is represented by its position on the time line relative to the origin,
called the epoch.
...the nspr data type for clock/calendar time,
called an exploded time, has the time zone information in it, so that its corresponding point in absolute time is uniquely specified.
... macros for time unit conversion types and constants time parameter
callback functions functions macros for time unit conversion macros for converting between seconds, milliseconds, microseconds, and nanoseconds.
...And 4 more matches
Named Shared Memory
pr_attachsharedmemory should be
called following pr_opensharedmemory to map the memory segment to an address in the application's address space.
... pr_attachsharedmemory may also be
called to remap a shared memory segment after detaching the same prsharedmemory object.
... pr_detachsharedmemory should be
called to unmap the shared memory segment from the application's address space.
...And 4 more matches
PR_JoinThread
blocks the
calling thread until a specified thread terminates.
...the function is synchronous in that it blocks the
calling thread until the target thread is in a joinable state.
... pr_jointhread returns to the
caller only after the target thread returns from its root function.
...And 4 more matches
PR_NormalizeTime
adjusts the fields of a clock/calendar time to their proper ranges, using a
callback function.
... params a time parameter
callback function.
... returns nothing; the time parameter is altered by the
callback function.
...And 4 more matches
nss tech note1
the type is undefined as it is completely dependent on the content of the decoder templates.† this typi
cally points to a struct that is described (or partially described) by the templates.
...if templates are nested, the offset applies to the location of the current component within the target component, typi
cally the decoded sequence.
...if kind contains the sec_asn1_xtrn or sec_asn1_dynamic modifiers, this is a pointer to a
callback function that will dynami
cally return the required subtemplate.
...And 4 more matches
NSS tools : signtool
you typi
cally get a certificate from an independent ca if you want to sign software that will be distributed over the internet.
...if the certificate authority's certificate isn't already installed in your copy of communicator, you typi
cally install it by clicking the appropriate link on the certificate authority's web site, for example on the page from which you initiated enrollment for your signing certificate.
... when you receive an object-signing certificate for your own use, it is automati
cally installed in your copy of the communicator client software.
...And 4 more matches
Introduction to the JavaScript shell
you can also pass in, on the command line, a javascript program file to run, in which case the program is run automati
cally.
...every string has a unique identifier,
called an atom.
...if you specified options on the command line, the results of
calling options will indicate which options you requested.
...And 4 more matches
JS::CompileOffThread
syntax bool js::cancompileoffthread(jscontext *cx, const js::readonlycompileoptions &options, size_t length); bool js::compileoffthread(jscontext *cx, const js::readonlycompileoptions &options, const char16_t *chars, size_t length, js::offthreadcompile
callback
callback, void *
callbackdata); jsscript * js::finishoffthreadscript(jscontext *maybecx, jsruntime *rt, void *token); typedef void (*js::offthreadcompile
callback)(void *token, void *
callbackdata); name type description cx / maybe jscontext * pointer to a js context from which to derive runtime information.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...
callback js::offthreadcompile
callback a
callback function invoked when the compilation.
...And 4 more matches
JS::Construct
this article covers features introduced in spidermonkey 38
call a specified js constructor.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
... fun js::handlevalue pointer to the function to
call.
...And 4 more matches
JSFinalizeOp
the garbage collector
calls this
callback for each object it collects.
... warning: this hook is
called during garbage collection.
... any jsapi
call that would allocate memory from the gc heap will fail if
called from a finalizer.
...And 4 more matches
JSNewEnumerateOp
this
callback overrides a portion of spidermonkey's default [[enumerate]] internal method.
...this
callback overrides a portion of spidermonkey's default [[enumerate]] internal method.
... when an ordinary object is enumerated, that object and each object on its prototype chain is tested for an enumerate op, and those ops are
called in order.
...And 4 more matches
JSObjectOps.dropProperty
the jsobjectops.dropproperty
callback releases a jsproperty.
... syntax typedef void (*jspropertyrefop)(jscontext *cx, jsobject *obj, jsproperty *prop); name type description cx jscontext * a context that was the cx argument to an earlier
call to jsobjectops.lookupproperty that found a property.
... description the following contract governs jsobjectops
callers and implementations: whenever jsobjectops.lookupproperty returns a jsproperty pointer, the property is locked.
...And 4 more matches
JS_AddArgumentFormatter
(at the moment, js_addargumentformatter fails only if there is no memory available to record the registration.) js_addargumentformatter does not copy format, it points at the string storage allocated by the
caller, which is typi
cally a string constant.
... if format is in dynamic storage, the
caller must keep the string alive until js_removeargumentformatter is
called.
...
callback syntax jsbool (*jsargumentformatter)(jscontext *cx, const char *format, jsbool fromjs, jsval **vpp, va_list *app); name type description cx jscontext * the context in which the conversion is being performed.
...And 4 more matches
JS_Add*Root
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...that could cause sporadic crashes during garbage collection, which can be hard to debug.) the variable must remain in memory until the balancing
call to js_removeroot.
...if the variable points to an object, then any memory reachable from its properties is automati
cally protected from garbage collection, too.
...And 4 more matches
JS_DefineProperty
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... getter jsnative the property getter
callback, which the javascript engine will
call each time the property's value is accessed; or null.
... setter jsnative the property setter
callback, which the javascript engine will
call each time the property is assigned; or null.
...And 4 more matches
JS_DefinePropertyWithTinyId
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... tinyid int8 8-bit id to aid in sharing getter and setter
callbacks among properties.
... tinyid is a signed 8-bit integer that affects the id value passed to certain
callbacks.
...And 4 more matches
JS_EnterLocalRootScope
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...to avoid
calling js_addroot and js_removeroot to manage global roots temporarily.
...
calling js_enterlocalrootscope and js_leavelocalrootscope around the body of the native hook protects each object, double, and string created using the same jscontext from gc.
...And 4 more matches
JS_FS
syntax #define js_fs(name,
call,nargs,flags) ...
... #define js_fn(name,
call,nargs,flags) ...
... #define js_sym_fn(symbol,
call,nargs,flags) ...
...And 4 more matches
JS_InitClass
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... unlike other jsnatives, this function must not
call js_this or js_this_object.
...after a successful
call to js_initclass, javascript code can see and manipulate the class's constructor and prototype just as if it were an ordinary javascript function with a prototype property.
...And 4 more matches
JS_IsConstructing
determine whether the currently executing jsnative was
called as a constructor.
...use
callargs::isconstructing or
callreceiver::isconstructing instead.
... description js_isconstructing must be
called only from a jsnative
called from the engine.
...And 4 more matches
JS_NewExternalString
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...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.
... (ultimately, the string will be garbage collected, and the javascript engine will
call the string finalizer
callback, allowing the application to free the array.) the array does not need to be zero-terminated.
...And 4 more matches
JS_NewFunction
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 ty...
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...
call jsnative native c/c++ implementation of this function.
...And 4 more matches
JS_TracerInit
syntax void js_tracerinit(jstracer *trc, jsruntime *rt, jstrace
callback
callback); name type description trc jstracer * the tracer to be initialized.
...
callback jstrace
callback a
callback, described below, which the tracing apis will
call each time a pointer is found from one gc thing to another.
...
callback syntax typedef void (*jstrace
callback)(jstracer *trc, void *thing, uint32 kind); name type description trc jstracer * the tracer visiting obj.
...And 4 more matches
SpiderMonkey 1.8
in certain cases, the javascript engine no longer
calls jsclass.resolve
callbacks repeatedly, as it did in previous versions.
... specifi
cally, if a property lookup first
calls a resolve hook which does not define the property, then finds the property on a prototype, that result can be cached.
... the security apis js_setcheckobjectaccess
callback, js_setprincipalstranscoder, and js_setobjectprincipalsfinder are still present but are deprecated in this release.
...And 4 more matches
Secure Development Guidelines
sing x86 as an example 6 basic registers (eax, ebx, ecx, edx, edi, esi) 2 stack-related registers (esp, ebp) mark top and bottom of current stack frame status register (eflags) contains various state information instruction pointer (eip) points to register being executed; can’t be modified directly introduction: gaining control (2) eip is modified using
call or jump instructions attacks usually rely on obtaining control over the eip otherwise the attacker can try to control memory pointed to by an existing function pointer a vulnerability is required to modify the eip or sensitive memory saved return addr or function pointer get altered introduction: gaining control (3) common issues used to gain control buffer overflows format stri...
...t vulnerabilities are a result of un-validated input always perform input validation could save you without knowing it examples: if it doesn’t have to be negative, store it in an unsigned int if the input doesn’t have to be > 512, cut it off there if the input should only be [a-za-z0-9], enforce it cross site scripting (xss) xss is a type of code injection attack typi
cally occurs in web applications injection of arbitrary data into an html document from another site victim’s browser executes those html instructions could be used to steal user credentials think: webmail, online auction, cms, online banking...
... bbv: stack overflow example: void foo(char *bar) { char c[12]; strcpy(c, bar); } int main(int argc, char **argv) { foo(argv[1]); } bbv: stack overflow before the stack overflow bbv: stack overflow after the stack overflow bbv: heap overflow dynamic memory malloc()
calloc() heapalloc() mmap() not on the stack segment!
...And 4 more matches
History Service Design
this is possible through a relevance algorithm that assigns a param
called frecency to every page in history, see the places frecency algorithm for major informations.
... actual tasks executed by this service include: database creation, maintenance and initialization: all services rely on a common shared database
called places.sqlite.
...in case the database has been created for the first time history service will create all tables, indexes and triggers,
calling related inittables static methods of other dependant services.
...And 4 more matches
Avoiding leaks in JavaScript XPCOM components
there are no
calls to malloc and free and no reference counting.
... basics of memory management creating objects that are not a fixed size for the lifetime of the program (global variables) or a fixed size for the lifetime of a function (stack variables) requires a system for dynamic memory allocation: a system that allocates memory from a space
called the heap.
... 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.
...And 4 more matches
XPCOM Stream Guide
there are two ways of getting the input stream: by
calling the channel's .open() method for a synchronous read, or by
calling the channel's .asyncopen() method with an nsistreamlistener object.
...if everything goes well,
calling the stream's .finish() method overwrites the original file with the new file.
... using streams in c++ using streams in javascript input streams input streams are not scriptable - you cannot directly
call .read() on them, for example.
...And 4 more matches
Components.utils
if the parameter is passed, the runnable will be dispatch in the compartment of the parameter, which affects which error reporter gets
called.
... exportfunction() export a javascript function from a more-privileged to a less-privileged scope, allowing it to be
called in the less-privileged scope.
...may only be
called from javascript code.
...And 4 more matches
Language bindings
more specifi
cally, an xpcom language binding: enables access to xpcom objects from that language (where access means reading/writing/creating xpcom objects as well as
calling methods on them).
...the scriptable methods on the nsicomponentmanager interface can be
called directly on this object.components.resultscomponents.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at table of errors), with the value of each corresponding to that constant's value.components.returncodecomponents.stackcomponents.stack is a read only property of type nsistackframe (idl definition) that...
... represents a snapshot of the current javascript
callstack.
...And 4 more matches
NS_InitXPCOM3
« xpcom api reference summary the ns_initxpcom3 function initiates use of xpcom in the
calling process with support for stati
cally defined xpcom modules.
...the service manager may alternatively be accessed by
calling ns_getservicemanager.
...some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is
called before xpcom's static initialization code executes.
...And 4 more matches
mozIJSSubScriptLoader
note: this method must only be
called from javascript!
... it defaults to the global object of the
caller.
... note that let and const declarations in the script will be placed on a syntactic scope that is not an object at all, and will not be available to the
caller of loadsubscript.
...And 4 more matches
nsIAppShell
calls to this function may be nested.
... when the number of
calls that pass pr_true is subtracted from the number of
calls that pass pr_false is greater than 0, performance is given precedence over preventing event starvation.
...
calls to suspendnative() and resumenative may be nested.
...And 4 more matches
nsIAppShellService
hiddendomwindow nsidomwindow return the (singleton) application hidden window, automati
cally created and maintained by this appshellservice.
... hiddenwindow nsixulwindow return the (singleton) application hidden window, automati
cally created and maintained by this appshellservice.
...(and at application startup, on platforms that do not normally quit when the last window has closed,
call enter once, but not exit) void enterlastwindowclosingsurvivalarea(); parameters none.
...And 4 more matches
nsICacheSession
does not block the
calling thread.
...it returns a unique descriptor each time it is
called, even if the same key is specified.
... when
called by multiple threads for write access, only one writable descriptor will be granted.
...And 4 more matches
nsICompositionStringSynthesizer
the composing string information is cleared by a
call of .dispatchevent().
... attr_selectedrawtext 0x03 a clause attribute but this is typi
cally not used.
... if appendclause() hasn't been
called, this dispatches events to set composition string without clause information.
...And 4 more matches
nsIContentSecurityPolicy
calls to this may trigger violation reports when queried, so this value should not be cached.
...
calls to this may trigger violation reports when queried, so this value should not be cached.
...
calls to this may trigger violation reports when queried, so this value should not be cached.
...And 4 more matches
nsICryptoHMAC
note: this method may be
called any time after init() is
called.
... this
call resets the object to its pre-init state.
...exceptions thrown ns_error_not_initialized if init() has not been
called.
...And 4 more matches
nsIDNSService
if not null, this parameter specifies the nsieventtarget of the thread on which the listener's onlookupcomplete should be
called.
... if this parameter is null, then onlookupcomplete will be
called on an unspecified thread (possibly recursively).
... init() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)
called to initialize the dns service.
...And 4 more matches
nsIFrameScriptLoader
frame scripts are loaded as soon as loadframescript() is
called.
... if this function is
called on a chromemessagebroadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aallowdelayedload is true, then the script will also be loaded into any applicable new frames opened after the loadframescript()
call.
... otherwise it will only be loaded into frames that exist at the time of the
call.
...And 4 more matches
nsIJetpack
registerreceiver() this registers a
callback to be triggered whenever the jetpack process sends a particular message.
... note: multiple
callbacks may be registered for the same message; they will all be triggered.
... void registerreceiver( in astring amessagename, in jsval areceiver ); parameters amessagename the name of the message from the jetpack process on which the
callback is triggered.
...And 4 more matches
nsIProtocolHandler
keep in mind that the decision of what constitutes an automatic load is made externally, by the
caller of nsiscriptsecuritymanager.checkloaduri().
... typi
cally, this flag is used by protocols that show highly untrusted content in a viewing area that the user expects to have a lot of control over, such as an email reader.
... uri_loadable_by_subsumers 1<<14 the uris for this protocol can be loaded only by
callers with a principal that subsumes this uri.
...And 4 more matches
nsIPushService
implemented by @mozilla.org/push/service;1 as a service: const pushservice = components.classes["@mozilla.org/push/service;1"] .getservice(components.interfaces.nsipushservice); method overview void subscribe(in domstring scope, in nsiprincipal principal, in nsipushsubscription
callback
callback); void getsubscription(in domstring scope, in nsiprincipal principal, in nsipushsubscription
callback
callback); void unsubscribe(in domstring scope, in nsiprincipal principal, in nsiunsubscriberesult
callback
callback); methods subscribe() creates a push subscription.
... void subscribe( in domstring scope, in nsiprincipal principal, in nsipushsubscription
callback
callback ); parameters scope the serviceworkerregistration.scope for a service worker subscription, or a unique url (for example, chrome://my-module/push) for a system subscription.
...
callback the
callback to
call when the nsipushsubscription is created.
...And 4 more matches
nsIRequest
inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) for example nsichannel typi
cally passes itself as the nsirequest argument to the nsistreamlistener on each onstartrequest, ondataavaliable, and onstoprequest invocation.
...for https, this flag is set automati
cally.
...by default, cached content is automati
cally validated if necessary before reuse.
...And 4 more matches
nsIScriptableIO
nsiinputstream: a stream returned by a previous
call to this method, or any other object that implements nsiinputstream.
...if the text mode is specified, a buffer is always used, regardless of whether or not it is specifi
cally requested.
... deleteonclose: the file is automati
cally deleted when the stream is closed.
...And 4 more matches
nsISimpleEnumerator
inherits from: nsisupports last changed in gecko 0.9.6 method overview nsisupports getnext(); boolean hasmoreelements(); methods getnext()
called to retrieve the next element in the enumerator.
... the "next" element is the first element upon the first
call.
... must be preceded by a
call to hasmoreelements() which returns pr_true.
...And 4 more matches
nsITransaction
this attribute is checked by the transaction manager after the transaction's execute() method is
called.
... if the transient state is false, a reference to the transaction is held by the transaction manager so that the transactions' undotransaction() and redotransaction() methods can be
called.
... if the transient state is true, the transaction manager returns immediately after the transaction's dotransaction() method is
called, no references to the transaction are maintained.
...And 4 more matches
XPCOM Interface Reference by grouping
security this section contains apis for secure channel communications system this section contains application level interfaces including
calls to external support elements (such as device
calls).
... browser autocomplete nsiautocompletecontroller nsiautocompleteinput nsiautocompletesearch console nsiconsolelistener nsiconsolemessage nsiconsoleservice document nsidocshell dom device nsidomgeogeolocation nsidomgeoposition nsidomgeopositionaddress nsidomgeoposition
callback nsidomgeopositioncoords nsidomgeopositionerror nsidomgeopositionerror
callback nsidomgeopositionoptions nsidomglobalpropertyinitializer element nsidomchromewindow nsidomclientrect nsidomelement nsidomhtmlaudioelement nsidomhtmlformelement nsidomhtmlmediaelement nsidomhtmlsourceelement nsidomhtmltimeranges nsidomjswindow nsidom...
...obalscope nsiworkermessageevent nsiworkermessageport nsiworkerscope tree nsitreeboxobject nsitreecolumn nsitreecolumns nsitreecontentview nsitreeselection nsitreeview xform nsixformsmodelelement nsixformsnsinstanceelement nsixformsnsmodelelement xmlhttprequest nsixmlhttprequesteventtarget favicon nsifavicondata
callback nsifaviconservice frame nsichromeframemessagemanager nsiframeloader nsiframeloaderowner nsiframemessagelistener nsiframemessagemanager interface nsijsxmlhttprequest jetpack nsijetpack nsijetpackservice offlinestorage nsiapplicationcache nsiapplicationcachechannel nsiapplicationcachecontainer nsiapplicationcach...
...And 4 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 */ onitemsremove...
...d: function _onitemsremoved(aitems, acollection) { }, /*
called when our database query completes */ onquerycompleted: function _onquerycompleted(conversation_coll) { try { for (var conv in conversation_coll) { //do something with the conversation here alert(conv.subject); } } catch (e) {} } } glodamessage.conversation.getmessagescollection(alistener) alternatively if you need to get a conversation based on the subject, you need to do a query (using the same listener as above).
...(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 */ onitemsremove...
...And 4 more matches
Index
19 creating a gloda message query thunderbird 3, thunderbird this page describes how to programmati
cally create a message query using gloda, thunderbird's global database.
...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.
... initially, the training.dat file is empty (there was discussion of shipping with a default file) on spam detection, the user can choose to move spam to a special "junk" folder the user can configure junk mail can be automati
cally purged from the "junk" folder to analyze a message for spam, we need the entire message, not just the headers.
...And 4 more matches
MailNews fakeserver
onerror command, rest of sent line server's response
called if handler does not define the command function.
... onstartup none server's response
called when a connection is made.
... onmultiline sent line server's response or nothing
called when in multi-line mode.
...And 4 more matches
Using the Multiple Accounts API
news.mozilla.org +- netscape.public.mozilla.announce +- netscape.public.mozilla.mail-news relevant api
calls: nsimsgaccount.incomingserver nsimsgaccountmanager.allservers: a list of all servers held by all accounts.
... in the above example, the list of identities would be as follows: alec flett <alecf@mywork.com>) alec flett <alecf@myisp.com>) alec flett <alecfnospam@myisp.com>) relevant api
calls: nsimsgaccount.identities nsimsgaccountmanager.allservers: a list of all servers across all accounts storage the accounts are stored in the preferences.
...you can do this by referring to the same identity or server key in the preferences, or with clever
calls to the account manager.
...And 4 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.
... creating initialized cdata objects similarly, you can initialize cdata objects with specific values at the type of creation by specifying them as a parameter when
calling the ctype's constructor, like this: var mycdataobj = new type(value); var mycdataobj = type(value); if the size of the specified type isn't undefined, the specified value is converted to the given type.
...this is
called aliasing.
...And 4 more matches
Flash Activation: Browser Comparison - Plugins
tion/x-shockwave-flash' in navigator.mimetypes by default when flash is inactive yes no no 'application/x-shockwave-flash' in navigator.mimetypes when user enables flash yes yes yes <object> with fallback content triggers ui yes, with exceptions no yes small/hidden flash triggers additional ui yes no no enabling flash automati
cally reloads the page no yes yes other features related to flash domain blocking plugin power saver peripheral content pause each of the browser vendors has a roadmap about the future of flash and changes to the user experience.
...this can be done by
calling a javascript function when the plugin is activated: function plugincreated() { // we don't need to see the plugin, so hide it by resizing var plugin = document.getelementbyid('myplugin'); plugin.height = 0; plugin.width = 0; plugin.
callpluginmethod(); } the html, by default, specifies the flash object to be a size that makes it visible, like this: <!-- give the plugin an initial s...
...ize so it is visible --> <object type="application/x-shockwave-flash" data="myapp.swf" id="myplugin" width="300" height="300"> <param name="
callback" value="plugincreated()"> </object> the
callback parameter defined in the html can be
called in flash using its flash.external.externalinterface api.
...And 4 more matches
Gecko Plugin API Reference - Plugins
the names of all of these methods begin with npp_ to indicate that they are implemented by the plug-in and
called by the browser.
...the names of all of these methods begin with npn_ to indicate that they are implemented by the browser and
called by the plug-in.
... warning: you must only
call these from the main thread;
calling them from other threads is not supported and may have unpredictable results.
...And 4 more matches
Debugger.Environment - Firefox Developer Tools
spidermonkey creates debugger.environment instances as needed as the debugger inspects stack frames and function objects;
calling debugger.environment as a function or constructor raises a typeerror exception.
...this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.) if a debugger.environment instance’s referent is not a debuggee environment, then attempting to access its properties (other than inspectable) or
call any its methods throws an instance of error.
...function
calls,
calls to eval, let blocks, catch blocks, and the like create declarative environment records.
...And 4 more matches
Debugger.Script - Firefox Developer Tools
the code passed to a single
call to eval, excluding the bodies of any functions that code defines.
... function properties of the debugger.script prototype object the functions described below may only be
called with a this value referring to a debugger.script instance; they may not be used as methods of other kinds of objects.
... a[i] = i*i;
calling getalloffsets() on that code might yield an array like this: [[0], [5, 20], , [10]] this array indicates that: the first line’s code starts at offset 0 in the script; the for statement head has two entry points at offsets 5 and 20 (for the initialization, which is performed only once, and the loop test, which is performed at the start of each iteration); the th...
...And 4 more matches
UI Tour - Firefox Developer Tools
the performance tool's ui consists of 4 main pieces: toolbar recordings pane recording overview details pane, which may contain any one of: waterfall
call tree flame chart toolbar the toolbar contains buttons to: start and stop a recording import a recording you previously saved clear the recordings pane.
...
call tree the
call tree is a sampling profiler for javascript running in the page.
... it periodi
cally samples the state of the javascript engine, and records the stack for the code executing at the time the sample was taken.
...And 4 more matches
DataTransferItem.webkitGetAsEntry() - Web APIs
note that to read all files in a directory, readentries needs to be
called repeatedly until it returns an empty array.
...that's done by
calling the item's createreader() method.
... after that, directoryreader.readentries() is
called to read in all the entries in the directory.
...And 4 more matches
FileSystemFileEntry.file() - Web APIs
syntax filesystemfileentry.file(success
callback[, error
callback]); parameters success
callback a
callback function which is
called when the file has been created successfully; the file is passed into the
callback as the only parameter.
... error
callback optional if provided, this must be a method which is
called when an error occurs while trying to create the file.
... this
callback receives as input a fileerror object describing the error.
...And 4 more matches
FileSystemFlags.create - Web APIs
filesystemflags is only used when
calling filesystemdirectoryentry.getfile() or filesystemdirectoryentry.getdirectory().
... option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function
called is getfile() or getdirectory() the success
callback is
called with a filesystemfileentry if getfile() was
called or a filesystemdirectoryentry if getdirectory() was
called.
... false n/a[1] path exists but doesn't match the desired type the error
callback is
called with an appropriate error code (if the
callback was provided).
...And 4 more matches
FileSystemFlags.exclusive - Web APIs
the exclusive property on the filesystemflags dictionary is used in tandem with the create property to determine whether or not it's acceptable to require that the file not already exist when the reference to it is created by
calling filesystemdirectoryentry.getfile() or filesystemdirectoryentry.getdirectory().
... option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function
called is getfile() or getdirectory() the success
callback is
called with a filesystemfileentry if getfile() was
called or a filesystemdirectoryentry if getdirectory() was
called.
... false n/a[1] path exists but doesn't match the desired type the error
callback is
called with an appropriate error code (if the
callback was provided).
...And 4 more matches
Using the Frame Timing API - Web APIs
when one of those event types is added to the browser's performance timeline, the application is notified of the event via the observer's
callback function that was specified when the observer was created.
... creating an observer to observe "frame" performance entry types, the application first creates a performanceobserver object with a specific frame observer
callback.
...); 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.
...And 4 more matches
Fullscreen API - Web APIs
this handler is
called only when the entire document is presented in full-screen mode.
... event handlers on elements element.onfullscreenchange an event handler which is
called when the fullscreenchange event is sent to the element, indicating that the element has been placed into, or removed from, full-screen mode.
... dictionaries fullscreenoptions provides optional settings you can specify when
calling requestfullscreen().
...And 4 more matches
Using the MediaStream Recording API - Web APIs
for example, in web dictaphone we have three main ui areas, stacked verti
cally.
...op'); const soundclips = document.queryselector('.sound-clips'); finally for this section, we set up the basic getusermedia structure: if (navigator.mediadevices && navigator.mediadevices.getusermedia) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }) // success
callback .then(function(stream) { }) // error
callback .catch(function(err) { console.log('the following getusermedia error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } the whole thing is wrapped in a test that checks whether getusermedia is supported before running anything else.
... next, we
call getusermedia() and inside it define: the constraints: only audio is to be captured for our dictaphone.
...And 4 more matches
MediaStream Recording API - Web APIs
set mediarecorder.ondataavailable to an event handler for the dataavailable event; this will be
called whenever data is available for you.
... once the source media is playing and you've reached the point where you're ready to record video,
call mediarecorder.start() to begin recording.
... your dataavailable event handler gets
called every time there's data ready for you to do with as you will; the event has a data attribute whose value is a blob that contains the media data.
...And 4 more matches
MutationObserverInit.attributes - Web APIs
syntax var options = { attributes: true | false } value a boolean value indicating whether or not to report through the
callback any changes to the values of attributes on the node or nodes being monitored.
... if true, the
callback specified when observe() was used to start observing the node or subtree will be
called any time one or more attributes have changed on observed nodes.
... if you set either attributefilter or attributeoldvalue to true, attributes is automati
cally assumed to be true, even if you don't expressly set it as such.
...And 4 more matches
RTCConfiguration - Web APIs
if this property isn't specified, a set of certificates is generated automati
cally for each rtcpeerconnection instance.
... this configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future
calls to rtcpeerconnection.setconfiguration().
...you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is
called.
...And 4 more matches
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().
... if the candidate parameter is missing or a value of null is given when
calling addicecandidate(), the added ice candidate is an "end-of-candidates" indicator.
...this is covered in more detail in the articles webrtc connectivity and signaling and video
calling.
...And 4 more matches
RTCPeerConnection.getStats() - Web APIs
obsolete syntax previously, getstats() used success and failure
callbacks to report the results to you, instead of using a promise.
... promise = rtcpeerconnection.getstats(selector, success
callback, failure
callback) parameters selector optional a mediastreamtrack for which to gather statistics.
... success
callback a
callback function to
call when the stats have been retrieved.
...And 4 more matches
Selection - Web APIs
to obtain a selection object for examination or manipulation,
call window.getselection().
... notes string representation of a selection
calling the selection.tostring() method returns the text contained within the selection, e.g.: var selobj = window.getselection(); window.alert(selobj); note that using a selection object as the argument to window.alert will
call the object's tostring method.
...typi
cally, it holds only one range, accessed as follows: var selobj = window.getselection(); var range = selobj.getrangeat(0); selobj is a selection object range is a range object as the selection api specification notes, the selection api was initially created by netscape and allowed multiple ranges (for instance, to allow the user to select a column from a <table>).
...And 4 more matches
Storage Access API - Web APIs
the embedding website needs to add this to allow storage access requests to be successful, along with allow-scripts and allow-same-origin to allow it to
call the api, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ...
...this is enforced through the following constraints: access requests are automati
cally denied unless the embedded content is currently processing a user gesture such as a tap or click.
...access requests are automati
cally denied if the browser detects that the user hasn’t interacted with the embedded content in a first-party context recently (in firefox, "recently" is "within 30 days").
...And 4 more matches
Lifetime of a WebRTC session - Web APIs
see signaling and video
calling for an actual example with a step-by-step explanation of what the code does.
...for developers trying to do peer-to-peer networking, this introduces a conundrum: without a unique identifier for every user device, it’s not possible to instantly and automati
cally know how to connect to a specific device on the internet.
...one peer can output a data object that can be printed out, physi
cally carried (on foot or by carrier pigeon) to another device, entered into that device, and a response then output by that device to be returned on foot, and so forth, until the webrtc peer connection is open.
...And 4 more matches
Using WebRTC data channels - Web APIs
since all webrtc components are required to use encryption, any data transmitted on an rtcdatachannel is automati
cally secured using datagram transport layer security (dtls).
...to do this, simply
call createdatachannel() without specifying a value for the negotiated property, or specifying the property with a value of false.
... this will automati
cally trigger the rtcpeerconnection to handle the negotiations for you, causing the remote peer to create a data channel and linking the two together across the network.
...And 4 more matches
Fundamentals of WebXR - Web APIs
a human eye is typi
cally able to take in a fov of around 135°.
... generally, only the horizontal fov is specifi
cally defined and managed by applications.
... for more details about this, see the optics of 3d in rendering and the webxr frame animation
callback.
...And 4 more matches
Controlling multiple parameters with ConstantSourceNode - Web APIs
we connect its output to the gain audioparam on both gainnode2 and gainnode3, and we start the constant node running by
calling its start() method; now it's sending the value 0.5 to the two gain nodes' values, and any change to constantnode.offset will automati
cally set the gain of both gainnode2 and gainnode3 (affecting their audio inputs as expected).
... function toggleplay(event) { if (playing) { playbutton.innerhtml = "▶️"; stoposcillators(); } else { playbutton.innerhtml = "⏸"; startoscillators(); } } if the playing variable indicates we're already playing the oscillators, we change the playbutton's content to be the unicode character "right-pointing triangle" (▶️) and
call stoposcillators() to shut down the oscillators.
... if playing is false, indicating that we're currently paused, we change the play button's content to be the unicode character "pause symbol" (⏸) and
call startoscillators() to start the oscillators playing their tones.
...And 4 more matches
Migrating from webkitAudioContext - Web APIs
note: there is a library
called webkitaudiocontext monkeypatch, which automati
cally fixes some of these changes to make most code targetting webkitaudiocontext to work on the standards based audiocontext out of the box, but it currently doesn't handle all of the cases below.
... please consult the readme file for that library to see a list of apis that are automati
cally handled by it.
...ontext.decodeaudiodata(xhr.response, function onsuccess(decodedbuffer) { // decoding was successful, do something useful with the audio buffer }, function onfailure() { alert("decoding the audio buffer failed"); }); }; note that the decodeaudiodata() method is asynchronous, which means that it will return immediately, and then when the decoding finishes, one of the success or failure
callback functions will get
called depending on whether the audio decoding was successful.
...And 4 more matches
Using the Web Audio API - Web APIs
a powerful feature of the web audio api is that it does not have a strict "sound
call limitation".
... for example, there is no ceiling of 32 or 64 sound
calls at one time.
...a baseaudiocontext is created for us automati
cally and extended to an online audio context.
...And 4 more matches
Window: popstate event - Web APIs
bubbles yes cancelable no interface popstateevent event handler property onpopstate the history stack if the history entry being activated was created by a
call to history.pushstate() or was affected by a
call to history.replacestate(), the popstate event's state property contains a copy of the history entry's state object.
... these methods and their corresponding events can be used to add data to the history stack which can be used to reconstruct a dynami
cally generated page, or to otherwise alter the state of the content being presented while remaining on the same document.
... note that just
calling history.pushstate() or history.replacestate() won't trigger a popstate event.
...And 4 more matches
WritableStream - Web APIs
it then
calls a function
called sendmessage(), passing the newly created stream and a string.
... inside this function it
calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter.
... a foreach()
call is used to write each chunk of the string to the stream.
...And 4 more matches
XMLHttpRequestEventTarget - Web APIs
t="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="276" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">xmlhttprequesteventtarget</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties xmlhttprequesteventtarget.onabort contains the function to
call when a request is aborted and the abort event is received by this object.
... xmlhttprequesteventtarget.onerror contains the function to
call when a request encounters an error and the error event is received by this object.
... xmlhttprequesteventtarget.onload contains the function to
call when an http request returns after successfully fetching content and the load event is received by this object.
...And 4 more matches
ARIA Test Cases - Accessibility
leopard) n/a n/a - fail window-eyes - - - - nvda - - - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - table legend - no info/test yet n/a not applicable (not supported techni
cally) pass expected behaviour met fail expected behaviour notmet 1.
...these test files are not specifi
cally for testing aria.
...when pressing space, new state should be announced automati
cally.
...And 4 more matches
ARIA: grid role - Accessibility
<!-- more columns --> </tr> <tr> <th scope="row">aisle 2</th> <td tabindex="-1"> <button id="2a" tabindex="-1">2a</button> </td> <td tabindex="-1"> <button id="2b" tabindex="-1">2b</button> </td> <!-- more columns --> </tr> </tbody> </table> description a grid widget contains one or more rows with one or more cells of themati
cally related interactive content.
... page down moves focus down an author-determined number of rows, typi
cally scrolling so the bottom row in the currently visible set of rows becomes one of the first visible rows.
... page up moves focus up an author-determined number of rows, typi
cally scrolling so the top row in the currently visible set of rows becomes one of the last visible rows.
...And 4 more matches
WAI-ARIA Roles - Accessibility
for a full list of roles, see using aria: roles, states, and properties aria: alert rolethe alert role can be used to tell the user an element has been dynami
cally updated.
...elements containing role="checkbox" must also include the aria-checked attribute to expose the checkbox's state to assistive technology.aria: comment rolethe comment landmark role semanti
cally denotes a comment/reaction to some content on the page, or to a previous comment.aria: complementary rolethe complementary landmark role is used to designate a supporting section that relates to the main content, yet can stand alone when separated.
... these sections are frequently presented as sidebars or
call-out boxes.
...And 4 more matches
CSS Animations tips and tricks - CSS: Cascading Style Sheets
the meat of this technique is in the play() function, which is
called when the user clicks on the "run" button.
... here's what happens when the play() function gets
called: the box's list of css classes is reset to simply "box".
... to be sure that the styles are recalculated, we use window.requestanimationframe(), specifying a
callback.
...And 4 more matches
Color picker tool - CSS: Cascading Style Sheets
e; }; color.prototype.getcolor = function getcolor() { if (this.a | 0 === 1) return this.gethexa(); return this.getrgba(); }; /*=======================================================================*/ /*=======================================================================*/ /*========== capture mouse movement ==========*/ var setmousetracking = function setmousetracking(elem,
callback) { elem.addeventlistener('mousedown', function(e) {
callback(e); document.addeventlistener('mousemove',
callback); }); document.addeventlistener('mouseup', function(e) { document.removeeventlistener('mousemove',
callback); }); }; /*====================*/ // color picker class /*====================*/ function colorpicker(node) { this.color = new color(); this.node...
...icker.prototype.inputchangehexa = function inputchangehexa(e) { var value = e.target.value; this.color.sethexa(value); this.setcolor(this.color); }; /*************************************************************************/ // internal pub/sub /*************************************************************************/ colorpicker.prototype.subscribe = function subscribe(topic,
callback) { this.subscribers[topic] =
callback; }; colorpicker.prototype.notify = function notify(topic, value) { if (this.subscribers[topic]) this.subscribers[topic](value); }; /*************************************************************************/ // set picker properties /*************************************************************************/ colorpicker.prototype.setc...
...****/ var setpickermode = function setpickermode(topic, mode) { if (pickers[topic]) pickers[topic].setpickermode(mode); }; var setcolor = function setcolor(topic, color) { if (pickers[topic]) pickers[topic].setcolor(color); }; var getcolor = function getcolor(topic) { if (pickers[topic]) return new color(pickers[topic].color); }; var subscribe = function subscribe(topic,
callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(
callback); }; var unsubscribe = function unsubscribe(
callback) { subscribers.indexof(
callback); subscribers.splice(index, 1); }; var notify = function notify(topic, value) { if (subscribers[topic] === undefined || subscribers[topic].length === 0) return; var color = new color(va...
...And 4 more matches
Variable fonts guide - CSS: Cascading Style Sheets
in all cases, it is still possible to link them with a common font-family name so you can
call them using the same font-family and appropriate font-style.
...this is typi
cally set in css using the font-stretch property, with values expressed as a percentage above or below ‘normal’ (100%), any number greater than 0 is techni
cally valid—though it is far more likely that the range would fall closer to the 100% mark, such as 75%-125%.
...italic designs often include dramati
cally different letterforms from their upright counterparts, so in the transition from upright to italic, a number of glyph (or character) substitutions usually occur.
...And 4 more matches
Value definition syntax - CSS: Cascading Style Sheets
the comma is often used to separate values in enumerations, or parameters in mathematical-like functions; the slash often separates parts of the value that are semanti
cally different, but have a common syntax.
... typi
cally, the slash is used in shorthand properties; to separate component that are of the same type, but belong to different properties.
...
called basic data types, they are represented with their name surrounded by the symbol '<' and '>': <angle>, <string>, … non-terminal data types less common data types,
called non-terminal data types, are also surrounded by '<' and '>'.
...And 4 more matches
Event reference
emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is
called to reload it.
...gzoom database events abort blocked complete error success upgradeneeded versionchange script events afterscriptexecute beforescriptexecute menu events dommenuitemactive dommenuiteminactive window events close popup events popuphidden popuphiding popupshowing popupshown tab events visibilitychange battery events chargingchange chargingtimechange dischargingtimechange levelchange
call events alerting busy
callschanged cfstatechange connecting dialing disconnected disconnecting error held, holding incoming resuming statechange voicechange sensor events compassneedscalibration devicemotion deviceorientation orientationchange smartcard events icccardlockerror iccinfochange smartcard-insert smartcard-remove stkcommand stksessionend cardstatechange sms and ussd events delive...
...for example, this event is triggered if the media has already been loaded (or partially loaded), and the load() method is
called to reload it.
...And 4 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
which side this is will vary depending on the writing-mode, direction, and text-orientation properties, which are typi
cally (but not always) used to adjust text directionality based on the language being displayed.
...this is typi
cally done by breaking down the color into components, such as how much of each of a set of primary colors to mix together, or how bright to make the color.
...although histori
cally it's been necessary to implement your own color picker, html now provides support for browsers to provide one for your use through the <input> element, by using "color" as the value of its type attribute.
...And 4 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
more specifi
cally, this article is for web administrators, server developers, and front-end developers.
...the only way to determine what specifi
cally went wrong is to look at the browser's console for details.
...those are
called “simple requests” in this article, though the fetch spec (which defines cors) doesn’t use that term.
...And 4 more matches
An overview of HTTP - HTTP
the messages sent by the client, usually a web browser, are
called requests and the messages sent by the server as an answer are
called responses.
...it is an application layer protocol that is sent over tcp, or over a tls-encrypted tcp connection, though any reliable transport protocol could theoreti
cally be used.
... each individual request is sent to a server, which handles it and provides an answer,
called the response.
...And 4 more matches
static - JavaScript
static methods aren't
called on instances of the class.
... instead, they're
called on the class itself.
... how a static method can and cannot be
called.
...And 4 more matches
Classes - JavaScript
a constructor can use the super keyword to
call the constructor of the super class.
...static methods are
called without instantiating their class and cannot be
called through a class instance.
...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 4 more matches
Default parameters - JavaScript
in the following example, if no value is provided for b when multiply is
called, b's value would be undefined when evaluating a * b and multiply would return nan.
... to guard against this, something like the second line would be used, where b is set to 1 if multiply is
called with only one argument: function multiply(a, b) { b = (typeof b !== 'undefined') ?
...other falsy values in the second
call in this example, even if the first argument is set explicitly to undefined (though not null or other falsy values), the value of the num argument is still the default.
...And 4 more matches
The arguments object - JavaScript
it has entries for each argument the function was
called with, with the first entry's index at 0.
... however, it can be converted to a real array: var args = array.prototype.slice.
call(arguments); // using an array literal is shorter than above but allocates an empty array var args = [].slice.
call(arguments); as you can do with any array-like object, you can use es2015's array.from() method or spread syntax to convert arguments to a real array: let args = array.from(arguments); // or let args = [...arguments]; the arguments object is useful for functions
called with more a...
...this example function accepts any number of string arguments and returns the longest one: function longeststring() { var longest = ''; for (var i=0; i < arguments.length; i++) { if (arguments[i].length > longest.length) { longest = arguments[i]; } } return longest; } you can use arguments.length to count how many arguments the function was
called with.
...And 4 more matches
Error.prototype.stack - JavaScript
the non-standard stack property of error objects offer a trace of which functions were
called, in what order, from which line and file, and with what arguments.
... the stack string proceeds from the most recent
calls to earlier ones, leading back to the original global scope
call.
... 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.
...And 4 more matches
Map.prototype.forEach() - JavaScript
syntax mymap.foreach(
callback([value][,key][,map])[, thisarg]) parameters
callback function to execute for each entry of mymap.
... thisarg optional value to use as this when executing
callback.
... description the foreach method executes the provided
callback once for each key of the map which actually exist.
...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.
... array optional the typed array map() was
called upon.
...And 4 more matches
TypedArray.prototype.reduce() - JavaScript
syntax typedarray.reduce(
callback[, initialvalue]) parameters
callback function to execute on each value in the typed array, taking four arguments: previousvalue the value previously returned in the last invocation of the
callback, or initialvalue, if supplied (see below).
... array the typed array reduce was
called upon.
...object to use as the first argument to the first
call of the
callback.
...And 4 more matches
Optional chaining (?.) - JavaScript
when used with function
calls, it returns undefined if the given function does not exist.
...if obj.first is null or undefined, the expression automati
cally short-circuits, returning undefined.
...undefined : temp.second); optional chaining with function
calls you can use optional chaining when attempting to
call a method which may not exist.
...And 4 more matches
new operator - JavaScript
arguments a list of values that the constructor will be
called with.
... the constructor function foo is
called with the specified arguments, and with this bound to the newly created object.
...if no argument list is specified, foo is
called without arguments.
...And 4 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
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 comma...
... 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.
... copy it into a sub-directory
called html_template inside your previous new directory.
...And 4 more matches
Interacting with page scripts - Archive of obsolete content
to expose a function defined in a content script to a page script so the page script can
call it, use exportfunction().
...note that the function's closure will be exported, too: // content-script.js var salutation = "hello, "; function greetme(user) { return salutation + user; } exportfunction(greetme, unsafewindow, {defineas: "greetme"}); finally, the "page.html" file adds a button and a page script that
calls the exported function when the user pushes the button: <html> <head> </head> <body> <input id="test" type="button" value="click me"/> <script> var test = document.getelementbyid("test"); test.addeventlistener("click", function() { alert(window.greetme("page script")); }, false); </script> </body> </html> exportfunction() works by structured cloning...
...since structured cloning doesn't work for functions, this means that you can't export functions that take functions as arguments (such as
callbacks) or functions that return functions.
...And 3 more matches
Communicating using "port" - Archive of obsolete content
for example, to receive the context message in a content script associated with a context menu object, you would
call the on function attached to the global self object: self.on("context", function() { // handle the message }); so the port property is essentially used here as a namespace for user-defined messages.
...so to receive messages from a content script associated with a panel you use panel.port.on(): var panel = require("sdk/panel").panel({ contentscript: "self.port.emit('showing', 'panel is showing');" }); panel.port.on("showing", function(text) { console.log(text); }); panel.show(); conversely, to emit user-defined messages from your add-on you can just
call panel.port.emit(): var panel = require("sdk/panel").panel({ contentscript: "self.port.on('alert', function(text) {" + " console.log(text);" + "});" }); panel.show(); panel.port.emit("alert", "panel is showing"); the panel and page-worker objects only host a single page at a time, so each distinct page object only needs a single channel of communication to ...
... it may be
called with any number of parameters, but is most likely to be
called with a name for the message and an optional payload.
...And 3 more matches
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", ...
... to provide this mapping the boolint requires two mandatory attributes
called "on" and "off", both of which are supplied as strings.
... when the user clicks the button, the function listening to the on() function for this preference is
called.
...And 3 more matches
windows - Archive of obsolete content
optional options: name type onopen function a
callback function that is
called when the window has opened.
... onclose function a
callback function that is
called when the window will be
called.
... onactivate function a
callback function that is
called when the window is made active.
...And 3 more matches
/loader - Archive of obsolete content
secure each module in an isolated js sandbox and makes any capability imports explicit via
calls to the require() function.
...in the sdk we
call these "pseudo modules".
... resolve is assigned a function that takes: the id of the module passed into require() the id of the module that
called require() on each require()
call, the supplied function is then
called with the id of the required module and that of the requiring module.
...And 3 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.
...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.
...pet.prototype.
call = function(name) { return this.name === name ?
...And 3 more matches
Listening for Load and Unload - Archive of obsolete content
if your add-on exports a function
called main(), then that function will be
called whenever the add-on is loaded, and it will be passed an object containing a string describing the reason it was loaded as well as any arguments passed to it.
... if your add-on exports a function
called onunload(), then that function will be
called when the add-on is unloaded, and it will be passed a string describing the reason it was unloaded.
... if your add-on exports a function
called main(), that function will be
called immediately after the overall main.js is evaluated, and after all top-level require() statements have run (so generally after all dependent modules have been loaded).
...And 3 more matches
JavaScript timers - Archive of obsolete content
but there are some javascript native functions (timers) which allow us to delay the execution of arbitrary instructions: settimeout() setinterval() setimmediate() requestanimationframe() the settimeout() function is commonly used if you wish to have your function
called once after the specified delay.
... documentation settimeout()
calls a function or executes a code snippet after specified delay.
... setinterval()
calls a function or executes a code snippet repeatedly, with a fixed time delay between each
call to that function.
...And 3 more matches
Intercepting Page Loads - Archive of obsolete content
there are 2 http topics you can listen to, as specified in the observer notifications page: topic description http-on-modify-request
called as an http request is made.
... http-on-examine-response
called after a response has been received from the webserver.
...remember that your observe method will be
called for every http request made by firefox, usually several dozen per page visit.
...And 3 more matches
Setting up an extension development environment - Archive of obsolete content
install firefox development extensions specifi
cally for this new developer user profile.
...as we are specifi
cally defining the user profile dev, if you don't have the dev profile already created, the profile selection window opens, where you can create it.
... in the following example, the described command starts a new instance of firefox, with a profile
called dev; even if an instance of firefox is already running.
...And 3 more matches
Promises - Archive of obsolete content
yield db.executetransaction(function* () { for (let node of nodes) // insert the node's data, using an automati
cally-cached, // pre-compiled statement, and parameter placeholders.
... yield db.close(); } }); promise wrappers and helpers the following are some example promise-based wrappers for common
callback-based asynchronous apis.
...rsion, loadgroup)); }, getinstallforfile: function getinstallforfile(url, mimetype) { return new promise(accept => this.addonmanager.getinstallforfile(url, accept, mimetype)); }, getallinstalls: function getallinstalls() { return new promise(accept => this.addonmanager.getallinstalls(accept)); }, _replacemethod: function replacemethod(method,
callback) { object.defineproperty(this, method, { enumerable: true, configurable: true, value: key => { return new promise(accept => this.addonmanager[method](key, addon => accept(
callback(addon)))); } }); }, }; for (let method of ["getaddonbyid", ...
...And 3 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
the following is an example of
calling the nsdraganddrop object.
... <button label="drag me" ondraggesture="nsdraganddrop.startdrag(event,buttonobserver);" /> the function startdrag will be
called when a drag starts on the button.
...if we wanted to handle the other cases also, we can
call the other functions, as in the following example: <description value="click and drag this text." ondraggesture="nsdraganddrop.startdrag(event,textobserver)" ondragover="nsdraganddrop.dragover(event,textobserver)" ondragexit="nsdraganddrop.dragexit(event,textobserver)" ondragdrop="nsdraganddrop.drop(event,textobserver)" /> as mentioned earlier, there is nothing special that happens during a dragenter event, so you can just write that yourself.
...And 3 more matches
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
this library provides the interfaces necessary to bootstrap mozilla and
call xpcom methods.
... if your code cannot find the gre and keeps throwing filenotfoundexceptions during the getgrepathwithproperties(...)
call, check whether you already registered the gre on your system: gre registration the initembedding method kicks off the embedding process, allowing the java application to work with xpcom and mozilla.
...in addition to retrieving and
calling methods on xpcom objects, javaxpcom allows the java application to pass java class objects to xpcom methods.
...And 3 more matches
Exception logging in JavaScript - Archive of obsolete content
as a result, if, for example, c++ code
called a javascript component, which threw an exception, that exception would be logged to the console before control was returned to the c++
caller.
...javascript code is sometimes designed to throw exceptions to report a result condition back to the c++
caller.
... all other errors are reported when the last javascript frame on the stack returns to a c++
caller without handling the exception.
...And 3 more matches
Block and Line Layout Cheat Sheet - Archive of obsolete content
nslinebox a block consists of lines and other blocks, stacked verti
cally.
...it may be set as a side-effect of
calling nsblockframe::shouldapplytopmargin(); once set, shouldapplytopmargin() uses it as a fast-path way to return whether the top margin should apply.
...in this case, the flag won't be set, so subsequent
calls to shouldapplytopmargin() will continue crawl the line list.) this flag is also set in the nsblockreflowstate constructor if brs_istopmarginroot is set; that is, if the frame being reflowed is a margin root by default.
...And 3 more matches
GRE - Archive of obsolete content
the framework for embedding mozilla technologies was at one point
called the gre (gecko runtime environment).
...this document describes how embedders should dynami
cally link to a gre.
...this prevents dynami
cally finding a compatible gre at runtime.
...And 3 more matches
Creating a Help Content Pack - Archive of obsolete content
original doc: http://www.mozilla.org/projects/help.../content_packs i hesitate to
call it "original", tho, because i've basi
cally rewritten the entire thing so that it's easier and faster to use to create help content.
...search automati
cally goes through all of the elements in the table of contents, index, and glossary, but you might wish to have search go through more sources of data.
... one possible source might be an online, dynami
cally-generated list of added content stored on your web site.
...And 3 more matches
JavaScript crypto - Archive of obsolete content
alse); document.addeventlistener("smartcard-remove", onsmartcardchange, false); } function deregister() { document.removeeventlistener("smartcard-insert", onsmartcardchange, false); document.removeeventlistener("smartcard-remove", onsmartcardchange, false); } document.body.onload = register; document.body.onunload = deregister; </script> with the above example, your web site will automati
cally reload anytime a smartcard is inserted or removed.
... this allows the page to automati
cally login and logout based on the presence of the smartcard.
... 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 certificate database) the public keys, wrapped encryption private key, and text string from the sc...
...And 3 more matches
Simple Storage - Archive of obsolete content
the jetpack.simple.storage object is automati
cally and periodi
cally flushed to disk.
...jetpacks can flush it manually, however, by
calling jetpack.storage.simple.sync().
... the object can also be forced to reload its data from disk by
calling jetpack.storage.simple.open(), although the data comes loaded automati
cally.
...And 3 more matches
Simple Storage - Archive of obsolete content
the jetpack.simple.storage object is automati
cally and periodi
cally flushed to disk.
...jetpacks can flush it manually, however, by
calling jetpack.storage.simple.sync().
... the object can also be forced to reload its data from disk by
calling jetpack.storage.simple.open(), although the data comes loaded automati
cally.
...And 3 more matches
Monitoring downloads - Archive of obsolete content
the download manager instance is cached into a member variable in the downloadlogger object for reuse later, and its addlistener() method is
called to start listening for download status updates.
... handling download state changes once the code above is run, our ondownloadstatechange() method is
called whenever a download's state changes.
... if the download's state indicates that the download is finished, canceled, or failed, we
call our logtransfercompleted routine to update the log to indicate that state change.
...And 3 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
we provide an xml-based language
called xul for defining the user interface of your application.
...gecko is the first browser engine ever to deliver the full web standards support that developers have been
calling for.
...this will dramati
cally reduce the cost and complexity of developing and distributing rich web applications and full-functionality browsing devices that run them.
...And 3 more matches
The new nsString class implementation (1999) - Archive of obsolete content
i won't repeat it's interface here since it is basi
cally a restatement (in xpcom terms) of the nsstring interface.
... nsstring use these lo
cally in objects who span of control is known to live within your own process.
... these should typi
cally not be exposed to objects in other modules.
...And 3 more matches
Using Breakpoints in Venkman - Archive of obsolete content
the first, and most common, is
called the "hard" breakpoint.
...when a script is loaded that matches the url of a future breakpoint, and has executable code at the specified line, venkman will automati
cally set a future breakpoint.
... early return from
caller with result will cause the function that the breakpoint is set in to return the value of the breakpoint script as its result, immediatley after the breakpoint script completes.
...And 3 more matches
Binding Attachment and Detachment - Archive of obsolete content
the inheritance link has been forged dynami
cally through the invocation of the element.style.mozbinding.
... <constructor>
call as a document is loaded and style rules are matched for elements, any binding documents that are encountered will load as needed.
... <destructor>
call bindings attached through css are detached when any of the following conditions are met: a bound element matches a style rule that specifies a different binding the element is removed from the bound document the element is destroyed (e.g., by closing the document) bindings attached through the dom are detached when the following conditions are met: mozbinding style rule is removed the...
...And 3 more matches
Binding Implementations - Archive of obsolete content
these functions are
called getters and setters in xbl.
... for example, given a binding with an implementation colorpickergrid that derives from an implementation colorpicker where the two implementations both specify the setcolor method, a
caller could invoke colorpicker's method with the following syntax: ...
... // myelement is a colorpickergrid myelement.colorpicker.setcolor(); //
calls the colorpicker method.
...And 3 more matches
Elements - Archive of obsolete content
constructor the code inside the constructor is
called when a binding has just been attached to an element.
... note: prior to firefox 3, the constructor could be
called at a time when reflow of the document layout was locked down, so that attempting to get layout information from within the constructor could return out of date information.
... in firefox 3 and later, the constructor is
called when reflow can take place, which results in up-to-date information being returned.
...And 3 more matches
A XUL Bestiary - Archive of obsolete content
in other words, a chrome url like the global pointer above picks up a file
called global.css, and the help pointer above could also be written as chrome://help/content, because the name of the package itself is "help." viewing chromes other than mozilla's there is a special flag you can use to start mozilla with some chrome other than the default.
...each package directory typi
cally has three subdirectories, content, skin, and locale, in which the xul, css, and localization information are defined, respectively: navigator/ content/ default/ navigator.xul ...
...though this is not yet in the browser, very soon it will be possible to change the look of a whole application dynami
cally, but only to the extent that the skin is actually defined in the main global.css, or global skin.
...And 3 more matches
Introduction to XUL - Archive of obsolete content
widgets will generally live grouped in separate, dynami
cally loaded libraries.
...the task of writing a xul window description is basi
cally the same as the task of writing an html content description, with these exceptions: the syntax is xml (not that different from html 4), and there are some elements unique to xul.
... xulelement also supports other methods for hooking up broadcasters; a function performed automati
cally by the xul document loader and therefore not normally used in javascript.
...And 3 more matches
ContextMenus - Archive of obsolete content
<hbox id="container" align="center" oncontextmenu="..."> <label value="name:"/> <textbox id="name"/> </hbox> in this example, an attempt to open a context menu anywhere inside the hbox will
call the event listener attached using the oncontextmenu attribute.
...this might be
called while initializing a window during a load event for example.
...typi
cally, this will cause the menuitem's label to appear in the context menu in bold.
...And 3 more matches
Rule Compilation - Archive of obsolete content
for instance, if generating the items in a listbox, you will typi
cally use only one rule.
...thus, changing the rule elements around dynami
cally doesn't affect anything.
...
calling a dom api which needs to get at the generated content will cause the template builder to generate output.
...And 3 more matches
Element Positioning - Archive of obsolete content
box element positioning so far, we know how to position elements either horizontally or verti
cally inside a box.
...re
call that flexible elements grow and shrink to fit the available space.
...for verti
cally oriented boxes, it controls the vertical positioning of the children.
...And 3 more matches
Modifying a XUL Interface - Archive of obsolete content
addbutton() the
calls the createelement() function to create a new button.
... finally the appendchild() function of the particular box found by getelementbyid() is
called to add the button to it.
...since a node may only be in one place at a time, the insertion
call will always remove the node from its existing location first.
...And 3 more matches
XUL Questions and Answers - Archive of obsolete content
as an extension author, you have at least two options: use dom methods to dynami
cally create or rearrange elements file an enhancement request in bugzilla to have extra ids added.
...some of them can be tied to a preference so that the preference is automati
cally updated as the control is manipulated.
... specifying window.onload function to specify a function to run when the window is loaded,add the following code between the script tags in the xul file: window.addeventlistener("load", function(e) { startup(); }, false); similarly, for onunload use the code: window.addeventlistener("unload", function(e) { shutdown(); }, false); is there an event which is
called when the firefox browser is initialized?
...And 3 more matches
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
so basi
cally, almost everyone should be able to skip the next section.
...in this case you can basi
cally copy over the file as is, since once again variables are used for things like the application name and version.
...chrome will be packaged automati
cally by the build system, so you also need to specify which files get put into which packages by using jar manifests.
...And 3 more matches
NPP_Write - Archive of obsolete content
if the return value is smaller than the size of the buffer, the browser sends the remaining data to the plug-in through subsequent
calls to npp_writeready and npp_write.
...the browser will destroy the stream by
calling npp_destroystream.
... description the browser
calls the npp_write function to deliver the data specified in a previous npp_writeready
call to the plug-in.
...And 3 more matches
Encryption and Decryption - Archive of obsolete content
a cryptographic algorithm, also
called a cipher, is a mathematical function used for encryption or decryption.
... with most modern cryptography, the ability to keep encrypted information secret is based not on the cryptographic algorithm, which is widely known, but on a number
called a key that must be used with the algorithm to produce an encrypted result or to decrypt previously encrypted information.
... public-key encryption (also
called asymmetric encryption) involves a pair of keys-a public key and a private key-associated with an entity that needs to authenticate its identity electroni
cally or to sign or encrypt data.
...And 3 more matches
Using SSH to connect to CVS - Archive of obsolete content
setting up cvs to use ssh in your system's environment, make sure thatcvs_rsh is set to whatever your ssh binary is
called; a full path is not necessary if ssh is already in your path.
... if you are behind a firewall with an http tunneling proxy, you can use a program
called corkscrew, in combination with the proxycommand ssh config directive to continue to access the mozilla cvs server.
... this technique was taken from eric engstrom's site, but the instructions have been re-written specifi
cally for mozilla.
...And 3 more matches
Array.unobserve() - Archive of obsolete content
syntax array.unobserve(arr,
callback) parameters arr the array to stop observing.
...
callback the reference to the observer to stop
calling each time changes are made on the array arr.
... description array.unobserve() should be
called after array.observe() in order to remove an observer from an array.
...And 3 more matches
Object.prototype.__noSuchMethod__ - Archive of obsolete content
the __nosuchmethod__ property used to reference a function to be executed when a non-existent method is
called on an object, but this function is no longer available.
...} id the name of the non-existent method that was
called args an array of the arguments passed to the method description by default, an attempt to
call a method that doesn't exist on an object results in a typeerror being thrown.
...the function takes two arguments, the first is the name of the method attempted and the second is an array of the arguments that were passed in the method
call.
...And 3 more matches
Object.unobserve() - Archive of obsolete content
syntax object.unobserve(obj,
callback) parameters obj the object to stop observing.
...
callback the reference to the observer to stop
calling each time changes are made on the object obj.
... description object.unobserve() should be
called after object.observe() in order to remove an observer from an object.
...And 3 more matches
Object.prototype.watch() - Archive of obsolete content
handler a function to
call when the specified property's value changes.
... 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.
... in firefox, handler is only
called from assignments in script, not from native code.
...And 3 more matches
The Business Benefits of Web Standards - Archive of obsolete content
specifi
cally, presentation is defined using layout-oriented css language.
...typi
cally this reduces page size by 25 to 50%.
...while some browsers have quirks that cause different behavior by platform, mozilla-based browsers are designed to behave identi
cally on all supported platforms (mac, linux, unix, windows...) web content is increasingly being accessed by a growing number of user agents other than browsers, or by browsers on different platforms - for example mobile telephones.
...And 3 more matches
CSS FAQ - Learn web development
modern browsers have two main rendering modes: quirks mode: also
called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers.
... it is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semanti
cally unique): using classes makes your styling extensible — even if you only have one element to style with a particular ruleset now, you might want to add more later.
... style rules that are syntacti
cally correct may not apply in certain situations.
...And 3 more matches
How do I use GitHub Pages? - Learn web development
github has a very useful feature
called github pages, which allows you to publish website code live on the web.
...with the primary entry point being an html file
called index.html.
...to do this: point the command line to your test-site directory (or whatever you
called the directory containing your website).
...And 3 more matches
What is a Domain Name? - Learn web development
to solve all those problems we use human-readable addresses
called domain names.
... the label located right before the tld is also
called a secondary level domain (sld).
... companies
called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name.
...And 3 more matches
Sending form data - Learn web development
the only thing displayed to the user is the url
called.
... note: this example won't work when you load it into a browser lo
cally — browsers cannnot interpret php code, so when the form is submitted the browser will just offer to download the php file for you.
...sk(__name__) @app.route('/', methods=['get', 'post']) def form(): return render_template('form.html') @app.route('/hello', methods=['get', 'post']) def hello(): return render_template('greeting.html', say=request.form['say'], to=request.form['to']) if __name__ == "__main__": app.run() the two templates referenced in the above code are as follows (these need to be in a subdirectory
called templates in the same directory as the python-example.py file, if you try to run the example yourself): form.html: the same form as we saw above in the the post method section but with the action set to {{ url_for('hello') }}.
...And 3 more matches
Function return values - Learn web development
if you look at the replace() function mdn reference page, you'll see a section
called return value.
...our draw() function draws 100 random circles somewhere on an html <canvas>: function draw() { ctx.clearrect(0, 0, width, height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); } } inside each loop iteration, three
calls are made to the random() function, to generate a random value for the current circle's x-coordinate, y-coordinate, and radius, respectively.
... we are returning the result of the calculation math.floor(math.random() * number) each time the function is
called.
...And 3 more matches
Test your skills: Math - Learn web development
call the variables something sensible.
... multiply the results from the last two steps together, storing the result in a variable
called finalresult.
...store the result in a variable
called evenoddresult.
...And 3 more matches
Introduction to the server side - Learn web development
most large-scale websites use server-side code to dynami
cally display different data when needed, generally pulled out of a database stored on a server and sent to the client to be displayed via some code (e.g.
... dynamic sites a dynamic website is one where some of the response content is generated dynami
cally, only when needed.
... requests for static resources are handled in the same way as for static sites (static resources are any files that don't change —typi
cally: css, javascript, images, pre-created pdf files etc).
...And 3 more matches
TypeScript support in Svelte - Learn web development
for example, if you start adding an ms property to the alert component
call, typescript will infer from the default value that the ms property should be a number: and if you pass something that is not a number it will complain about it: the application template has a validate script configured that runs svelte-check against your code.
... now from todos.svelte, we will instantiate a todo component with a literal object as its parameter before the
call to the moreactions component, like this: <hr /> <todo todo={ { name: 'a new task with no id!', completed: false } } /> <!-- moreactions --> <moreactions {todos} add the lang='ts' to the <script> tag of the todos.svelte component, so that it knows to use the type checking we have specified.
...typescript will warn us about the todos prop and the t variable in the
call to todos.filter(t =>...).
...And 3 more matches
Vue conditional rendering: editing existing todos - Learn web development
in your components directory, create a new file
called todoitemeditform.vue.
...specifi
cally, we need to add a variable to track if the item is being edited, and a button to toggle that variable.
... we've also added "edit" and "delete" buttons: the "edit" button, when clicked, will toggle displaying the todoitemeditform component so we can use it to edit our todo item, via an event handler function
called toggletoitemeditform().
...And 3 more matches
Mozilla's Section 508 Compliance
part of section 508 (§1194.21) specifi
cally relates to mozilla, and the ability of us government agencies to buy software that contains mozilla software components.
...the focus shall be programmati
cally exposed so that assistive technology can track focus and focus changes.
...we expose focus programmati
cally via msaa (windows) and atk (linux/unix).
...And 3 more matches
Mozilla’s UAAG evaluation report
in the rare cases where it is, it is of no help (typi
cally it's just the filename, maybe with a file size).
...(p3) p we have no repair strategy in 2.7 we have no way to configure that alt="" still needs to be repaired 2.9 render conditional content automati
cally.
... out-of-process access is needed for it to be truly useful for assistive technology we do support some com interfaces
called isimpledomnode, which has a large portion of useful dom read access 6.2 dom write access.
...And 3 more matches
Listening to events on all tabs
adding a listener to listen to progress events on all tabs,
call the browser's addtabsprogresslistener() method: gbrowser.addtabsprogresslistener(myprogresslistener); myprogresslistener is an object that implements the
callbacks used to provide notifications of progress events.
... removing a listener to remove a previously installed progress listener,
call removetabsprogresslistener(): gbrowser.removetabsprogresslistener(myprogresslistener); implementing a listener the listener object itself has five methods it can implement to handle various events: onlocationchange
called when the uri of the document displayed in the tab changes.
...optional from gecko 10 onprogresschange
called when updated progress information for the download of a document is available.
...And 3 more matches
Message manager overview
in multiprocess firefox there are (at least) two processes: the chrome process, also
called the parent process, runs the browser ui (chrome) code and code inserted by extensions one or more content processes, also
called child processes.
...these scripts are
called frame scripts, and as the name suggests, they are scoped to a specific browser frame.
... frame message managers in multiprocess firefox, when chrome code needs to interact with web content, it needs to: factor the code that needs direct access to content into separate scripts, which are
called "frame scripts" use a frame message manager to load these frame scripts into the content process use the frame message manager api to communicate with the frame script some older articles on multiprocess firefox and the message manager might refer to "content scripts" instead of "frame scripts".
...And 3 more matches
Performance
rget result = helper(frameglobal.content, message.data) frameglobal.sendasyncmessage("my-addon:response-from-child", {something: result}) } function addframe(frameglobal) { frameglobal.addmessagelistener("my-addon:request-from-parent", dosomething) } javascript modules are per-process singletons and thus all their objects are only initialized once, which makes them suitable for stateless
callbacks.
...m 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 by other functions don't register observers (and other
callbacks to global services) in a frame script bad: //framescript.js services.obs.addobserver("document-element-inserted", { observe: function(doc, topic, data) { if(doc.ownerglobal.top != content) return; // bail out if this is for another tab decoratedocument(doc); } }) observer notifications get fired for events that happen anywhere in the browser, they are not scoped to ...
...if each framescript registers a seperate listener then the observed action will trigger the
callbacks in all tabs.
...And 3 more matches
Script security
because the wrapper we choose is specific to the relationship between the two compartments, the security policy it implements can be static: when the
caller uses the wrapper, there's no need to check who is making the
call or where it is going.
... when objects share an origin but not a global - for example two web pages from the same protocol, port, and domain - they belong to two different compartments, and the
caller gets a transparent wrapper to the target object.
... transparent wrappers allow access to all the target's properties: functionally, it's as if the target is in the
caller's compartment.
...And 3 more matches
Getting Started with Chat
for example, you can connect using ssl or a non-secure connection, and you can configure the client to automati
cally connect to a server and join a particular set of channels when you start the client.
...these users are known as bots and automati
cally perform certain tasks; some automatic, some triggered by other users.
... the most common of these bots are
called nickserv, chanserv, and firebot.
...And 3 more matches
Implementing QueryInterface
a reference implementation of queryinterface ns_imethodimp nsmyimplementation::queryinterface( refnsiid aiid, void** ainstanceptr ) { ns_assertion(ainstanceptr, "queryinterface requires a non-null destination!"); // it's a logic error, not a runtime error, to
call me without any place to put my answer!
... // ...but that won't matter when someone
calls me wrongly in a non-debug build.
...
calling an inherited queryinterface sometimes you are just adding one or two new interfaces to an implementation that already supports many other interfaces.
...And 3 more matches
AsyncShutdown.jsm
typi
cally, each shutdown phase removes some capabilities from the application.
...// collect any information that may be useful for debugging shutdown issues with this blocker return status; } }); in this example, at some point during phase profilebeforechange, function condition will be
called.
...in this case, a crash report is produced, with information on all the shutdown blockers that have not been resolved, and all the additional debug information returned by
calls to info().
...And 3 more matches
Http.jsm
method get, post or put (this is automati
cally set if postdata exists).
... onload a function handle to
call when the load is complete, it takes two parameters: the responsetext and the xhr object.
... onerror a function handle to
call when an error occurs, it takes three parameters: the error, the responsetext and the xhr object.
...And 3 more matches
QA phase
manual & automated builds with the click of a button, some l10n tools (like narro and koala) automati
cally create language pack builds for you.
... finally, you will need a file
called .mozconfig to proceed with manual builds.
... we use a web service
called bit bucket to start the learning process.
...And 3 more matches
JS::PerfMeasurement
it is a stopwatch profiler -- that is, it counts events that occur while code of interest is running; it does not do
call traces or sampling.
...perfmeasurement::all in a constructor
call, this special value means "measure everything that can possibly be measured." perfmeasurement::num_measurable_events this constant equals the total number of events defined by the api - not necessarily the total number of events that a particular os allows you to measure.
...void start()
call this on a perfmeasurement instance to start timing.
...And 3 more matches
A brief guide to Mozilla preferences
a preference is read from a file, and can
call up to four methods: pref(), user_pref(), sticky_pref() and lockpref().
... all preferences files may
call pref(), user_pref() and sticky_pref(), while the config file in addition may
call lockpref().
...file a configuration file, usually with .cfg extension, may be
called from a default pref file via the general.config.filename preference.
...And 3 more matches
I/O Functions
nspr converts the slashes in a pathname to the directory separator of the native os--for example, backslash (\) on windows and colon (:) on mac os--before passing it to the native system
calls.
... two new functions, pr_transmitfile and pr_acceptread, can exploit the new system
calls of some operating systems for higher performance.
... the purpose of a pollable event is to combine event waiting with i/o waiting in a single pr_poll
call.
...And 3 more matches
PR_PushIOLayer
some subtle ramifications: the ownership of the storage pointed to by the
caller's layer argument is relinquished to the runtime.
...the correct mechanism to access the object is to get a pointer to it by
calling pr_getidentitieslayer.
... the contents of the
caller's object are swapped into another container, including the reference to the object's destructor.
...And 3 more matches
JSS Provider Notes
at runtime, the jre automati
cally verifies this signature whenever a jss class is loaded that implements a jce algorithm.
... installing the provider in order to use any part of jss, including the jca provider, you must first
call cryptomanager.initialize().
...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.
...And 3 more matches
Mozilla-JSS JCA Provider notes
at runtime, the jre automati
cally verifies this signature whenever a jss class is loaded that implements a jce algorithm.
... installing the provider in order to use any part of jss, including the jca provider, you must first
call cryptomanager.initialize().
...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.
...And 3 more matches
nss tech note6
the new checksum file is
called libsoftokn3.chk on unix/linux and softokn3.chk on windows.
... on 32-bit windows and 32-bit os/2, this shared library is
called freebl3.dll, and the corresponding .chk file is
called freebl3.chk .
... on 32-bit solaris x86, 64-bit solaris x64 (amd64), 32-bit linux x86, 64-bit linux x86-64, 32-bit aix and 64-bit aix, this shared library is
called libfreebl3.so, and the corresponding .chk file is
called libfreebl3.chk .
...And 3 more matches
nss tech note8
as originally designed, before
calling the cache function, the
caller was responsible to fill in the session creation time (which might not be the same as the time of insertion into the cache) and the session expiration time, among other things.
...steps, whether for client or for server: for ssl2: sid->lastaccesstime = sid->creationtime = ssl_time(); sid->expirationtime = sid->creationtime + ssl_sid_timeout; (*ss->sec.cache)(sid); for ssl3: sid->lastaccesstime = sid->creationtime = ssl_time(); sid->expirationtime = sid->creationtime + ssl3_sid_timeout; (*ss->sec.cache)(sid); the cache api was defined such that the
caller must set creationtime properly, and may set expirationtime to the desired value or to zero.
... if zero, then the
called cache function would compute the correct expiration time by adding the chosen timeout (from one of those two global variables) to the sid's creationtime, giving the expirationtime.
...And 3 more matches
NSPR functions
nspr initialization and shutdown nspr is automati
cally initialized by the first nspr function
called by the application.
...
call pr_cleanup to shut down nspr and clean up its resources.
...
call pr_geterror to get the error code of the last failed nss or nspr function.
...And 3 more matches
NSS tools : certutil
it can specifi
cally 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.
... · oid (example): 1.2.3.4 · critical-flag: critical or not-critical · filename: full path to a file containing an encoded extension -f password-file specify a file that will automati
cally supply the password to include in a certificate or to access a certificate database.
...when this argument is used, the default three-month period is automati
cally added to any value given in the valid-month argument.
...And 3 more matches
certutil
-f password-file specify a file that will automati
cally supply the password to include in a certificate or to access a certificate database.
...unless specified otherwise the default token is an internal slot (specifi
cally, internal slot 2).
...when this argument is used, the default three-month period is automati
cally added to any value given in the valid-month argument.
...And 3 more matches
Necko Architecture
necko has been designed to accommodate pluggable protocols so developers can contribute their own protocol libraries that can be dynami
cally loaded and used by applications utilizing necko.
...uris (re
call that a url is just one implementation of a uri) can be created as individual components independently of necko, or they can be retrieved via the nsiioservice interface.
...if you want to move data asynchronously you need to be able to receive
callbacks using an implementation of nsistreamlistener.
...And 3 more matches
64-bit Compatibility
builtins and
calls when passing arguments to lirwriter::ins
call(), there are four types: argsize_f - floating point value argsize_i - 32-bit integer argsize_q - 64-bit integer argsize_p - 32-bit integer on 32-bit platforms, 64-bit integer on 64-bit platforms.
...luckily there is an alias that will choose the right opcode for you - lir_ldp: struct object { void *data; }; lir->insload(lir_ldp, objins, ins->insimm(offsetof(object, data))); when you use lirwriter::insstore, the correct size is chosen for you automati
cally, based on the size of the input operands.
...to help form well-typed lir, there is a special opcode
called lir_float which specifies that the associated constant value is definitely floating-point.
...And 3 more matches
JS::Add*Root
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...that could cause sporadic crashes during garbage collection, which can be hard to debug.) the variable must remain in memory until the balancing
call to js::remove*root.
...if the variable points to an object, then any memory reachable from its properties is automati
cally protected from garbage collection, too.
...And 3 more matches
JS_ForgetLocalRoot
syntax void js_forgetlocalroot(jscontext *cx, void *thing); name type description cx jscontext * pointer to the context in which the
caller is running.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...in case a native hook allocates many objects or other gc-things, but the native protects some of those gc-things by storing them as property values in an object that is itself protected, the hook can
call js_forgetlocalroot to free the local root automati
cally pushed for the now-protected gc-thing.
...And 3 more matches
JS_GetProperty
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...then the jsclass.getproperty hook of obj's class is
called with the arguments (cx, obj, id, vp).
... if the property is found on a non-native object, get handler of proxy (only if the object is a proxy) or its jsobjectops.getproperty method is
called.
...And 3 more matches
JS_PushArguments
cx also affects the interpretation of format, if js_addargumentformatter has been
called.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
... description js_pusharguments provides a convenient way to translate a series of native c/c++ values to jsvals with a single function
call.
...And 3 more matches
JS_SET_TRACING_DETAILS
printer jstracenameprinter a
callback function, described below; or null.
...
callback syntax typedef void (*jstracenameprinter)(jstracer *trc, char *buf, size_t bufsize); name type description trc jstracer * the tracer.
...the
callback stores a string describing the reference traced in buf.
...And 3 more matches
JS_SetObjectPrincipalsFinder
set the runtime-wide object-principals-finder
callback.
...in spidermonkey 1.8.1 or later, use js_setruntimesecurity
callbacks instead.
... fop jsobjectprincipalsfinder the new object-principals-finder
callback.
...And 3 more matches
SpiderMonkey 38
many jsapi types, functions, and
callback signatures have changed, though most functions that have changed still have the same names and implement essentially unchanged functionality.
... js::clonefunctionobject (bug 1088228) interned_string_to_jsid (bug 1045900) js::construct (bug 1017109) js::createerror (bug 984048) js::falsehandlevalue (bug 959787) js::handlesymbol (bug 645416) js::identifystandardconstructor (bug 976148) js::is
callable (bug 1065811) js::isconstructor (bug 1065811) js::mutablehandlesymbol (bug 645416) js::ordinarytoprimitive (bug 1103152) js::propertyspecnameequalsid (bug 1082672) js::propertyspecnameissymbol (bug 1082672) js::propertyspecnametopermanentid (bug 1082672) js::protokeytoid (bug 987669) js::rootedsymbol (bug 645416) js::truehandlevalue (bug 959787) jsconstintegerspec (bug 1066020) jsi...
...d_is_symbol (bug 645416) jsid_to_symbol (bug 645416) jsprop_define_late (bug 825199) jsprop_ignore_enumerate (bug 1037770) jsprop_ignore_permanent (bug 1037770) jsprop_ignore_readonly (bug 1037770) jsprop_ignore_value (bug 1037770) jsprop_propop_accessors (bug 1088002) jsprop_redefine_nonconfigurable (bug 1101123) js_addfinalize
callback (bug 996785) js_defineconstintegers (bug 1066020) js_getflatstringcharat (bug 1034627) js_getfunctionscript (bug 1069694) js_getlatin1flatstringchars (bug 1037869) js_getlatin1internedstringchars (bug 1037869) js_getlatin1stringcharsandlength (bug 1032726) js_getstringcharat (bug 1034627) js_gettwobyteexternalstringchars (bug 1034627) js_gettwobyteflatstringchars (bug 1037869) js_gettwobyteinternedstringchars (bug 1037869) js_gettwobytestrin...
...And 3 more matches
Mozilla Projects
mozilla
calls mccoy a "simple system" which is a clear sign that something probably is not working, and indeed, is not.
...applications periodi
cally look for and install updates to their add-ons.
...specifi
cally, it focuses on the process of digitally signing update manifests so the applications can verify the integrity of a manifest retrieved over normally insecure channels.
...And 3 more matches
The Publicity Stream API
publicizeactivity( <activity>, [ { [ onsuccess: <function> ], [ onerror: <function> ] } ]): applications should
call this method when an user-initiated activity deemed attractive to potential consumers occurs.
... onsuccess is a
callback that will be invoked with no arguments if the activity is successfully posted.
... onerror is an error
callback that will be invoked if the publicity fails.
...And 3 more matches
Fun With XBL and XPConnect
once the regular xul textfield widget is bound to this interface, it
calls the auto complete function of the object using regular javascript.
... getservice(components.interfaces.nsiautocompletesession); ]]> </property> so we've defined a property on the widget
called autocompletesession.
...all you have to do is specifi
cally defining a method on the xbl widget which forwards the method
call to the xpcom object.
...And 3 more matches
Packaging WebLock
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.
...the files themselves are stored in the jar file weblock.jar, which is simple a zip file with the xpi extension that sometimes also contains an internal installation file
called install.js.
... archiving resources once you have compiled all the resources that make up the weblock component and the files that make up the user interface that will be added to the browser, you can place these within a subdirectory
called weblock.
...And 3 more matches
Components.lastResult
components.lastresult returns the numeric nsresult code that was the result code of the last xpcom method
called via xpconnect.
...this is because failure result codes get converted by xpconnect into exceptions that are thrown into the
calling javascript method.
... in cases where components.lastresult is used, it is best to get it right away after the target
call is made and save it in a local variable to test its value rather than doing multiple tests against components.lastresult.
...And 3 more matches
NS_InitXPCOM2
« xpcom api reference summary the ns_initxpcom2 function initiates use of xpcom in the
calling process.
...the service manager may alternatively be accessed by
calling ns_getservicemanager.
...some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is
called before xpcom's static initialization code executes.
...And 3 more matches
IAccessibleText
typi
cally this feature would not be implemented by an application.
...three" object would be 4, matching the embed character</li> the caretoffset for "two" would be 2, matching the "o" the caret position/offset is that of the character logi
cally following it, for example to the right of it in a left to right language.
...it represents the current input position and will therefore typi
cally be queried by at more often than other positions.
...And 3 more matches
imgIContainer
flag_sync_decode: forces synchronous/non-progressive decode of all available data before the
call returns.
... it is an error to pass this flag from a
call stack that originates in a decoder (that is, from a decoder observer event).
...otherwise, the image will be automati
cally tiled as necessary.
...And 3 more matches
nsIAlertsService
note: if you are
calling this function from javascript, you should wrap it in a try/catch because it can fail on mac os x prior to firefox 22.
... cookie optional a blind cookie the alert passes back to the consumer during alert listener
callbacks.
... alertlistener optional an object to receive
callbacks from the alert; may be null if you don't care about
callbacks.
...And 3 more matches
nsIAnnotationObserver
pports last changed in gecko 1.9 (firefox 3) method overview void onitemannotationremoved(in long long aitemid, in autf8string aname); void onitemannotationset(in long long aitemid, in autf8string aname); void onpageannotationremoved(in nsiuri auri, in autf8string aname); void onpageannotationset(in nsiuri apage, in autf8string aname); methods onitemannotationremoved() this method is
called when an annotation is deleted for an item.
...this is not
called when annotations are expired (normally happens when the application exits).
... onitemannotationset() this method is
called when an annotation value is set for an item.
...And 3 more matches
nsIAuthModule
methods getnexttoken() this method is
called to get the next token in a sequence of authentication steps.
...the buffer at aouttoken must be recycled with a
call to nsimemory.free().
... init() this method is
called to initialize an auth module.
...And 3 more matches
nsIClipboardDragDropHooks
if more than one implementation is set for a window, the hooks will be
called in the order they are added.
... adding the same hook to the same window will not add a second
call.
... each hook can only be
called once per user action/api.
...And 3 more matches
nsIDOMParser
to create a domparser when the constructor is not available (e.g., from a js xpcom component, a js module, or an xpcshell test), use: var parser = components.classes["@mozilla.org/xmlextras/domparser;1"] .createinstance(components.interfaces.nsidomparser); // optionally,
call parser.init(principal, documenturi, baseuri); principals, document and base uri note: this section covers changes introduced to domparser in gecko 1.9.
...these values are automati
cally determined as defined below, but if you work with domparser from privileged code, you can override the defaults by providing arguments to the domparser constructor or
calling parser.init().
... 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.
...And 3 more matches
nsIHttpServer
(not supported) * @param function
callback optional
callback */ listen: function(port, opt,
callback) { if (arguments.length == 2 && "function" == typeof opt) {
callback = opt; } if (
callback) { this.registerprefixhandler("/",
callback); } let host = "localhost"; if (typeof port === "string" && port.indexof(':')...
...h, file); }, registerdirectory : function(path, directorypath) { var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(directorypath); return server.registerdirectory(path, file); }, registerpathhandler: function(path, handler
callback) { server.registerpathhandler(path, function (request, response) { var req = createhttprequest(request); var resp = new httpresponse(response); handler
callback(req, resp); }); }, registerprefixhandler: function(prefix, handler
callback) { server.registerprefixhandler(prefix, functio...
...n (request, response) { var req = createhttprequest(request); var resp = new httpresponse(response); handler
callback(req, resp); }); }, close: function(){ server.stop(function(){}); }, get port() { return server.identity.primaryport } } } reference : mozilla-release/netwerk/test/httpserver/nsihttpserver.idl [scriptable, uuid(cea8812e-faa6-4013-9396-f9936cbb74ec)] interface nsihttpserver : nsisupports { /** * starts up this server, listening upon the given port.
...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); ...
...must be
called before using other interfaces.
...if the user consents, modifylogin() will be
called.
...And 3 more matches
nsILoginManagerStorage
methods addlogin()
called by the login manager to store a new login.
...this method is
called, for example, to check to see if there is a login that will match the criteria without having to ask the user for their master password in order to decrypt the logins.
...this method is
called by the login manager when looking for saved logins that might apply to a form or authentication request.
...And 3 more matches
nsINavBookmarkObserver
it is
called before the actual removal takes place.
...other notifications will be sent during the batch change, but the observer is guaranteed that onendupdatebatch() will be
called at the completion of changes.
...this will be
called whenever any attributes like "title" are changed.
...And 3 more matches
nsIPrefService
inherits from: nsisupports last changed in gecko 1.7 method overview nsiprefbranch getbranch(in string aprefroot); nsiprefbranch getdefaultbranch(in string aprefroot); void readuserprefs(in nsifile afile); void resetprefs(); void resetuserprefs(); void savepreffile(in nsifile afile); methods getbranch()
call to get a preferences "branch" which accesses user preference data.
... getdefaultbranch()
call to get a preferences branch which accesses only the default preference data.
... readuserprefs()
called to read in the preferences specified in a user preference file.
...And 3 more matches
nsISHistory
shistoryenumerator nsisimpleenumerator
called to obtain a enumerator for all the documents stored in session history.
... to access individual history entries of the enumerator, perform the following steps:
call getshistoryenumerator() to obtain handle the nsisimpleenumerator object.
... methods addshistorylistener()
called to register a listener for the session history component.
...And 3 more matches
nsISpeculativeConnect
1.0 66 introduced gecko 15.0 inherits from: nsisupports last changed in gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) to use this service, simply
call nsisupports.queryinterface() on the nsiioservice you plan to use for the connection, to get access to the i/o service's implementation of nsispeculativeconnect.
... then
call speculativeconnect() to let the networking layer know what you might be doing in the future.
... method overview void speculativeconnect(in nsiuri auri, in nsiinterfacerequestor a
callbacks, 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.
...And 3 more matches
nsIStringEnumerator
inherits from: nsisupports last changed in gecko 1.7 method overview astring getnext(); boolean hasmore(); methods getnext()
called to retrieve the next string in the enumerator.
... the "next" element is the first string upon the first
call.
... must be preceded by a
call to hasmoreelements() which returns pr_true.
...And 3 more matches
nsITreeBoxObject
it is dynami
cally settable, either using a view attribute on the tree tag or by setting this attribute to a new value.
...the view is responsible for
calling this notification method when rows are added or removed.
... for non-contiguous additions/removals, this method should be
called multiple times.
...And 3 more matches
nsIWebBrowserPersist
progresslistener nsiwebprogresslistener
callback listener for progress notifications.
... persist_flags_cleanup_on_failure 8192 automati
cally cleanup after a failed or cancelled operation, deleting all created files and directories.
...the
caller is responsible for cleaning up partially written files or directories.
...And 3 more matches
Setting HTTP request headers
http channels when you deal with http requests and responses, typi
cally you are doing this with an nsihttpchannel.
...and once the observer is registered for a topic, it will get notified about the topic by having its observe method
called.
...so we need to change the nsisupports into a nsihttpchannel which is what the queryinterface
call does.
...And 3 more matches
Working with Multiple Versions of Interfaces
what happens is that the
call to do_createinstance fails with nsresult ns_error_no_interface.
... this is because the
call to do_createinstance(acid, aouter, error); will eventually evolve into a request for an object supporting the interface with iid ns_get_iid(nsiaccessibleretrieval).
...all the xpcom
calls succeed, or at least think they succeed.
...And 3 more matches
Mail and RDF
information for this column is queried when the tree's rdf template
calls the folder datasource's gettarget() method.
...this is basi
cally what happens, behind the scenes: var target = rdf.getresource("mailbox://alecf@pop.myisp.com/inbox"); var property = rdf.getresource("http://home.netscape.com/nc-rdf#totalmessages"); var resultnode = datasource.gettarget(target, property, true); in the folder datasource's gettarget(), target would be queryinterfaced to a nsimsgfolder.
... to get the total messages, the datasource would then
call nsimsgfolder.gettotalmessages().
...And 3 more matches
Using popup notifications
in addition, notifications can be dismissed and re
called by clicking anywhere outside the notification, then clicking on the notification icon to bring it back again.
... then you can create the popup notification at the appropriate time like this: popupnotifications.show(gbrowser.selectedbrowser, "sample-popup", "this is a sample popup notification.", null, /* anchor id */ { label: "do something", accesskey: "d",
callback: function() { alert("doing something awesome!"); } }, null /* secondary action */ ); in this case, we aren't providing any secondary actions; that is, actions provided to the user through the drop-down menu.
...you can use this to style the icon, like this: .popup-notification-icon[popupid="sample-popup"] { list-style-image: url("chrome://popupnotifications/skin/mozlogo.png"); } with this css in place, the result is the look we want: adding secondary options to provide options in the drop-down menu, add an array of notification actions to the
call to the show() method, like this: popupnotifications.show(gbrowser.selectedbrowser, "sample-popup", "this is a sample popup notification.", null, /* anchor id */ { label: "do something", accesskey: "d",
callback: function() { alert("doing something awesome!"); } }, [ { label: "first s...
...And 3 more matches
AbstractRange - Web APIs
specifi
cally, as the node tree mutates and changes, the range does not.
... to illustrate this, consider the html below: <div class="container"> <div class="header"> <img src="" class="sitelogo"> <h1>the ultimate website</h1> </div> <article> <section class="entry" id="entry1"> <h2>section 1: an interesting thing...</h2> <p>a <em>very</em> interesting thing happened on the way to the forum...</p> <aside class="
callout"> <h2>aside</h2> <p>an interesting aside to share with you...</p> </aside> </section> </article> <pre id="log"></pre> </div> after loading the html and constructing the dom representation of the document, the resulting dom tree looks like this: in this diagram, the nodes representing html elements are shown in green.
...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.
...And 3 more matches
Cache.match() - Web APIs
note: cache.match() is basi
cally identical to cache.matchall(), except that rather than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]).
...a catch() clause is triggered when the
call to fetch() throws an exception.
...if there are any other fetch handlers registered, they will get a chance to
call event.respondwith().
...And 3 more matches
Basic usage of canvas - Web APIs
for example, we could provide a text description of the canvas content or provide a static image of the dynami
cally rendered content.
...the <canvas> element has a method
called getcontext(), used to obtain the rendering context and its drawing functions.
... var canvas = document.getelementbyid('tutorial'); var ctx = canvas.getcontext('2d'); the first line in the script retrieves the node in the dom representing the <canvas> element by
calling the document.getelementbyid() method.
...And 3 more matches
Document.write() - Web APIs
note: because document.write() writes to the document stream,
calling document.write() on a closed (loaded) document automati
cally
calls document.open(), which will clear the document.
... writing to a document that has already loaded without
calling document.open() will automati
cally
call document.open().
... after writing,
call document.close() to tell the browser to finish loading the page.
...And 3 more matches
Event - Web APIs
it can also be triggered programmati
cally, such as by
calling the htmlelement.click() method of an element, or by defining the event, then sending it to a specified target using eventtarget.dispatchevent().
...(for example, a webpage with an advertising-module and statistics-module both monitoring video-watching.) when there are many nested elements, each with its own handler(s), event processing can become very complicated—especially where a parent element receives the very same event as its child elements because "spatially" they overlap so the event techni
cally occurs in both, and the processing order of such events depends on the event bubbling and capture settings of each handler triggered.
...equestupdateevent pointerevent popstateevent progressevent relatedevent rtcdatachannelevent rtcidentityerrorevent rtcidentityevent rtcpeerconnectioniceevent sensorevent storageevent svgevent svgzoomevent timeevent touchevent trackevent transitionevent uievent userproximityevent webglcontextevent wheelevent constructor event() creates an event object, returning it to the
caller.
...And 3 more matches
Using Fetch - Web APIs
gin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: json.stringify(data) // body data type must match "content-type" header }); return response.json(); // parses json response into native javascript objects } postdata('https://example.com/answer', { answer: 42 }) .then(data => { console.log(data); // json data parsed by `data.json()`
call }); note that mode: "no-cors" only allows a limited set of headers in the request: accept accept-language content-language content-type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain sending a request with credentials included to cause browsers to send a request with credentials included, even for a cross-origin
call, add credentials: 'include' ...
... fetch('https://example.com', { credentials: 'include' }); if you only want to send credentials if the request url is on the same origin as the
calling script, add credentials: 'same-origin'.
... // the
calling script is on the origin 'https://example.com' fetch('https://example.com', { credentials: 'same-origin' }); to instead ensure browsers don’t include credentials in the request, use credentials: 'omit'.
...And 3 more matches
FileSystemFileEntry.createWriter() - Web APIs
syntax filesystemfileentry.createwriter(success
callback[, error
callback]); parameters success
callback a
callback function which is
called when the filewriter has been created successfully; the filewriter is passed into the
callback as the only parameter.
... error
callback optional if provided, this must be a method which is caled when an error occurs while trying to create the filewriter.
... this
callback receives as input a fileerror object describing the error.
...And 3 more matches
FileSystemFileEntry - Web APIs
basic concepts to write content to file, create a filewriter object by
calling createwriter().
... to read a file, obtain a file object representing its contents by
calling file().
... example the following code creates an empty file
called "log.txt" (if it doesn't exist) and fills it with the text "meow".
...And 3 more matches
FileHandle API - Web APIs
because the files manipulated through that api can be physi
cally stored on the device, the editing part uses a turn-based locking mechanism in order to avoid race issues.
... api overview this api is based on the following interfaces: idbdatabase.mozcreatefilehandle (was
called idbdatabase.mozcreatefilehandle.) idbmutablefile (was previously filehandle.) lockedfile filerequest it also has connections with the file api, especially the file and blob interfaces.
...such an object is basi
cally a domrequest with an extra power: it allows to monitor the progress of an operation.
...And 3 more matches
Geolocation API - Web APIs
the geolocation api is accessed via a
call to navigator.geolocation; this will cause the user's browser to ask them for permission to access their location data.
... geolocation.watchposition(): registers a handler function that will be
called automati
cally each time the position of the device changes, returning the updated location.
... in both cases, the method
call takes up to three arguments: a mandatory success
callback: if the location retrieval is successful, the
callback executes with a geolocationposition object as its only parameter, providing access to the location data.
...And 3 more matches
HTMLCanvasElement - Web APIs
htmlcanvaselement.mozprint
callback is a function that is initially null.
... web content can set this to a javascript function that will be
called when the canvas is to be redrawn while the page is being printed.
... when
called, the
callback is passed a "printstate" object that implements the mozcanvasprintstate interface.
...And 3 more matches
Basic concepts - Web APIs
the api doesn't give you data by returning values; instead, you have to pass a
callback function.
...they have onsuccess and onerror properties, and you can
call addeventlistener() and removeeventlistener() on them.
... database database a repository of information, typi
cally comprising one or more object stores.
...And 3 more matches
Browser storage limits and eviction criteria - Web APIs
note: the information below should be fairly accurate for most modern browsers, but browser specifics are
called out where known.
...basi
cally, the persistent folder was renamed to permanent a while ago to keep upgrades/migration simpler.
...in firefox, an internal browser tool
called the quota manager keeps track of how much disk space each origin is using up, and deletes data if necessary.
...And 3 more matches
MutationObserver.takeRecords() - Web APIs
the mutationobserver method takerecords() returns a list of all matching dom changes that have been detected but not yet processed by the observer's
callback function, leaving the mutation queue empty.
... note: the queue of mutations which have occurred, but not been delivered to the observer's
callback is left empty after
calling takerecords().
... example in this example, we demonstrate how to handle any undelivered mutationrecords by
calling takerecords() just before disconnecting the observer.
...And 3 more matches
PaymentResponse.retry() - Web APIs
typi
cally you will use this by
calling show(), then entering a loop or recursive function that checks the paymentresponse for errors or other reasons to retry the payment request.
... if a retry is needed, the loop
calls retry(), then loops back to check the response when it comes in.
... validate the returned reponse; if there are any fields whose values are not acceptable,
call the response's complete() method with a value of "fail" to indicate failure.
...And 3 more matches
Pointer Lock API - Web APIs
the pointer lock api (formerly
called mouse lock api) provides input methods based on the movement of the mouse over time (i.e., deltas), not just the absolute position of the mouse cursor in the viewport.
...pointer lock is different from mouse capture in the following ways: it is persistent: pointer lock does not release the mouse until an explicit api
call is made or the user uses a specific release gesture.
... document.exitpointerlock = document.exitpointerlock || document.mozexitpointerlock; // attempt to unlock document.exitpointerlock(); pointerlockchange event when the pointer lock state changes—for example, when
calling requestpointerlock(), exitpointerlock(), the user pressing the esc key, etc.—the pointerlockchange event is dispatched to the document.
...And 3 more matches
Pointer events - Web APIs
typi
cally, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media.
... function process_pressure(pressure) { // pressure handler } function process_non_primary(event) { // non primary handler } function down_handler(ev) { // calculate the touch point's contact area var area = ev.width * ev.height; // compare cached id with this event's id and process accordingly if (id == ev.identifier) process_id(ev); //
call the appropriate pointer type handler switch (ev.pointertype) { case "mouse": process_mouse(ev); break; case "pen": process_pen(ev); break; case "touch": process_touch(ev); break; default: console.log("pointertype " + ev.pointertype + " is not suported"); } //
call the tilt hand...
...ler if (ev.tiltx != 0 && ev.tilty != 0) process_tilt(ev.tiltx, ev.tilty); //
call the pressure handler process_pressure(ev.pressure); // if this event is not primary,
call the non primary handler if (!ev.isprimary) process_non_primary(ev); } function init() { var el=document.getelementbyid("target"); // register pointerdown handler el.onpointerdown = down_handler; } </script> <body onload="init();"> <div id="target"> touch me ...
...And 3 more matches
RTCConfiguration.certificates - Web APIs
if this property isn't specified, the browser will automati
cally generate and use a certificate to secure the connection.
... description if this property isn't included in the configuration, a set of certificates is automati
cally generated for each instance of rtcpeerconnection.
... using certificates when you wish to provide your own certificates for use by an rtcpeerconnection instead of having the rtcpeerconnection generate them automati
cally, you do so by
calling the static rtcpeerconnection.generatecertificate() function.
...And 3 more matches
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
networkteststart() this function simply
calls the rtcpeerconnection method getstats() to request an rtcstatsreport and store it in the variable startreport.
... let startreport; async function networkteststart(pc) { if (pc) { startreport = await pc.getstats(); } } given an rtcpeerconnection, pc, this
calls its getstats() method to obtain a statistics report object, which it stores in startreport for use once the end-of-test data has been collected by networkteststop().
...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.
...And 3 more matches
WebRTC API - Web APIs
rtcstatsreport provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by
calling rtcpeerconnection.getstats().
... 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().
... negotiationneeded informs the rtcpeerconnection that it needs to perform session negotiation by
calling createoffer() followed by setlocaldescription().
...And 3 more matches
WebXR application life cycle - Web APIs
call navigator.xr.issessionsupported(), specifying the webxr experience mode you want to provide: inline, immersive-vr, or immersive-ar, in order to determine whether or not the type of session you wish to provide is available.
...this is done by
calling navigator.xr.requestsession(), again specifying the string indicating the mode you want to enable: inline, immersive-vr, or immersive-ar.
...
call the xrsession method requestanimationframe() to schedule the first frame render for the xr device.
...And 3 more matches
Lighting a WebXR setting - Web APIs
while sunlight does actually fall off in intensity with distance, the rate of change is very low and is only noticed over vast distances, so the rate of intensity change of sunlight doesn't typi
cally matter for rendering a 3d scene.
...the rate at which the brightness of a point light falls off is
called attenuation, and is a configurable feature of the light source in webgl and other lighting systems.
... computing the color of a lighted pixel although some graphics libraries include support for light source objects and automati
cally calculate and apply lighting effect for you, webgl does not.
...And 3 more matches
WebXR permissions and security - Web APIs
once that check is passed, the request to enter immersive-vr mode is allowed if all of the following are true: the requestsession()
call was issued by code executing within the handler for a user event, or the from the startup code for a user-launched web application.
... inline presentation when you request an xrsession with the mode set to inline, and any features are required or requested, the browser will only allow the session to be created if the
call to requestsession() was made by code which is executing expressly due to user intent.
... specifi
cally: if the requestsession()
call isn't coming from within the handler executed in response to a user event, and is not being issued while launching a web application, the request is denied and false is delivered to the promise's fulfillment handler.
...And 3 more matches
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.
...in floating point audio, 1 is a convenient number to map to "full scale" for mathematical operations on signals, so oscillators, noise generators and other sound sources typi
cally output bipolar signals in the range -1 to 1.
...e has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(audiocontext, filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audiocontext.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when
calling this function, which ensures that we can only run subsequent code when it has finished executing.
...And 3 more matches
window.postMessage() - Web APIs
origin the origin of the window that sent the message at the time postmessage was
called.
...note that this origin is not guaranteed to be the current or future origin of that window, which might have been navigated to a different location since postmessage was
called.
... the secret response is: rheeeeet!" } window.addeventlistener("message", receivemessage, false); /* * in the popup's scripts, running on <http://example.com>: */ //
called sometime after postmessage is
called function receivemessage(event) { // do we trust the sender of this message?
...And 3 more matches
XMLHttpRequest.readyState - Web APIs
open() not
called yet.
... 1 opened open() has been
called.
... 2 headers_received send() has been
called, and headers and status are available.
...And 3 more matches
XRInputSourceArray.forEach() - Web APIs
the xrinputsourcearray method foreach() executes the specified
callback once for each input source in the array, starting at index 0 and progressing until the end of the list.
... syntax xrinputsourcearray.foreach(
callback, thisarg); parameters
callback a function to execute once for each entry in the array xrinputsourcearray.
... the
callback accepts up to three parameters: currentvalue a xrinputsource object which is the value of the item from within the xrinputsourcearray which is currently being processed.
...And 3 more matches
XRSession.cancelAnimationFrame() - Web APIs
the cancelanimationframe() method of the xrsession interface cancels an animation frame which was previously requested by
calling requestanimationframe.
... syntax xrsession.cancelanimationframe(handle); parameters handle the unique value returned by the
call to requestanimationframe() that previously scheduled the animation
callback.
...once started, the session schedules its first frame to be rendered by
calling requestanimationframe().
...And 3 more matches
Keyboard-navigable JavaScript widgets - Accessibility
these widgets are typi
cally composed of <div> and <span> elements that do not, by nature, offer the same keyboard functionality that their desktop counterparts do.
...once keyboard focus lands on the containing <ul> element, the javascript developer must programmati
cally manage focus and respond to arrow keys.
...there are two techniques for accomplishing this: roving tabindex: programmati
cally moving focus aria-activedescendant: managing a 'virtual' focus technique 1: roving tabindex setting the tabindex of the focused element to "0" ensures that if the user tabs away from the widget and then returns, the selected item within the group retains focus.
...And 3 more matches
Coordinate systems - CSS: Cascading Style Sheets
this fixed point is
called the origin.
... dimensions in the coordinate systems used by web technologies, convention dictates that the horizontal offset is
called the x-coordinate, where a negative value indicates a position to the left of the origin and a positive value is to the right of the origin.
...this code will be
called by the event handler for the various mouse events we watch.
...And 3 more matches
Border-image generator - CSS: Cascading Style Sheets
topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) return; value = parsefloat(value.tofixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setattribute('data-value', value); slider.setinputvalue(); if (send_notify === false) return; notify.
call(slider); }; var setmax = function setmax(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.max = value; setvalue(topic, slider.value); }; var setmin = function setmin(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.min = value; setvalue(topic, slider.value); }; var setunit = function setunit...
...value : 5; }; var getnode = function getnode(topic) { return sliders[topic].node; }; var getprecision = function getprecision(topic) { return sliders[topic].precision; }; var getstep = function getstep(topic) { return sliders[topic].step; }; var subscribe = function subscribe(topic,
callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(
callback); }; var unsubscribe = function unsubscribe(topic,
callback) { subscribers[topic].indexof(
callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].len...
...!== "ui-dropdown-list") { this.setnodevalue(e.target); this.toggle(false); } this.time = date.now(); }; dropdown.prototype.setnodevalue = function setnodevalue(node) { this.value['name'] = node.textcontent; this.value['value'] = node.getattribute('data-value'); this.select.textcontent = node.textcontent; this.select.setattribute('data-value', this.value['value']); 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(dropd...
...And 3 more matches
vertical-align - CSS: Cascading Style Sheets
the vertical-align property can be used in two contexts: to verti
cally align an inline element's box inside its containing line box.
... for example, it could be used to verti
cally position an <img> in a line of text: <p> top:<img style="vertical-align:top" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> middle:<img style="vertical-align:middle" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> bottom:<img style="vertical-align:bottom" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> super:<img style="vertical-align:super" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> sub:<img style="vertical-align:sub" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> </p> <p> text-top:<img style="vertical-align:text-top" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> text-bottom:<img style="vertical-align:text-bottom" src="https://udn.realityrip...
...lityripple.com/samples/16/ed9c61c3b6.png"/> -100%:<img style="vertical-align:-100%" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> </p> #* { box-sizing: border-box; } img { margin-right: 0.5em; } p { height: 3em; padding: 0 .5em; font-family: monospace; text-decoration: underline overline; margin-left: auto; margin-right: auto; width: 80%; } to verti
cally align the content of a cell in a table: <table> <tr> <td style="vertical-align: baseline">baseline</td> <td style="vertical-align: top">top</td> <td style="vertical-align: middle">middle</td> <td style="vertical-align: bottom">bottom</td> <td> <p>there is a theory which states that if ever anyone discovers exactly what the universe is for and why it is here, it wil...
...And 3 more matches
Video player styling basics - Developer guides
note: in some cases some basic css is omitted from the code examples here as its use is either obvious or not specifi
cally relevant to styling the video player.
...its position is also specifi
cally set to relative, which is required for its responsiveness (more on that later).
...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'); } } // mute button else...
...And 3 more matches
Overview of events and handlers - Developer guides
browsers use as the registration method for the function which will handle those data structures a method
called addeventlistener which expects as arguments a string event type name and the handler function.
... this code relies on the agreement that there is a kind of event
called 'click' which will
call any listener (or 'handler') function with an event object argument (actually, in this case a derivative mouseevent object) and which will be fired by html button elements after user interaction.
... the code has no visible effect until a user interacts with the button either by placing the mouse pointer over the html button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the html button; when that happens, the buttondomelement javascript object would
call the example_click_handler function with an event object as an argument.
...And 3 more matches
Using HTML sections and outlines - Developer guides
semantic sectioning elements are specifi
cally designed to communicate structural meaning to browsers and other technologies interpreting the document on behalf of users, such as screen readers and voice assistants.
... html header element (<header>) defines a page area that typi
cally contains a logo, title, and navigation.
... html footer element (<footer>) defines a page footer, which typi
cally contains copyright or legal notices and sometimes some links.
...And 3 more matches
HTML attribute reference - HTML: Hypertext Markup Language
attribute list attribute name elements description accept <form>, <input> list of types the server accepts, typi
cally a file type.
... autocapitalize global attribute sets whether input is automati
cally capitalized when entered by user autocomplete <form>, <input>, <select>, <textarea> indicates whether controls in this form can by default have their values automati
cally completed by the browser.
... autofocus <button>, <input>, <keygen>, <select>, <textarea> the element should be automati
cally focused after the page loaded.
...And 3 more matches
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
autoplay a boolean attribute: if specified, the audio will automati
cally begin playback as soon as it can do so, without waiting for the entire audio file to finish downloading.
... note: sites that automati
cally play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible.
... if you must offer autoplay functionality, you should make it opt-in (requiring a user to specifi
cally enable it).
...And 3 more matches
<input type="color"> - HTML: Hypertext Markup Language
the element's presentation may vary substantially from one browser and/or platform to another—it might be a simple textual input that automati
cally validates to ensure that the color information is entered in the proper format, or a platform-standard color picker, or some kind of custom color picker window.
... colorwell.select(); appearance variations as previously mentioned, when a browser doesn't support a color picker interface, its implementation of color inputs will be a text box that validates the contents automati
cally to ensure that the value is in the correct format.
... var colorwell; var defaultcolor = "#0000ff"; window.addeventlistener("load", startup, false); initialization once the page is loaded, our load event handler, startup(), is
called: function startup() { colorwell = document.queryselector("#colorwell"); colorwell.value = defaultcolor; colorwell.addeventlistener("input", updatefirst, false); colorwell.addeventlistener("change", updateall, false); colorwell.select(); } this gets a reference to the color <input> element in a variable
called colorwell, then sets the color input's value to the value in defaultcolor...
...And 3 more matches
inputmode - HTML: Hypertext Markup Language
decimal fractional numeric input keyboard containing the digits and decimal separator for the user's locale (typi
cally .
...inputs that require a telephone number should typi
cally use <input type="tel">instead.
...inputs that require a search query should typi
cally use <input type="search"> instead.
...And 3 more matches
Using the application cache - HTML: Hypertext Markup Language
[allow] [never for this site] [not now] the term "offline(-enabled) applications" sometimes refers specifi
cally to applications that the user has allowed to use offline capabilities.
... if the manifest file has changed, all the files listed in the manifest—as well as those added to the cache by
calling applicationcache.add()—are fetched into a temporary cache, following the appropriate http caching rules.
... once all the files have been successfully retrieved, they are moved into the real offline cache automati
cally, and a cached event is sent to the applicationcache object.
...And 3 more matches
Evolution of HTTP - HTTP
initially
calling it the mesh, it was later renamed to world wide web during its implementation in 1990.
... a client to display (and accidentally edit) these documents, the first web browser
called worldwideweb.
... http/0.9 – the one-line protocol the initial version of http had no version number; it has been later
called 0.9 to differentiate it from the later versions.
...And 3 more matches
Browser detection using the user agent - HTTP
while user agent sniffing can sometimes detect these, not all devices are the same: some mobile devices have big screen sizes, some desktops have a small touchscreen, some people use smart tv's which are an entirely different ballgame altogether, and some people can dynami
cally change the width and height of their screen by flipping their tablet on its side!
...never be satisfied with your webpage until you can open up the dev tools side panel and resize the screen while the webpage looks smooth, fluid, and dynami
cally resized.
... the simplest way to do this is to separate all the code that moves content around based on screen size to a single function that is
called when the page is loaded and at each resize event thereafter.
...And 3 more matches
HTTP caching - HTTP
however, common http caches are typi
cally limited to caching responses to get and may decline other methods.
... freshness once a resource is stored in a cache, it could theoreti
cally be served by the cache forever.
... caches have finite storage so items are periodi
cally removed from storage.
...And 3 more matches
Content negotiation - HTTP
principles of content negotiation a specific document is
called a resource.
...the server uses this url to choose one of the variants it provides – each variant being
called a representation – and returns a specific representation to the client.
...how a specific representation is chosen when the resource is
called is determined by content negotiation and there are several ways of negotiating between the client and the server.
...And 3 more matches
Introduction - JavaScript
in contrast, javascript descends in spirit from a line of smaller, dynami
cally typed languages such as hypertalk and dbase.
...inheritance is through the prototype mechanism, and properties and methods can be added to any object dynami
cally.
...classes and instances cannot have properties or methods added dynami
cally.
...And 3 more matches
constructor - JavaScript
} description a constructor enables you to provide any custom initialization that must be done before any other methods can be
called on an instantiated object.
...if your class is a base class, the default constructor 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 v...
... however, if you provide your own constructor, and your class derives from some parent class, then you must explicitly
call the parent class constructor using super.
...And 3 more matches
TypeError: "x" is not a function - JavaScript
the javascript exception "is not a function" occurs when there was an attempt to
call a value from a function, but the value is not actually a function.
... it attempted to
call a value from a function, but the value is not actually a function.
...maybe the object you are
calling the method on does not have this function?
...And 3 more matches
Array.prototype.flatMap() - JavaScript
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.
... arrayoptional the array map was
called upon.
... thisargoptional value to use as this when executing
callback.
...And 3 more matches
FinalizationRegistry.prototype.unregister() - JavaScript
there is no need to all unregister in your cleanup
callback.
... only
call unregister if you haven't received a cleanup
callback and no longer need to receive one.
... examples 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.
...And 3 more matches
Function - JavaScript
calling the constructor directly can create functions dynami
cally but suffers from security and similar (but far less significant) performance issues to eval.
... function.
caller specifies the function that invoked the currently executing function.
... instance methods function.prototype.apply(thisarg [, argsarray])
calls a function and sets its this to the provided thisarg.
...And 3 more matches
JSON.stringify() - JavaScript
initially, the replacer function is
called with an empty string as key representing the object being stringified.
... it is then
called for each property on the object or array being stringified.
... if you return any other object, the object is recursively stringified,
calling the replacer function on each property.
...And 3 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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 3 more matches
Property accessors - JavaScript
a method is simply a property that can be
called (for example, if it has a reference to a function instance as its value).
...(in the ecmascript standard, the names of properties are techni
cally "identifiernames", not "identifiers", so reserved words can be used but are not recommended).
... const variable = object.property_name; object.property_name = value; const object = {}; object.$1 = 'foo'; console.log(object.$1); // 'foo' object.1 = 'bar'; // syntaxerror console.log(object.1); // syntaxerror here, the method named createelement is retrieved from document and is
called.
...And 3 more matches
function* - JavaScript
generators in javascript -- especially when combined with promises -- are a very powerful tool for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with
callbacks, such as
callback hell and inversion of control.
...
calling a generator function does not execute its body immediately; an iterator object for the function is returned instead.
... when the iterator's next() method is
called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function.
...And 3 more matches
Transitioning to strict mode - JavaScript
poisoned arguments and function properties accessing arguments.
callee, arguments.
caller, anyfunction.
caller, or anyfunction.arguments throws an error in strict mode.
... the only legitimate use case would be to reuse a function as in: // example taken from vanillajs: http://vanilla-js.com/ var s = document.getelementbyid('thing').style; s.opacity = 1; (function() { if ((s.opacity-=.1) < 0) s.display = 'none'; else settimeout(arguments.
callee, 40); })(); which can be rewritten as: 'use strict'; var s = document.getelementbyid('thing').style; s.opacity = 1; (function fadeout() { // name the function if((s.opacity-=.1) < 0) s.display = 'none'; else settimeout(fadeout, 40); // use the name of the function })(); semantic differences these differences are very subtle differences.
... this in function
calls in function
calls like f(), the this value was the global object.
...And 3 more matches
Authoring MathML - MathML
texzilla has an <x-tex> custom element, that can be used to write things like <x-tex>\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1</x-tex> and get it automati
cally converted into mathml.
...then on your web pages, add a <script> tag to load asciimathml and the mathematical expressions delimited by ` (grave accent) will be automati
cally parsed and converted to mathml: <html> <head> ...
...the installation is similar: copy latexmathml.js and latexmathml.standardarticle.css, add links in the header of your document and the latex content of your web page marked by the "latex" class will be automati
cally parsed and converted to html+mathml: <head> ...
...And 3 more matches
Exported WebAssembly functions - WebAssembly
exported webassembly functions are basi
cally just javascript wrappers that represent webassembly functions in javascript.
... when you
call them, you get some activity in the background to convert the arguments into types that wasm can work with (for example converting javascript numbers to int32), the arguments are passed to the function inside your wasm module, the function is invoked, and the result is converted and passed back to javascript.
... you can retrieve exported webassembly functions in two ways: by
calling table.prototype.get() on an existing table.
...And 3 more matches
ui/frame - Archive of obsolete content
to do this, you
call postmessage() not on the frame itself but on the source attribute of the object passed into an event listener.
...you can specify the url in one of two ways: as a resource:// url pointing at a file under your add-on's "data" directory, typi
cally constructed using self.data.url(filename) as a relative path: a string in the form "./relativepath", where "relativepath" is a relative path to the file beginning in your add-on's "data" directory var { frame } = require("sdk/ui/frame"); var self = require("sdk/self"); var frame1 = new frame({ url: require("sdk/self").data.url("content1.html") }); var frame2 = new frame({ ur...
...toolbar = toolbar({ name: "my-toolbar", title: "my toolbar", items: [frame] }); frame.postmessage("ping", frame.url); frame scripts can receive these messages using window.addeventlistener(): function ponged(message) { label.textcontent = message.data; } window.addeventlistener("message", ponged, false); to send a message only to the frame instance hosted by a specific browser window
call postmessage() on the source property of the object passed into any of the frame's event listeners.
...And 2 more matches
ui/toolbar - Archive of obsolete content
); 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.
... after that, though, you can't show or hide the toolbar programmati
cally.
...the listener is automati
cally removed after the first time the event is emitted.
...And 2 more matches
Creating annotations - Archive of obsolete content
the click handler sends a message
called show back to the main add-on code.
...notator', 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.
... the page-mod matches all pages, so each time the user loads a page the page-mod emits the attach event, which will
call the listener function we've assigned to onattach.
...And 2 more matches
Unit Testing - Archive of obsolete content
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.
... now "index.js" imports the base64 module and
calls its two exported functions.
...in its place create a file
called test-base64.js with the following contents: var base64 = require("../base64"); exports["test atob"] = function(assert) { assert.ok(base64.atob("agvsbg8=") == "hello", "atob works"); } exports["test btoa"] = function(assert) { assert.ok(base64.btoa("hello") == "agvsbg8=", "btoa works"); } exports["test empty string"] = function(assert) { assert.throws(function() { base64.atob(); }, "empty string check works"); } require("sdk/test").run(exports); note that with jpm we must give the e...
...And 2 more matches
JavaScript Debugger Service - Archive of obsolete content
snippets acquiring the service we acquire the service by
calling the xpcom object.
...nscriptdestroyed: function(script) { // your function here } }; jsd.errorhook = { onerror: function(message, filename, lineno, colno, flags, errnum, exc) { // your function here } }; // triggered when jsd.errorhook[onerror] returns false jsd.debughook = { onexecute: function(frame, type, rv) { // your function here } }; jsd.enumeratescripts({ // the enumeratescript method will be
called once for every script jsd knows about enumeratescript: function(script) { // your function here } }); a simple stack trace here, we will show how to implement a simple javascript stack trace using the jsd.
... note that onerror is
called for every exception.
...And 2 more matches
Miscellaneous - Archive of obsolete content
running us services.appinfo.name; // returns "firefox" for firefox services.appinfo.version; // returns "2.0.0.1" for firefox version 2.0.0.1 retrieving the version of an extension as specified in the extension's install.rdf components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("extension-guid@example.org", function(addon) { // this is an asynchronous
callback function that might not be
called immediately alert("my extension's version is " + addon.version); }); restarting firefox/thunderbird/seamonkey_2.0 for firefox 3 see onwizardfinish around here: http://mxr.mozilla.org/seamonkey/sou...pdates.js#1639 for firefox 2 see around here: http://mxr.mozilla.org/mozilla1.8/so...pdates.js#1631 bug 338039 tracks improving this situation by providi...
...further enhancements would include // handling for fields dynami
cally added to the page (e.g., by page javascript).
...g(0, element.selectionstart); var aftertext = currentvalue.substring(element.selectionend, currentvalue.length); element.value = beforetext + snippet + aftertext; element.focus(); //put the cursor after the inserted text element.setselectionrange(selectionend, selectionend); } inserttext(document.getelementbyid("example"), "the text to be inserted"); disabling javascript programmati
cally // disable js in the currently active tab from the context of browser.xul gbrowser.docshell.allowjavascript = false; if this isn't your browser, you should save the value and restore it when finished.
...And 2 more matches
Common Pitfalls - Archive of obsolete content
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.
... how to do security checks for uri loads before loading a uri, one of two security checks needs to be performed: if the uri is a string that will be loaded via passing the string to nsiwebnavigation::loaduri, the one must
call checkloaduristrwithprincipal and pass the principal that the uri originates from as the first argument and the uri string as the second argument.
... in all other cases, one should
call checkloaduriwithprincipal and pass the principal that the uri originates from as the first argument and an nsiuri object representing the uri as the second argument.
...And 2 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
sometimes an extension will be packaged with a special xpcom component developed specifi
cally for it.
...
calling xpcom from xpconnect use the xpconnect technology to use xpcom in javascript.
... each component is identified with a contract id in the form @domain_name/module_name/component_name;version_number, and implements one or more interfaces that determine what functions can be
called on these components.
...And 2 more matches
Adding menus and submenus - Archive of obsolete content
you can also have menus that are filled dynami
cally.
...the oncommand attribute is set on the menupopup to avoid code duplication, since now the 3 items
call the same function.
...menu icons are typi
cally 16px by 16px.
...And 2 more matches
Custom XUL Elements with XBL - Archive of obsolete content
« previousnext » xml binding language (xbl, sometimes also
called extensible bindings language) is a language for describing bindings that can be attached to elements in other documents.
... the element that the binding is attached to,
called the bound element, acquires the new behavior specified by the binding.
...in this case we're adding the "persons" dynami
cally, so you'll have to look into the js file to see how xshelloperson elements are created and added to the dom just like any other.
...And 2 more matches
Index of archived content - Archive of obsolete content
nabling quicklaunch for all users how mozilla finds its configuration files how thunderbird and firefox find their configuration files introduction kill the xul.mfl file for good locked config settings other mozilla customization pages protecting mozilla's registry.dat file automati
cally handle failed asserts in debug builds blackconnect blackwood bonsai bookmark keywords build building transformiix standalone chromeless compiling the npruntime sample plugin in visual studio creating a firefox sidebar extension creating a microsummary creating a mozilla exten...
...sion adding the structure conclusion enabling the behavior - retrieving tinderbox status enabling the behavior - updating the status bar panel enabling the behavior - updating the status periodi
cally finding the code to modify finding the file to modify making a mozilla installation modifiable making it into a dynamic overlay and packaging it up for distribution making it into a static overlay prerequisites specifying the appearance tinderbox creating a release tag creating a skin for firefox/getting started creating a skin for mozilla faq ...
... plugins adobe flash external resources for plugin creation logging multi-process plugins monitoring plugins multi-process plugin architecture npapi plugin developer guide npapi plugin reference browser-side plug-in api npapi plug-in side api npany
callbackstruct npbyterange npclass npembedprint npevent npfullprint npidentifier npn newstream npnvariable npn_createobject npn_destroystream npn_enumerate npn_evaluate npn_forceredraw npn_getauthenticationinfo npn_getintide...
...And 2 more matches
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
extract theme while you can hypotheti
cally begin with any theme already designed for firefox, for the sake of consistency we'll speak as though everyone is editing the default firefox theme.
...opening the .jar files in your archive manager of choice should result in the file being automati
cally detected as being a zip archive.
... skin\classic\communicator doesn't do a whole lot and can typi
cally be forgotten about promptly.
...And 2 more matches
Building Firefox with Rust code - Archive of obsolete content
please instead refer to the documentation found within the modern firefox build system documentation; specifi
cally, the section
called including rust code in firefox.
... 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.
... if you want to
call code in the "e10s" crate, you would add: extern crate e10s; to toolkit/library/rust/shared/lib.rs; you would also need to specify the path to that crate in the dependencies section of toolkit/library/rust/shared/cargo.toml: [dependencies] e10s = { path = "../../../../path/from/srcdir/e10s" } the e10s crate must also be checked into the tree at the appropriate path.
...And 2 more matches
Twitter - Archive of obsolete content
to
call trends/current, use jetpack.lib.twitter.trends.current().
...success is a function that's
called when the request successfully completes, and error is a function
called when it fails to complete.
... the library simply passes them to jquery.ajax(), and so they are
called like so: success(data, textstatus) data is twitter's decoded json response.
...And 2 more matches
Microsummary topics - Archive of obsolete content
warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) programmati
cally installing a microsummary generator to programmati
cally install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then
call its installgenerator() method, passing it an xml document containing the generator.
...when programmati
cally installing generators, you should specify a unique identifier for the generator in the uri attribute of the <generator> element.
...in the future, firefox may access source urls to download updated versions of generators, so unless you are installing generators which are available from urls, you should not use this form for your programmati
cally-installed generators.
...And 2 more matches
Build - Archive of obsolete content
extract the source code, and you should have a directory
called mozilla/.
... change directory into mozilla/ and checkout the latest prism code : cd mozilla/ svn co http://svn.mozilla.org/projects/webrunner/trunk prism create a file
called .mozconfig make sure it is in the mozilla/ directory.
...file should look something like this : mk_add_options moz_co_project=xulrunner mk_add_options moz_objdir=@topsrcdir@/mozilla-obj ac_add_options --enable-application=xulrunner ac_add_options --disable-debug ac_add_options --enable-optimize ac_add_options --disable-tests ac_add_options --disable-javaxpcom build xulrunner : make -f client.mk build once the build is done, there will be a directory
called mozilla-obj.
...And 2 more matches
RDF Datasource How-To - Archive of obsolete content
there are basi
cally two approaches that you can take in this endeavor: delegate to an inner proxy.
...typi
cally, you provide a parser for reading in some sort of static storage (e.g., a data file); the parser translates the datafile into a series of
calls to assert() to set up the in-memory datasource.
... when flush() is
called, or the last reference to the datasource is released, a routine walks the in-memory datasource and re-serializes the graph back to the original file format.
...And 2 more matches
Space Manager High Level Design - Archive of obsolete content
bandrects are a linked list (provided by prcliststr super-class) and also provide some geometry-management methods (splitverti
cally, splithorizontally) and some methods that query or manipulate the frames associated with the band (isoccupiedby, addframe, removeframe).
...eck if the float can be placed in the actual band: if not advance to the next band; check the float type and if it can be added to the space manager; align the float to its containing block top if rule css2/9.5.1/4 is not respected; add the float using nsspacemanager::addrectregion compare the area that the float used to occupy with the area that it now occupies: if different, record the verti
cally affected interval using nsspacemanager::includeindamage use case 3: space manager is used to find available space to reflow into the nsblockframe makes use of the space manager indirectly to get the available space to reflow a child block or inline frame into.
... getavailablespace is
called on the blockreflowstate the blockreflowstate
calls getavailablespace on its blockbanddata instance (which was setup in the blockreflowstate's constructor based on the space manager passed in and computed content area).
...And 2 more matches
String Quick Reference - Archive of obsolete content
function declarations what: use abstract classes instead of concrete classes when passing strings across function boundaries why: using abstract classes allows the
caller to choose the storage mechanism, allowing for possible sharing or more efficient handling of string fragments.
...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")); converting literal strings to string objects what: converting from const prunichar*/const char* to the appropriate string type why: avoid making extra copies of strings, just to convert between types!
...And 2 more matches
Example Sticky Notes - Archive of obsolete content
--> <stylesheet src="notes.css"/> </resources> <content> <!-- this svg graphics will be added automati
cally around each bound element.
...--> <constructor><![cdata[ /** * the code below will be
called one time only after * the binding is successfully prepared and bound.
... */ // your code goes here ]]></constructor> <destructor><![cdata[ /** * the code below will be
called one time only before * binding is unbound.
...And 2 more matches
Moving, Copying and Deleting Files - Archive of obsolete content
copying a file nsifile.copyto() is used to copy files or directories, and should be
called on the source file to copy.
... 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.
...nsifile.copyto() of the former is
called, passing the latter as the first argument to nsifile.copyto().
...And 2 more matches
Box Model Details - Archive of obsolete content
as shown in the image, there are two buttons which expand verti
cally to fit their container, which in this case is the hbox.
... alignment controls how the row of elements are aligned verti
cally.
... vertical boxes lay out their elements verti
cally in a column.
...And 2 more matches
More Wizards - Archive of obsolete content
call the wizard's goto() method.
...you might
call this method in the onpageadvanced or onwizardnext handlers.
...the function checkcode() is
called whenever the first page is shown as indicated by the onpageshow attribute.
...And 2 more matches
Tree Selection - Archive of obsolete content
when the user selects an item from the tree, the event handler is
called.
...if the user holds down the cursor key to rapidly scroll through the items, the event handler is not
called until the user stops.
...you would then write a loop for the number of ranges,
calling getrangeat() to get the actual indices of the start and end of the range.
...And 2 more matches
XBL Example - Archive of obsolete content
we'll
call this a slideshow element.
...to set the page, a method 'setpage' is
called which will be defined later.
...this will
call the onget script to get the value, increment or decrement the value by one, and then
call the onset handler to set the value.
...And 2 more matches
prefpane - Archive of obsolete content
onpaneload type: script code code defined here is
called when the pane has been loaded, much like the load event for a window.
... void userchangedvalue(in domelement element); the user changed the value in a widget that the preferences system does not automati
cally track state changes for (1) and the preference element associated with the widget should be updated based on the state held by the widget.
... for example, if you are using a listbox and the user changes the contents of the listbox (such as adding or removing an item) and you want to sync the changes back to a preference, you must write an onsynctopreference handler for your listbox that returns the value to be written to the preference element, and then
call the userchangedvalue function every time you edit the list in a way that should cause the preference's value to change.
...And 2 more matches
tooltip - Archive of obsolete content
noautohide type: boolean if this attribute is set to false or omitted, the tooltip will automati
cally disappear after a few seconds.
... example: <menupopup id="top" onpopuphidden="console.log('the onpopuphidden method of id=top was
called.');"> <menuitem label="item 1"/> <menuitem label="item 2"/> <menu id="submenu1" label="submenu 1"> <menupopup id="submenu1-popup"> <menuitem label="submenu1 item 1"/> <menuitem label="submenu1 item 2"/> </menupopup> </menu> <menu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="subme...
...this handler is usually used to dynami
cally set the contents when the user requests to display it.
...And 2 more matches
Debugging a XULRunner Application - Archive of obsolete content
it doesn't matter what the file is
called (as long as the extension is .js), so debug.js is as good as any!
... to output dump
calls instead to a file, set browser.dom.window.dump.file to the file destination where the log should be created and restart the application.
...to download the package, right-click the install link and save the package lo
cally.
...And 2 more matches
calICalendarView - Archive of obsolete content
implementations should therefore be wary to check whether a controller has been assigned to the view, before
calling any of the methods it implements.note that in most cases, this attribute will be set by the consumers of calicalendarview very early in an application/extension's loading process.
...note that this date is typi
cally not immediately useful for querying for the events and tasks shown in the calicalendarview.
... typi
cally, one more day must be added to it, in order to make it exclusive.
...And 2 more matches
NPN_PostURLNotify - Archive of obsolete content
notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify
call, which returns this value (see description below).
... description npn_posturlnotify functions identi
cally to npn_posturl, with these exceptions: npn_posturlnotify supports specifying headers when posting a memory buffer.
... npn_posturlnotify
calls npp_urlnotify upon successful or unsuccessful completion of the request.
...And 2 more matches
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
there are only two key differences: in the npp_setwindow
call, the window parameter will be the xid of the hosting xembed window.
...in your plugin instance npp_getvalue
call you need to make sure that you support the new nppvpluginneedsxembed value.
...the general idea is that you use the xid that was passed into your npp_setwindow()
call and create a gtkplug to host inside of that socket.
...And 2 more matches
TCP/IP Security - Archive of obsolete content
at each layer, the logical units are typi
cally composed of a header and a payload.
... designing a cryptographi
cally 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.
... another good source of information is nist sp 800-52, guidelines on the selection and use of transport layer security, available from https://csrc.nist.gov/publications/nistpubs/.) the use of tls typi
cally requires each application to support tls; however, unlike application layer controls, which typi
cally involve extensive customization of the application, transport layer controls such as tls are much less intrusive because they do not need to understand the application’s functions or characteristics.
...And 2 more matches
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.
... create a folder
called chrome in your theme's folder.
... create the install manifest open the file
called install.rdf that you created at the top of your extension's folder hierarchy and put this inside: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>sample@example.net</em:id> <em:version>1.0</em:version> <em:type>4</em:type> <!-- targe...
...And 2 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
full circle if you were part of the early web's big bang in the mid-1990s you might re
call that being able to use javascript both client-side and server-side was core to netscape's original vision for web apps.
...jaxer manages ajax
calls behind the scenes to accomplish this.
... listing 5 - demonstration of server-proxy <script runat="server"> function notexposed() { // runs on the server, hidden from the browser return "can't see me!"; } function exposed() { // runs on the server,
callable from the browser return "exposed to the browser"; } exposed.proxy = true; // tell jaxer this function is ok to be
called from the browser </script> <script runat="client" type="text/javascript"> alert( exposed() ); //works like a charm alert( notexposed() ); //produces an object not found error since it server-side only </script> understanding the concept of operating ...
...And 2 more matches
Reference - Archive of obsolete content
they are there specifi
cally to show the differences between the two versions.
...--maian 05:10, 22 september 2005 (pdt) if the examples are there specifi
cally to show the differences between two versions of js, and if we have a section in the reference that is dedicated to discussing these differences, i would think that those samples should be included in that section of the reference.
...thanks for your thoughts --
callek 15:05, 13 january 2006 (pst) notification when reorganization is finished leandro (localiser for the portuguese wiki) would like to be emailed when the js reference reorganization has been finished.
...And 2 more matches
RDF in Fifty Words or Less - Archive of obsolete content
right now, most web browsers let you organize your bookmarks hierarchi
cally intofolders.
... each bookmark is apointer to a web page
called a uri (uniform resource identifier).
...and fundamentally, there's no reason that you shouldn't be able to treat these as "bookmarks" as well, grouping them together into folders as you please, or maybe even creating "smart" folders that, when you open them, dynami
cally generate their contents by running common search that you define.
...And 2 more matches
Animations and tweens - Game development
loading the animation next up, go into your create() function, find the line that loads the ball sprite, and below it put the
call to animations.add() seen below: ball = game.add.sprite(50, 250, 'ball'); ball.animations.add('wobble', [0,1,0,2,0,1,0,2,0], 24); to add an animation to the object we use the animations.add() method, which contains the following parameters the name we chose for the animation an array defining the order in which to display the frames during the animation.
... applying the animation when the ball hits the paddle in the arcade.collide() method
call that handles the collision between the ball and the paddle (the first line inside update(), see below) we can add an extra parameter that specifies a function to be executed every time the collision happens, in the same fashion as the ballhitbrick() function.
... update the first line inside update() as shown below: function update() { game.physics.arcade.collide(ball, paddle, ballhitpaddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } then we can create the ballhitpaddle() function (having ball and paddle as default parameters), playing the wobble animation when it is
called.
...And 2 more matches
Scaling - Game development
we can make the game scale to fit on any screen size automati
cally during the preload stage, so we don't have to worry about it later.
...update your existing preload() function as follows: function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally = true; game.scale.pagealignverti
cally = true; } scalemode has a few different options available for how the canvas can be scaled: no_scale — nothing is scaled.
... exact_fit — scale the canvas to fill all the available space both verti
cally and horizontally, without preserving the aspect ratio.
...And 2 more matches
Function - MDN Web Docs Glossary: Definitions of Web-related terms
a function is a code snippet that can be
called by other code or by itself, or a variable that refers to the function.
... when a function is
called, arguments are passed to the function as input, and the function can optionally return a value.
...an outer function is a function containing a function (addsquares in this case): function addsquares(a,b) { function square(x) { return x * x; } return square(a) + square(b); }; //using ecmascript 2015 arrow notation const addsquares = (a,b) => { const square = x => x*x; return square(a) + square(b); }; a recursive function is a function that
calls itself.
...And 2 more matches
CSS and JavaScript accessibility best practices - Learn web development
make sure your headings stand out from your body text, typi
cally big and bold like the default styling.
... emphasised text inline markup that confers specific emphasis to the text that it wraps: <p>the water is <em>very hot</em>.</p> <p>water droplets collecting on surfaces is
called <strong>condensation</strong>.</p> you might want to add some simple coloring to your emphasised text: strong, em { color: #a60000; } you will however rarely need to style emphasis elements in any significant way.
... you shouldn't however deviate too much from the expected visual feedback form elements receive when they are focused, which is basi
cally the same as links (see above).
...And 2 more matches
HTML: A good basis for accessibility - Learn web development
— you'll keep seeing a common theme: the importance of using semantic html (sometimes
called posh, or plain old semantic html).
...here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0": <div data-message="this is from the first button" tabindex="0">click me!</div> <div data-message="this is from the second button" tabindex="0">click me too!</div> <div data-message="this is from the third button" tabindex="0">and me!</div> basi
cally, the tabindex attribute is primarily intended to allow tabbable elements to have a custom tab order (specified in positive numerical order), instead of just being tabbed through in their default source order.
...use it only if you really need to, for example, if the layout shows things in a very different visual order to the source code, and you want to make things work more logi
cally.
...And 2 more matches
HTML: A good basis for accessibility - Learn web development
— you'll keep seeing a common theme: the importance of using semantic html (sometimes
called posh, or plain old semantic html).
...here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0": <div data-message="this is from the first button" tabindex="0">click me!</div> <div data-message="this is from the second button" tabindex="0">click me too!</div> <div data-message="this is from the third button" tabindex="0">and me!</div> basi
cally, the tabindex attribute is primarily intended to allow tabbable elements to have a custom tab order (specified in positive numerical order), instead of just being tabbed through in their default source order.
...use it only if you really need to, for example, if the layout shows things in a very different visual order to the source code, and you want to make things work more logi
cally.
...And 2 more matches
Organizing your CSS - Learn web development
you will typi
cally have rules set up for: body p h1, h2, h3, h4, h5 ul and ol the table properties links in this section of the stylesheet we are providing default styling for the type on the site, setting up a default style for data tables and lists and so on.
...typi
cally they tend to result in more verbose use of css than you might have if you wrote and optimised every selector to a custom set of rules for that project.
... if you are not taking an oocss approach you might create custom css for the different places this pattern is used, for example creating a class
called comment with a bunch of rules for the component parts, then a class
called list-item with almost the same rules as the comment class except for some tiny differences.
...And 2 more matches
Practical positioning examples - Learn web development
in addition, so-
called "single page apps" are becoming very popular — especially for mobile web uis — because having everything served as a single file cuts down on the number of http requests required to view all the content, thereby improving performance.
... note: some web developers take things even further, only having one page of information loaded at once, and dynami
cally changing the information shown using a javascript feature such as xmlhttprequest.
... styling our tabs now we want to style tabs to look like tabs — basi
cally, these are a horizontal navigation menu, but instead of loading different web pages when they are clicked on like we've seen previously in the course, they cause different panels to be displayed on the same page.
...And 2 more matches
HTML basics - Learn web development
nesting elements you can put elements inside other elements too — this is
called nesting.
... empty elements some elements have no content and are
called empty elements.
...however these days, they don't do much, and are basi
cally just needed to make sure your document behaves correctly.
...And 2 more matches
How the Web works - Learn web development
clients and servers computers connected to the web are
called clients and servers.
...it's basi
cally like the street between your house and the shop.
...here it is", and then starts sending the website's files to the browser as a series of small chunks
called data packets (the shop gives you your goods, and you bring them back to your house).
...And 2 more matches
Advanced text formatting - Learn web development
a couple of examples: <p>we use <abbr title="hypertext markup language">html</abbr> to structure our web documents.</p> <p>i think <abbr title="reverend">rev.</abbr> green did it in the kitchen with the chainsaw.</p> these will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over): note: there is another element, <acronym>, which basi
cally does the same thing as <abbr>, and was intended specifi
cally for acronyms rather than abbreviations.
...if you wrap the text in <pre></pre> tags however, your whitespace will be rendered identi
cally to how you see it in your text editor.
... <var>: for specifi
cally marking up variable names.
...And 2 more matches
Creating hyperlinks - Learn web development
the root of this directory structure is
called creating-hyperlinks.
... when working lo
cally with a web site, you'll have one directory that contains the entire site.
...for example, if an index.html page is uploaded to a directory
called projects that sits inside the root of a web server, and the web site's domain is http://www.example.com, the page would be available at http://www.example.com/projects/index.html (or even just http://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it isn't specified in the url.) an absolute url will always point to the same location, no...
...And 2 more matches
Test your skills: Links - Learn web development
links 1 in this task we want you to help fill in the links on our whales information page: the first link should be linked to a page
called whales.html, which is in the same directory as the current page.
... you'll get a bonus point if you also set it so that the subject line of the email is automati
cally filled in as "question about whales".
... links 2 in this task we want you to fill in the four links so that they link to the appropriate places: the first link should link to an image
called blue-whale.jpg, which is located in a directory
called blue inside the current directory.
...And 2 more matches
What’s in the head? Metadata in HTML - Learn web development
chrome) automati
cally fix incorrect encodings, so depending on what browser you use, you may not see this problem anyway.
...some content management systems have facilities to automati
cally extract page author information and make it available for such purposes.
... note: in google, you will see some relevant subpages of mdn web docs listed below the main homepage link — these are
called sitelinks, and are configurable in google's webmaster tools — a way to make your site's search results better in the google search engine.
...And 2 more matches
Handling text — strings in JavaScript - Learn web development
previous overview: first steps next next, we'll turn our attention to strings — this is what pieces of text are
called in programming.
... let one = 'hello, '; let two = 'how are you?'; let joined = one + two; joined; the result of this is a variable
called joined, which contains the value "hello, how are you?".
...try this: let response = one + 'i am fine — ' + two; response; note: when you enter an actual string in your code, enclosed in single or double quotes, it is
called a string literal.
...And 2 more matches
Test your skills: Arrays - Learn web development
in this task we'd like you to create an array of three items, stored inside a variable
called myarray.
...save the result in a variable
called myarray.
... store the length of the array in a variable
called arraylength.
...And 2 more matches
Aprender y obtener ayuda - Learn web development
in fact, you'll be
called to do so as part of this course when you are learning!
... note: you might favor one learning method over the others, but realisti
cally a hybrid approach is probably what you will end up with.
...it is also physi
cally bad to work for too long without a break — looking at a monitor for too long can hurt your eyes, and sitting still for too long can be bad for your back or legs.
...And 2 more matches
Routing in Ember - Learn web development
typi
cally, when writing web applications, you want the page to be represented by the url so that if (for any reason), the page needs to refresh, the user isn't surprised by the state of the web app — they can link directly to significant views of the app.
... to adjust our old way of rendering the todolist app, we'll first need to replace the todolist component invocation from the application template with an {{outlet}}
call, which means "any sub-route will be rendered in place here".
...s service } from '@ember/service'; export default class indexroute extends route { @service('todo-data') todos; model() { let todos = this.todos; return { get alltodos() { return todos.all; } } } } we can now update the todomvc/app/templates/index.hbs file so that when it includes the <todolist /> component, it does so explicitly with the available model,
calling its alltodos() getter to make sure all of the todos are shown.
...And 2 more matches
Understanding client-side JavaScript frameworks - Learn web development
getting started with ember in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain lo
cally, create a sample app, and then do some initial setup to get it ready for 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 lo
cally, and get it prepared to start building our example.
...along the way, we'll learn about a few important concepts such as
calling components inside other components, passing data to them via props and saving data state.
...And 2 more matches
Eclipse CDT Manual Setup
setup time some points in the rest of this document below are old and taken care of by the mach commands described above (although some of the project configuration is not done automati
cally yet).
...this process is sometimes
called "build option discovery" or "compiler option discovery".
... 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 automati
cally" in "c/c++ > indexer", disable "automati
cally update the index" turning off automatic indexing prevents the cpu intensive indexer from running at various stages during the steps below before we're ready.
...And 2 more matches
Experimental features in Firefox
these nightly builds of firefox typi
cally include experimental or partially-implemented features, including those for proposed or cutting-edge web platform standards.
...the current implementation is a little inelegant but is basi
cally functional.
... nightly 33 no developer edition 33 no beta 33 no release 33 no preference name media.track.enabled dom document property: autoplaypolicy the document property autoplaypolicy returns a string indicating how the browser handles requests to automati
cally play media (either using the autoplay property on a media element or by attempting to trigger playback from javascript code.
...And 2 more matches
Limitations of chrome scripts
a common pattern here is to use the notification
callbacks property of the nsihttpchannel to get the dom window that initiated the load, like this: observe: function (subject, topic, data) { if (topic == "http-on-modify-request") { var httpchannel = subject.queryinterface(ci.nsihttpchannel); var domwindow = httpchannel.notification
callbacks.getinterface(ci.nsidomwindow); } } or this: observe: function (subject, topic, data) { if (to...
...pic == "http-on-modify-request") { var httpchannel = subject.queryinterface(ci.nsihttpchannel); var domwindow = httpchannel.notification
callbacks.getinterface(ci.nsiloadcontext).associatedwindow; } } in multiprocess firefox these patterns will no longer work: the getinterface
call will fail.
... in multiprocess firefox, notification
callbacks is a special object that tries to emulate the single-process notifications
callbacks object as best it can.
...And 2 more matches
Using the Browser API
to run the demo, the best approach is to clone the github repo lo
cally (or just download it directly if you don't do github), open webide, open the repo as a packaged app, then run it either on a simulator or a real device if you have one.
...when you press the keyboard's return button, the 'submit' event is fired, which we handle like this: urlform.addeventlistener('submit',function(e) { e.preventdefault(); browser.src = urlbar.value; urlbar.blur(); }); we first
call preventdefault() to stop the form just submitting and reloading the page — which is really not what we want.
...finally, we
call blur() on the url bar to stop focusing it, so the keyboard moves off the screen, allowing us to get our full screen view back.
...And 2 more matches
Extending a Protocol
to make this tutorial less abstract (more fun!), we are going to implement a js method
called echo() on the navigator interface.
... in our case, our protocol, which we will
call pecho.ipdl, will send a message to a parent, and the parent will respond with the message we sent.
... async __delete__(); - this is
called when an instance is deleted.
...And 2 more matches
JavaScript-DOM Prototypes in Mozilla
as an example: function bar() { alert("hello world!"); } document.images[0].__proto__.foo = bar; this would make every image in this document have a
callable foo property (i.e.
... so far so good; we have shared prototypes, and xpconnect gives us most of this automati
cally.
...nswindowsh::globalresolve() will be
called for every name on the parent chain).
...And 2 more matches
Addon
ring appversion, in string platformversion) void findupdates(in updatelistener listener, in integer reason, in string appversion, in string platformversion) overview of optional methods void uninstall() void canceluninstall() boolean hasresource(in string path) nsiuri getresourceuri(in string path) void getdatadirectory(in datadirectory
callback
callback) required properties attribute type description appdisabled read only boolean true if this add-on cannot be used in the application based on version compatibility, dependencies, and blocklisting.
... applybackgroundupdates integer indicates whether updates found in the background for this add-on will be applied automati
cally.
... contributionamount read only string averagerating read only number reviewcount read only integer reviewurl read only string totaldownloads read only integer weeklydownloads read only integer dailyusers read only integer repositorystatus read only integer
callbacks datadirectory
callback() a
callback which is passed a directory path, and, when an error has occured, an error object.
...And 2 more matches
Using JavaScript code modules
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.
...vel modules/directory containing the bar.js module (that is, the modules/directory is a sibling to chrome.manifest and install.rdf), you could create an alias to that directory via the instruction: resource foo modules/ (don't forget the trailing slash!) you could then import the module into your javascript code via the statement: components.utils.import("resource://foo/bar.js"); programmati
cally adding aliases custom aliases to paths that can be represented as an nsilocalfile can be programmati
cally added as well.
...a possible solution is moving the
call to components.utils.import() into the xpcom component constructor (discussion).
...And 2 more matches
WebRequest.jsm
t webrequest, use code like: let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); the webrequest object has the following properties, each of which corresponds to a specific stage in executing a web request: onbeforerequest onbeforesendheaders onsendheaders onheadersreceived onresponsestarted oncompleted each of these objects defines two functions: addlistener(
callback, filter, opt_extrainfospec) removelistener(
callback) adding listeners use addlistener to add a listener to a particular event.
... name type description
callback function the
callback argument is a function to be
called when the event is triggered.
... filter object the optional filter argument is used to restrict the requests for which the listener
callback will be invoked.
...And 2 more matches
DMD
first, you will need to push the libdmd.so library to the device so that it can by dynami
cally loaded by fennec.
...this will occur automati
cally the first time you run dmd.py on the output file.
...(void const*)) const (/home/njn/moz/mi2/xpcom/base/nscyclecollector.cpp:933) 0x7f6860fdb7af #04: nscyclecollector::sizeofincludingthis(unsigned long (*)(void const*), unsigned long*, unsigned long*, unsigned long*, unsigned long*, unsigned long*) const (/home/njn/moz/mi2/xpcom/base/nscyclecollector.cpp:3029) 0x7f6860fdb6b1 #05: cyclecollectormultireporter::collectreports(nsimemorymultireporter
callback*, nsisupports*) (/home/njn/moz/mi2/xpcom/base/nscyclecollector.cpp:3075) 0x7f6860fde432 #06: nsmemoryinfodumper::dumpmemoryreportstofileimpl(nsastring_internal const&) (/home/njn/moz/mi2/xpcom/base/nsmemoryinfodumper.cpp:626) 0x7f6860fece79 #07: nsmemoryinfodumper::dumpmemoryreportstofile(nsastring_internal const&, bool, bool) (/home/njn/moz/mi2/xpcom/base/nsmemoryinfodumper.cpp:344) 0x7f...
...And 2 more matches
TimerFirings logging
-991946880[7f46c365ba00]: [6775] fn timer (slack 100 ms): layeractivitytracker -991946880[7f46c365ba00]: [6775] fn timer (one_shot 250 ms): presshell::spaintsuppression
callback -991946880[7f46c365ba00]: [6775] fn timer (one_shot 160 ms): nsbrowserstatusfilter::timeouthandler -991946880[7f46c365ba00]: [6775] iface timer (one_shot 200 ms): 7f46964d7f80 -1340643584[7f46c365ec00]: [6775] obs timer (slack 1000 ms): 7f46a95a0200 each line has the following information.
...there are also timers for settimer or setinterval
calls in javascript code, as the following sample shows.
... 2082435840[100445640]: [81190] fn timer (one_shot 8000 ms): [from dladdr] gfxfontinfoloader::delayedstart
callback(nsitimer*, void*) second, on linux the code uses dladdr to get the symbol library and address, which can be post-processed by tools/rb/fix_stacks.py.
...And 2 more matches
Process Forking in NSPR
on some platforms, nspr threads directly map one-to-one to the threads provided by the platform vendor, on other platforms nspr threads are basi
cally user-level threads within a single process (with no kernel threads) and on still others nspr threads are user-level threads implemented on top of one or more kernel threads within single address space.
... nspr does not override the fork function and so, when fork is
called from the nspr thread the results are different on the various platforms.
... all the threads present in the parent process may be replicated in the child process, only the
calling thread may be replicated in the child process or only the
calling kernel thread may be replicated.
...And 2 more matches
NSPR Types
calling convention types are used for externally visible functions and globals.
...
calling convention types these types are used to support cross-platform declarations of prototypes and implementations: pr_extern is used for declarations of external functions or variables.
... pr_
callback is used for definitions and declarations of functions that are
called via function pointers.
...And 2 more matches
PR_AttachThread
the thread object is automati
cally destroyed when it is no longer needed.
... you don't need to
call pr_attachthread unless you create your own native thread.
... pr_init
calls pr_attachthread automati
cally for the primordial thread.
...And 2 more matches
PR_EnterMonitor
description when the
calling thread returns, it will have acquired the monitor's lock.
... attempts to acquire the lock for a monitor that is held by some other thread will result in the
caller blocking.
... if the monitor's entry count is greater than zero and the
calling thread is recognized as the holder of the lock, pr_entermonitor increments the entry count by one and returns.
...And 2 more matches
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.
...if the swapped out value is not null, the destructor function is
called.
...the destructor is
called with the runtime holding no locks.
...And 2 more matches
PR_WaitCondVar
if unsuccessful (for example, if the
caller has not locked the lock associated with the condition variable or the thread was interrupted with pr_interrupt), pr_failure.
... description before the
call to pr_waitcondvar, the lock associated with the condition variable must be held by the
calling thread.
... after a
call to pr_waitcondvar, the lock is released and the thread is blocked in a "waiting on condition" state until another thread notifies the condition or a
caller-specified amount of time expires.
...And 2 more matches
Using JSS
jss version 3.0 linked stati
cally with nss, so it only required nspr.
... jss versions 3.1 and later link dynami
cally with nss, so they also require the nss shared libraries.
...for example, the nspr library is
called nspr4.dll or libnspr4.dll on windows and libnspr4.so on solaris.
...And 2 more matches
NSS Memory allocation
each block of memory allocated in a plarenapool is
called a plarena.
...see the prototype at http://mxr.mozilla.org/nspr/source/n.../ds/plarenas.h a program should
call that function at the very end, after having shutdown nss and nspr, to really free the contents of the free list.
...leak analysis tools will frequently report the wrong
call stack for the allocation of leaked arenas.
...And 2 more matches
NSS 3.12.5 release_notes
memory for the strings are owned by the
caller, who is free to free them once nss_contextinit returns.
... additional documentation in pk11pub.h: the
caller of pk11_derencodepublickey should free the returned secitem with a secitem_freeitem(..., pr_true)
call.
...the
caller of pk11_readrawattribute should free the data buffer pointed to by item using a secitem_freeitem(item, pr_false) or port_free(item->data)
call.
...And 2 more matches
PKCS #11 Module Specs
these modules specs can be passed by the application directly to nss via the secmod_loadusermodule()
call.
... parameter passing if the parameter is specified, the application/library will strip the value out, processing any outter quotes and escapes appropriately, and pass the parameter to the pkcs #11 library when it
calls c_initialize().
... random - this token should be used to generate random numbers when the application
call 'pk11_generaterandom'.
...And 2 more matches
NSS_Initialize
if any of those simpler nss initialization functions suffices for your needs,
call that instead.
...nss_init_norootinit - don't try to look for the root certs module automati
cally.
...if a pkcs#11 module isn't thread-safe, don't serialize its
calls; just don't load it instead.
...And 2 more matches
NSS tools : modutil
the tasks associated with security module database management are part of a process that typi
cally also involves managing key databases and certificate databases.
... -newpwfile new-password-file specify a text file containing a token's new or replacement password so that a password can be entered automati
cally with the -changepw option.
... -pwfile old-password-file specify a text file containing a token's existing password so that a password can be entered automati
cally when the -changepw option is used to change passwords.
...And 2 more matches
NSS tools : ssltab
the tool does not automati
cally detect ssl sessions.
...for example, assume your development machine is
called intercept.
...if you are using the default badcert
callback, you can still connect through a dialog.
...And 2 more matches
NSS tools : ssltap
the tool does not automati
cally detect ssl sessions.
...for example, assume your development machine is
called intercept.
...if you are using the default badcert
callback, you can still connect through a dialog.
...And 2 more matches
sslcrt.html
description the cert_verifycertnow function must
call one or more pk11 functions to obtain the services of a pkcs #11 module.
...to obtain the value to pass in the wincx parameter,
call ssl_revealpinarg.
...when you
call cert_destroycertificate or seckey_destroyprivatekey, the function decrements the reference count and, if the reference count reaches zero as a result, both frees the memory and sets all the bits to zero.
...And 2 more matches
NSS Tools ssltap
the tool also displays the data to the shell window from which it was
called.
...the tool does not automati
cally detect ssl sessions.
... for example, assume your development machine is
called intercept.
...And 2 more matches
NSS tools : modutil
the tasks associated with security module database management are part of a process that typi
cally also involves managing key databases and certificate databases.
... -newpwfile new-password-file specify a text file containing a token's new or replacement password so that a password can be entered automati
cally with the -changepw option.
... -pwfile old-password-file specify a text file containing a token's existing password so that a password can be entered automati
cally when the -changepw option is used to change passwords.
...And 2 more matches
NSS tools : ssltap
the tool does not automati
cally detect ssl sessions.
...for example, assume your development machine is
called intercept.
...if you are using the default badcert
callback, you can still connect through a dialog.
...And 2 more matches
Performance Hints
however, if you don't intend for any other function to access these variables, then storing them globally is probably wrong anyway (what if you
called another function that had a loop like the one in sum!).
...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).
... a constructor
call like that indicates to the runtime that a javascript array should be used for the first n entries of the array.
...And 2 more matches
Garbage collection
in other words, from the point of view of the rest of the engine, the job of the gc is to allocate cells and automati
cally collect them.
... the spidermonkey incremental write barrier spidermonkey uses a (relatively!) simple, common incremental write barrier
called a snapshot-at-the-beginning allocate-black barrier.
...(this means if an object has all references to it dropped during this incremental gc, it will be collected on the next incremental gc.) this is
called snapshot-at-the-beginning because it is conceptually equivalent to taking a snapshot of live objects at the beginning of the incremental gc and marking all those objects.
...And 2 more matches
JS::PersistentRooted
this is typi
cally used for global variables.
...initialization may take place on construction, or in two phases if the no-argument constructor is
called followed by init().
... js::persistentrooted<t> may be automati
cally coerced to a js::handle<t> and js::mutablehandle<t>.
...And 2 more matches
JS::Value
js::value is not inherently type-safe it is an error to
call any accessor method on a value of a non-matching type: val.toint32() must only be
called if val.isint32(), val.tostring() must only be
called if val.isstring(), and so on.
... in particular, note that it is an error to
call val.toobject() when val.isnull().
...an assertion is thrown in the case that the type is not correct (val.isx() is
called for each val.tox(), where x is the type).
...And 2 more matches
JSCheckAccessOp
(it is also the type of the
callback set by js_setcheckobjectaccess
callback.) syntax typedef jsbool (* jscheckaccessop)(jscontext *cx, jsobject *obj, jsval id, jsaccessmode mode, jsval *vp); name type description cx jscontext * the js context in which the property access attempt is occurring.
...on success, the
callback must set *vp to the stored value of the property.
... if a class leaves the checkaccess field null, a runtime-wide object access
callback is
called instead; see js_setcheckobjectaccess
callback.
...And 2 more matches
JSExtendedClass.wrappedObject
this article covers features introduced in spidermonkey 1.8
callback for objects that wrap other objects.
...in these cases the engine
calls the jsextendedclass.wrappedobject
callback to get the wrapped object.
...when walking the chain to do this check, wrappers are automati
cally unwrapped.
...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.
...in contrast, all native and host objects have a jsobjectmap at obj->map, which may be shared among a number of objects, and which contains the jsobjectops *ops pointer used to dispatch object operations from api
calls.
... thus jsclass (which pre-dates jsobjectops in the api) provides a low-level interface to class-specific code and data, while jsobjectops allows for a higher level of operation, which does not use the object's class except to find the class's jsobjectops struct, by
calling clasp->getobjectops, and to finalize the object.
...And 2 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.
...on success, the
callback must set the *objp out parameter to null if id was not resolved; or non-null, referring to obj or one of its prototypes, if id was resolved; and return js_true.
...this hook instead of jsresolveop is
called via the jsclass.resolve member if jsclass_new_resolve is set in jsclass.flags.
...And 2 more matches
JSObjectOps.newObjectMap
the jsobjectops.newobjectmap
callback is
called whenever a new object is created.
...an application that implements jsobjectops must therefore either implement the newobjectmap by including the non-public header jsobj.h, or obtain the default newobjectmapop by
calling the jsclass.getobjectops
callback of a standard jsclass.
...usually, the nrefs parameter to jsobjectops.newobjectmap will be 1, to count the ref returned to the
caller on success.
...And 2 more matches
JSResolveOp
description jsresolveop
callback is a hook which is
called when a property is not found on an object.
... the
callback must set *resolvedp to true and return true if the property is resolved, or set *resolvedp to false and return true if the object has no lazy property with the given id; or return false to indicate any other error.
... obsolete since jsapi 36 the
callback must return true if the property is resolved, or if the object has no lazy property with the given id; or false to indicate any other error.
...And 2 more matches
JS_ClearContextThread
before transferring a jscontext from thread a to thread b, thread a must
call js_clearcontextthread.
... before thread b uses the jscontext, it must
call js_setcontextthread.
...no other thread may use cx until the current thread removes this association by
calling js_clearcontextthread.
...And 2 more matches
JS_ConvertValue
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...typi
cally users of this function set vp to point to v, so that if conversion is successful, v now contains the converted value.
... js_convertvalue
calls other, type-specific conversion routines based on the type argument.
...And 2 more matches
JS_DeleteProperty
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then obj's jsclass.delproperty hook is
called.
...in this case, obj's jsclass.delproperty hook is
called.
...And 2 more matches
JS_DumpNamedRoots
data void * a pointer that is passed to dump each time it is
called.
... description each
call to js_addnamedroot creates a record in a table of named roots maintained by the garbage collector.
...it
calls the dump function once for each named root in the given runtime rt.
...And 2 more matches
JS_GetFunctionObject
fun must be either a function implemented by a jsnative (or jsfastnative) or the result of a
call to js_compilefunction or similar functions.
... in other cases, the object returned by js_getfunctionobject is not necessarily safe to
call and should not be exposed to script.
...for certain functions, the two have a strictly one-to-one relationship, and for those functions it is safe to
call js_getfunctionobject to move from the jsfunction to the jsobject.
...And 2 more matches
JS_InstanceOf
syntax bool js_instanceof(jscontext *cx, js::handle<jsobject*> obj, const jsclass *clasp, js::
callargs *args); // added in spidermonkey 38 bool js_instanceof(jscontext *cx, js::handle<jsobject*> obj, const jsclass *clasp, jsval *argv); // obsolete since jsapi 32 name type description cx jscontext * pointer to a js context from which to derive runtime information.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
... args js::
callargs * optional pointer to arguments.
...And 2 more matches
JS_LookupProperty
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...flags js_lookuppropertywithflags and js_lookuppropertywithflagsbyid allow the
caller to specify flags requesting special lookup behavior.
...(the javascript engine simply passes these flags through to the object when it
calls the object's jsclass.resolve
callback, so objects of a custom jsclass may interpret these flags however they like.) if flags is 0, js_lookuppropertywithflags uses the default lookup rules, the ones used by js_lookupproperty.
...And 2 more matches
JS_SetErrorReporter
callback syntax typedef void (* jserrorreporter)(jscontext *cx, const char *message, jserrorreport *report); name type description cx jscontext * the context in which the error happened.
...the reporter you define is automati
cally passed a jserrorreport structure when an error occurs and has been parsed by js_reporterror.
... typi
cally, the error reporting mechanism you define should log the error where appropriate (such as to a log file), and display an error to the user of your application.
...And 2 more matches
JS_SetOptions
mxr id search for jsoption_private_is_nsisupports jsoption_compile_n_go
caller of js_compilescript et al promises to execute the compiled script once only, in the same scope object used for compilation.
... the
caller may not modify objects on the scope chain between compilation and execution.
... mxr id search for jsoption_moar_xml jsoption_native_branch_
callback the branch
callback set by js_setbranch
callback may be
called with a null script parameter, by native code that loops intensively.
...And 2 more matches
JS_SetProperty
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... if obj is a native object with custom setgeneric op, the op is
called with (cx, obj, id, &v, false)).
...after the new property is added, the jsclass.addproperty hook is
called with the arguments (cx, obj, id, &v).
...And 2 more matches
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.
...
calling this method before all other resources have been destroyed has undefined behavior.
... failure to
call this method, at present, has no adverse effects other than leaking memory.
...And 2 more matches
JS_SuspendRequest
suspends the
calling thread's current request, if any, to allow the thread to block or perform time-consuming calculations.
... savedepth jsrefcount (only in js_resumerequest) the valued returned by the matching js_suspendrequest
call.
... description in js_threadsafe builds, when a multi-threaded application is in a request but needs to block or perform lengthy computation that can race safely with the garbage collector, it should
call js_suspendrequest before the time-consuming operation and js_resumerequest after.
...And 2 more matches
JS_ValueToNumber
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...(this behavior is implemented by v's jsobjectops.defaultvalue hook, so host objects can override it all.) first, the object's jsclass.convert
callback is
called.
... for objects of standard classes, this is js_convertstub, which simply
calls v.valueof() if present.
...And 2 more matches
JS_ValueToString
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...(this behavior is implemented by v's jsobjectops.defaultvalue method, so host objects can override it all.) if v.tostring() is a function, it is
called.
... otherwise, the resulting object's jsclass.convert
callback is
called.
...And 2 more matches
SpiderMonkey 45
many jsapi types; functions, and
callback signatures, have changed though most functions that have retain their previous name, providing relatively unchanged functionality.
... applications will require significant changes, but most changes will be automati
cally detected by the c/c++ compiler, making them easy to detect and updating the code a relatively straightforward job.
...5) js::disposeperformancemonitoring (bug 1208747) js::setstopwatchismonitoringcpow (bug 1156264) js::getstopwatchismonitoringcpow (bug 1156264) js::setstopwatchismonitoringjank (bug 1156264) js::getstopwatchismonitoringjank (bug 1156264) js::isstopwatchactive (bug 674779) js::getperfmonitoringtestcpurescheduling (bug 1181175) js::addcpowperformancedelta (bug 1181175) js::setstopwatchstart
callback (bug 1208747) js::setstopwatchcommit
callback (bug 1208747) js::setgetperformancegroups
callback (bug 1208747) js_stringhasbeeninterned renamed to js_stringhasbeenpinned (bug 1178581) js_internjsstring renamed to js_atomizeandpinjsstring (bug 1178581) js_internstringn renamed to js_atomizeandpinstringn (bug 1178581) js_internstring renamed to js_atomizeandpinstring (bug 1178581) js_inter...
...And 2 more matches
Handling Mozilla Security Bugs
this work is separate from the work of developers adding new security features (cryptographi
cally-based or otherwise) to mozilla, although obviously many of the same people will be involved in both sets of activities.
...in particular, the mozilla.org bugzilla system will allow bug reports related to security vulnerabilities to be marked as "security-sensitive," and will have special access control features specifi
cally for use with such bug reports.
...each and every member of the mozilla security bug group will automati
cally have access to all mozilla bugs marked "security-sensitive." the members of the mozilla security bug group will be drawn primarily from the following groups: security developers (i.e., those whose bugs are often singled out as security-relevant or who have security-relevant bugs assigned to them), and security qa people who are the qa contacts for those bugs.
...And 2 more matches
Mork
the keys are hexadecimal numbers starting at 0x80, because the values less than 0x80 are theoreti
cally their representative ascii values.
...the first is the kind column (k), where the mid is typi
cally column-scoped (:c).
...changesets a group is theoreti
cally an atomic transaction à la sql's transactions.
...And 2 more matches
Components.Constructor
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.
...(this benefit is also partly a result of having to travel through the layer between the javascript engine and xpcom fewer times.) the behavior of functions returned by components.constructor() varies depending upon the arguments given to components.constructor() when
called.
...the component is then returned immediately, with only the base interface nsisupports available on it; you must
call nsisupports.queryinterface() on it to
call methods on the object.
...And 2 more matches
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.
...as of gecko 13 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10), if you don't specify a sandbox name it will default to the
caller's filename.
...And 2 more matches
nsXPIDLCString
class declaration nstxpidlstring extends nststring such that: (1) mdata can be null (2) objects of this type can be automati
cally cast to |const chart*| (3) getter_copies method is supported to adopt data allocated with ns_alloc, such as "out string" parameters in xpidl.
...
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
...And 2 more matches
nsXPIDLString
class declaration nstxpidlstring extends nststring such that: (1) mdata can be null (2) objects of this type can be automati
cally cast to |const chart*| (3) getter_copies method is supported to adopt data allocated with ns_alloc, such as "out string" parameters in xpidl.
...
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
...And 2 more matches
amIWebInstallListener
methods onwebinstallblocked()
called when the website is not allowed to directly prompt the user to install add-ons.
... return value true if the
caller should start the installs.
... onwebinstalldisabled()
called when installation by websites is currently disabled.
...And 2 more matches
nsIAutoCompleteInput
forcecomplete boolean if true, the text field automati
cally completes to the default result whenever the user hits the enter key or the text field loses focus.
...onsearchbegin()
called when the search starts.
...onsearchcomplete()
called when the search ends successfully.
...And 2 more matches
nsIConsoleService
if no messages are logged, this function will return a count of 0, but allocating a placeholder word for messages, showing as a 0-length array when
called from the script.
...if no messages are logged, this function will return a count of 0, but allocating a placeholder word for messages, showing as a 0-length array when
called from the script.
... note: see the code samples below for how to
call getmessagearray.
...And 2 more matches
nsIContentPrefService
to create an instance, use: var contentprefservice = components.classes["@mozilla.org/content-pref/service;1"] .getservice(components.interfaces.nsicontentprefservice); method overview void addobserver(in astring aname, in nsicontentprefobserver aobserver); nsivariant getpref(in nsivariant agroup, in astring aname, [optional] in nsicontentpref
callback a
callback); nsipropertybag2 getprefs(in nsivariant agroup); nsipropertybag2 getprefsbyname(in astring aname); boolean haspref(in nsivariant agroup, in astring aname); void removegroupedprefs(); void removeobserver(in astring aname, in nsicontentprefobserver aobserver); void removepref(in nsivariant agroup, in astring aname); voi...
...useful for accessing and manipulating preferences in ways that are
caller-specific or for which there is not yet a generic method, although generic functionality useful to multiple
callers should generally be added to this unfrozen interface.
... nsivariant getpref( in nsivariant agroup, in astring aname, in nsicontentpref
callback a
callback optional ); parameters agroup the group for which to retrieve a preference; this may be specified as either a uri or as a string; in either case, the group consists of all sites matching the hostname portion of the specified uri.
...And 2 more matches
nsIDOMChromeWindow
this method will fail unless
called while the left mouse button is held down,
callers must check this.
...when this method is
called on windows, gecko moves the mouse cursor to center of the button if the auto cursor snap setting is enabled on the system.
...this method is
called automati
cally on dialog element or wizard element of xul.
...And 2 more matches
nsILocalFile
followlinks prbool determines whether or not the nsilocalfile will automati
cally resolve symbolic links.
...the
caller is responsible for
calling pr_unloadlibrary() on the result.
...the
caller is responsible for
calling fclose() on the result.
...And 2 more matches
nsIMemory
the result must be freed with a
call to free() when it is no longer needed.
... void heapminimize( in boolean immediate ); parameters immediate if true, heap minimization will occur immediately if the
call was made on the main thread.
...the result must be freed with a
call to free() when it is no longer needed.
...And 2 more matches
nsIMessageListenerManager
all listener
callbacks for a particular message are invoked when that message is received.
... removemessagelistener() undo an addmessagelistener()
call; that is,
calling this causes listener to stop being invoked when the specified message is received.
... void addweakmessagelistener(in astring messagename, in nsimessagelistener listener); if you have two weak message listeners for the same message, they may be
called in any order.
...And 2 more matches
nsIMicrosummaryService
callable by content via nsisidebar.addmicrosummarygenerator().
...if the
caller passes a bookmark id, and one of the microsummaries is the current one for the bookmark, this method will retrieve content from the datastore for that microsummary, which is useful when
callers want to display a list of microsummaries for a page that isn't loaded, and they want to display the actual content of the selected microsummary immediately (rather than after the content is asynchronousl...
... bookmarkid optional the id of the bookmark for which this method is being
called.
...And 2 more matches
nsIMsgFolder
void alertfilterchanged(in nsimsgwindow msgwindow); void throwalertmsg(in string msgname, in nsimsgwindow msgwindow); astring getstringwithfoldernamefrombundle(in string msgname); void notifycompactcompleted(); long comparesortkeys(in nsimsgfolder msgfolder); [noscript] void getsortkey(out octet_ptr key, out unsigned long length); boolean
callfilterplugins(in nsimsgwindow amsgwindow); acstring getstringproperty(in string propertyname); void setstringproperty(in string propertyname, in acstring propertyvalue); boolean isancestorof(in nsimsgfolder folder); boolean containschildnamed(in astring name); nsimsgfolder getchildnamed(in astring aname); nsimsgfolder findsubfolder(in acstring ...
... dbtransferinfo nsidbfolderinfo subfolders nsisimpleenumerator readonly: returns an enumerator containing a list of nsimsgfolder items that are subfolders of the instance this is
called on.
... void toggleflag(in unsigned long flag); onflagchange()
called to notify the database and/or listeners of a change of flag.
...And 2 more matches
nsIMsgHeaderParser
it is up to the
caller to free them.
... the
caller may pass nsnull for charset and it will be interpreted as "us-ascii".
... either of the provided pointers may be null if the
caller is not interested in those components.
...And 2 more matches
nsIPipe
re
call that a non-blocking stream will return ns_base_stream_would_block if it cannot be read or written to without blocking the
calling thread.
... for example, if you try to read from an empty pipe that has not yet been closed, then if that pipe's input end is non-blocking, then the read
call will fail immediately with ns_base_stream_would_block as the error condition.
... however, if that pipe's input end is blocking, then the read
call will not return until the pipe has data or until the pipe is closed.
...And 2 more matches
nsIPrintingPrompt
the service is automati
cally registered at start up.
... histori
cally, 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.
... note: the windows version mozilla implements this service which is automati
cally built and registered for you.
...And 2 more matches
nsIProgressEventSink
an implementation of this interface can be passed to a channel via the channel's notification
callbacks attribute.
...the channel will begin passing notifications to the progress event sink after its asyncopen method has been
called.
... notifications will cease once the channel
calls its listener's onstoprequest method or once the channel is canceled (via nsirequest.cancel()).
...And 2 more matches
nsISecurityCheckedComponent
this includes creating instances of arbitrary xpcom objects and
calling methods and setting properties on them.
...method overview string can
callmethod(in nsiidptr iid, in wstring methodname); string cancreatewrapper(in nsiidptr iid); string cangetproperty(in nsiidptr iid, in wstring propertyname); string cansetproperty(in nsiidptr iid, in wstring propertyname); methods can
callmethod() returns a capability string indicating what permissions are required to
call the specified method on the given interface.
... string can
callmethod( in nsiidptr iid, in wstring methodname ); parameters iid the iid of the interface this method exists on.
...And 2 more matches
nsIServiceManager
unlike createinstance, this will always return the same object each time it is
called with the same arguments.
... users of the service manager must first obtain a pointer to the global service manager by
calling ns_getservicemanager.
... after that, they can request specific services by
calling getservice().
...And 2 more matches
nsITaskbarTabPreview
1.0 66 introduced gecko 1.9.2 inherits from: nsitaskbarpreview last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) tab preview support is disabled by default in gecko 1.9.2 creating an nsitaskbartabpreview for a window will automati
cally hide that window's nsitaskbarwindowpreview; this is done by windows and cannot be prevented.
... when there are no more tab previews left for a window, the window preview is automati
cally made visible again.
... you can't directly instantiate this interface; instead,
call the nsiwintaskbar.createtaskbartabpreview().
...And 2 more matches
nsITaskbarWindowPreview
1.0 66 introduced gecko 1.9.2 inherits from: nsitaskbarpreview last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) you can't directly instantiate this interface; instead,
call nsiwintaskbar.gettaskbarwindowpreview() to get the taskbar preview for a specific window.
...if the enablecustomdrawing attribute is true, the controller you implement will start receiving
calls to its nsitaskbarpreviewcontroller.drawpreview() and nsitaskbarpreviewcontroller.drawthumbnail() methods, as well as reads of its width, height, and thumbnailaccessratio attributes.
...if a window has any visible nsitaskbartabpreview objects, the nsitaskbarwindowpreview for the corresponding window is automati
cally hidden.
...And 2 more matches
nsIUTF8StringEnumerator
the "next" element is the first string upon the first
call.
... must be preceded by a
call to hasmore(), which returns pr_true.
... this method is generally
called within a loop to iterate over the strings in the enumerator.
...And 2 more matches
nsIWebBrowser
the chrome object may optionally implement nsiwebprogresslistener instead of explicitly
calling addwebbrowserlistener() and removewebbrowserlistener() to register a progress listener object.
... methods addwebbrowserlistener() registers a listener of the type specified by the iid to receive
callbacks.
...typi
cally this method will be
called to register an object to receive nsiwebprogresslistener or nsishistorylistener notifications in which case the the iid is that of the interface.
...And 2 more matches
nsIWindowMediator
classes, ci: interfaces} = components; var windowlistener = { onopenwindow: function (awindow) { // wait for the window to finish loading let domwindow = awindow.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsidomwindowinternal || ci.nsidomwindow); domwindow.addeventlistener("load", function () { domwindow.removeeventlistener("load", arguments.
callee, false); //this removes this load function from the window //window has now loaded now do stuff to it //as example this will add a function to listen to tab select and will fire alert in that window if (domwindow.gbrowser && domwindow.gbrowser.tabcontainer) { domwindow.gbrowser.tabcontainer.addeventlistener('tabselect', function () { ...
...but we expect this to be
called from
callbacks originating in native window code.
... native code only!updatewindowtimestamp
call this method when a window gains focus.
...And 2 more matches
Working with out parameters
adata and adatalen are marked as out, meaning that they act as "return values" for this method, and are changed during the method
call.
... these are so-
called out parameters.
...after the
call, this object will have a new property
called value, which contains the out values.
...And 2 more matches
Creating a gloda message query
this content covers features introduced in thunderbird 3 this page describes how to programmati
cally create a message query using gloda, thunderbird's global database.
... 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 */ onitems...
...removed: 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!
...And 2 more matches
Filelink Providers
note: the setup dialog window should resize itself automati
cally in order to fit the content of the iframe without scrollbars.
...for each input event, the checkvalidity method of the form is automati
cally
called.
... saving the preferences is handled automati
cally by the dialog code.
...And 2 more matches
Creating a Custom Column
the column handler now that our column physi
cally exists it's time to give it a bit of personality.
...rest assured that these functions will be
called - so implement them, even with empty function.
... return hdr.getstringproperty("replyto"); }, getsortstringforrow: function(hdr) {return hdr.getstringproperty("replyto");}, isstring: function() {return true;}, getcellproperties: function(row, col, props){}, getrowproperties: function(row, props){}, getimagesrc: function(row, col) {return null;}, getsortlongforrow: function(hdr) {return 0;} } basi
cally, all we are doing here is making sure that both the text that is displayed to the user (getcelltext()) and the string we sort according to (when the user decided to sort the view by our custom column) are identical.
...And 2 more matches
Declaring types
every type is represented by a ctype object, which, in turn, provides a constructor method you can
call to define values of those types.
... var timestr = asctime(thetime.address()); // pass a pointer to the tm struct var jsstring = timestr.readstring(); // convert the c string to javascript the last line converts the c string returned by the libc asctime() function into a javascript string by
calling the cdata readstring() method.
...you can then define the fields in the opaque structure later by
calling the ctype object's define() method.
...And 2 more matches
Version, UI, and Status Information - Plugins
to accomplish this, the plug-in
calls the npn_status method to display your message on the status line.
... the plug-in
calls the npn_useragent method to retrieve the contents of the user_agent field.
... the plug-in
calls the npn_version method to check for changes in major and minor plug-in api version numbers.
...And 2 more matches
Introduction to DOM Inspector - Firefox Developer Tools
if the dom inspector doesn't automati
cally load a document or loads a document other than the one you'd like to inspect, you can select the desired document a few different ways.
...the dom inspector keeps track of all the windows that are open, so to inspect the dom of a particular window in the dom inspector, simply access that window as you would normally and then choose its title from this dynami
cally updated menulist.
...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 automati
cally updated to reflect the information for that node.
...And 2 more matches
AddressErrors - Web APIs
the addresserrors dictionary is used by the payment request api to to report validation errors in a physical address (typi
cally a billing address or a shipping address).
... request.onshippingaddresschange = handleaddresschange; //
call show() to trigger the browser's payment flow.
... after that, we set up the handler for the shippingaddresschange event so we can validate address information and
call the request's show() method to start running the payment ui.
...And 2 more matches
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.
...indeed, you can use these nodes in a "fire and forget" manner: create the node,
call start() to begin playing the sound, and don't even bother to hold a reference to it.
... it will automati
cally be garbage-collected at an appropriate time, which won't be until sometime after the sound has finished playing.
...And 2 more matches
BlobBuilder - Web APIs
just create a blobbuilder and append chunks of data to it by
calling the append() method.
... when you're done building your blob,
call getblob() to retrieve a blob containing the data you sent into the blob builder.
... getblob() returns the blob object that has been constructed using the data passed through
calls to append().
...And 2 more matches
Cache - Web APIs
use cachestorage.open() to open a specific named cache object and then
call any of the cache methods to maintain the cache.
... you are also responsible for periodi
cally purging cache entries.
...this is functionally equivalent to
calling fetch(), then using put() to add the results to the cache.
...And 2 more matches
CanvasRenderingContext2D - Web APIs
basic example to get a canvasrenderingcontext2d instance, you must first have an html <canvas> element to work with: <canvas id="my-house" width="300" height="300"></canvas> to get the canvas' 2d rendering context,
call getcontext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getelementbyid('my-house'); const ctx = canvas.getcontext('2d'); with the context in hand, you can draw anything you like.
...
call this method when you want to create a new path.
...everything drawn after clip() is
called appears inside the clipping path only.
...And 2 more matches
Basic animations - Web APIs
controlling an animation shapes are drawn to the canvas by using the canvas methods directly or by
calling custom functions.
... scheduled updates first there's the window.setinterval(), window.settimeout(), and window.requestanimationframe() functions, which can be used to
call a specific function over a set period of time.
... requestanimationframe(
callback) tells the browser that you wish to perform an animation and requests that the browser
call a specified function to update an animation before the next repaint.
...And 2 more matches
DataTransferItem.getAsString() - Web APIs
the datatransferitem.getasstring() method invokes the given
callback with the drag data item's string data as the argument if the item's kind is a plain unicode string (i.e.
... syntax datatransferitem.getasstring(
callback); parameters
callback a
callback function that has access to the data transfer item's string data.
... see
callback below for details.
...And 2 more matches
Document.getElementsByClassName() - Web APIs
when
called on the document object, the complete document is searched, including the root node.
... you may also
call getelementsbyclassname() on any element; it will return only elements which are descendants of the specified root element with the given class name(s).
... names is a string representing the class name(s) to match; multiple class names are separated by whitespace getelementsbyclassname can be
called on any element, not only on the document.
...And 2 more matches
Element.setAttribute() - Web APIs
to get the current value of an attribute, use getattribute(); to remove an attribute,
call removeattribute().
...the attribute name is automati
cally converted to all lower-case when setattribute() is
called on an html element in an html document.
...any non-string value specified is converted automati
cally into a string.
...And 2 more matches
EventTarget.removeEventListener() - Web APIs
return value undefined matching event listeners for removal given an event listener previously added by
calling addeventlistener(), you may eventually come to a point at which you need to remove it.
... for example, consider this
call to addeventlistener(): element.addeventlistener("mousedown", handlemousedown, true); now consider each of these two
calls to removeeventlistener(): element.removeeventlistener("mousedown", handlemousedown, false); // fails element.removeeventlistener("mousedown", handlemousedown, true); // succeeds the first
call fails because the value of usecapture doesn't match.
... now look at each of these
calls to removeeventlistener() in turn.
...And 2 more matches
FileError - Web APIs
fileerror objects are passed to error
callbacks.
... error
callbacks are not optional for your sanity although error
callbacks are optional, you should include them in the arguments of the methods for the sake of the sanity of your users.
...in fact, many of the powerful storage apis (such as file system, blobbuilder, and filereader) throw errors if you run the app lo
cally from file://.
...And 2 more matches
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 one of those event types is recorded in the browser's performance timeline, the application is notified of the event via the observer's
callback function that was specified when the observer was created.
... to observe "frame" performance entry types, the application first creates a performanceobserver object with a specific frame observer
callback (function).
...And 2 more matches
HTMLCanvasElement.toBlob() - Web APIs
syntax canvas.toblob(
callback, mimetype, qualityargument); parameters
callback a
callback function with the resulting blob object as a single argument.
...nvas'); 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 blob
callback(iconname) { return function(b) { var a = document.createelement('a'); a.textcontent = 'download'; document.body.appendchild(a); a.style.display = 'block'; a.download = iconname + '.ico'; a.href = window.url.createobjecturl(b); } } canvas.toblob(blob
callback('passthisstring'), 'image/vnd.microsoft.icon', '-moz-parse-options:format=bmp;bpp=32'); save ...
...And 2 more matches
HTMLMediaElement.play() - Web APIs
exceptions the promise's rejection handler is
called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown).
... usage notes although the term "autoplay" is usually thought of as referring to pages that immediately begin playing media upon being loaded, web browsers' autoplay policies also apply to any script-initiated playback of media, including
calls to play().
... if the user agent is configured not to allow automatic or script-initiated playback of media,
calling play() will cause the returned promise to be immediately rejected with a notallowederror.
...And 2 more matches
The HTML DOM API - Web APIs
for example, consider a document with two elements, one of which has two more elements nested inside it: while the document interface is defined as part of the dom specification, the html specification significantly enhances it to add information specific to using the dom in the context of a web browser, as well as to using it to represent html documents specifi
cally.
... html element interfaces the element interface has been further adapted to represent html elements specifi
cally by introducing the htmlelement interface, which all more specific html element classes inherit from.
... domstringlist domstringmap errorevent htmlallcollection mimetype mimetypearray promiserejectionevent interfaces belonging to other apis several interfaces are techni
cally defined in the html specification while actually being part of other apis.
...And 2 more matches
Working with the History API - Web APIs
note:
calling history.back() normally behaves the same way as clicking the back button.
... but there is one important exception: after using history.pushstate(),
calling history.back() does not raise a popstate event.
...note that the browser won't attempt to load this url after a
call to pushstate(), but it might attempt to load the url later, for instance after the user restarts the browser.
...And 2 more matches
IdleDeadline - Web APIs
the idledeadline interface is used as the data type of the input parameter to idle
callbacks established by
calling window.requestidle
callback().
... it offers a method, timeremaining(), which lets you determine how much longer the user agent estimates it will remain idle and a property, didtimeout, which lets you determine if your
callback is executing because its timeout duration expired.
... to learn more about how request
callbacks work, see collaborative scheduling of background tasks.
...And 2 more matches
install - Web APIs
method of installtrigger object syntax int install(array xpilist [, function
callbackfunc ] ) parameters the install method has the following parameters: xpilist an array of files to be installed (see example below).
...
callbackfunc an optional
callback function invoked when the installation is complete (see example below).
... firefox 3 note in firefox 3 the
callback is no longer invoked unless the website performing the installation is whitelisted.
...And 2 more matches
MediaDevices.getDisplayMedia() - Web APIs
invalidstateerror the
call to getdisplaymedia() was not made from code running due to a user action, such as an event handler.
... another potential cause for this event: the document in whose context getdisplaymedia() was
called is not fully active; for example, perhaps it is not the frontmost tab.
... typeerror the specified constraints include constraints which are not permitted when
calling getdisplaymedia().
...And 2 more matches
MediaQueryList.addListener() - Web APIs
the addlistener() method of the mediaquerylist interface adds a listener to the mediaquerylistener that will run a custom
callback function in response to the media query status changing.
... this is basi
cally an alias for eventtarget.addeventlistener(), for backwards compatibility purposes.
... syntax mediaquerylist.addlistener(func) parameters func a function or function reference representing the
callback function you want to run when the media query status changes.
...And 2 more matches
MediaQueryList - Web APIs
you can create a mediaquerylist by
calling matchmedia() on the window object.
... this is very useful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodi
cally, and allows you to programmati
cally make changes to a document based on media query status.
... addlistener() adds to the mediaquerylist a
callback which is invoked whenever the media query status—whether or not the document matches the media queries in the list—changes.
...And 2 more matches
MediaRecorder.onerror - Web APIs
the mediarecorder interface's onerror event handler is
called by the mediastream recording api when an error occurs.
... syntax mediarecorder.onerror = errorhandlerfunction; value a function to be
called whenever an error occurs during the recorder's lifetime.
... in addition to other general errors that might occur, the following errors are specifi
cally possible when using the mediastream recording api; to determine which occurred, check the value of mediarecordererrorevent.error.name.
...And 2 more matches
MediaStreamTrack.stop() - Web APIs
syntax track.stop() description
calling stop() tells the user agent that the track's source—whatever that source may be, including files, network streams, or a local camera or microphone—is no longer needed by the mediastreamtrack.
... immediately after
calling stop(), the readystate property is set to ended.
... examples stopping a video stream in this example, we see a function which stops a streamed video by
calling stop() on every track on a given <video>.
...And 2 more matches
MediaTrackSettings.autoGainControl - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.autogaincontrol property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... automatic gain control is a feature in which a sound source automati
cally manages changes in the volume of its source media to maintain a steady overall volume level.
... this feature is typi
cally used on microphones, although it can be provided by other input sources as well.
...And 2 more matches
MediaTrackSettings.groupId - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.groupid property you provided when
calling either getusermedia().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.groupid as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
...And 2 more matches
MediaTrackSettings.noiseSuppression - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.noisesuppression property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... noise suppression automati
cally filters the audio to remove background noise, hum caused by equipment, and the like from the sound before delivering it to your code.
... this feature is typi
cally used on microphones, although it is techni
cally possible it could be provided by other input sources as well.
...And 2 more matches
MutationObserver - Web APIs
constructor mutationobserver() creates and returns a new mutationobserver which will invoke a specified
callback function when dom changes occur.
... methods disconnect() stops the mutationobserver instance from receiving further notifications until and unless observe() is
called again.
... observe() configures the mutationobserver to begin receiving notifications through its
callback function when dom changes matching the given options occur.
...And 2 more matches
OffscreenCanvas - Web APIs
once a new frame has finished rendering in this context, the transfertoimagebitmap() method can be
called to save the most recent rendered image.
... to display the imagebitmap, you can use a imagebitmaprenderingcontext context, which can be created by
calling canvas.getcontext("bitmaprenderer") on a (visible) canvas element.
...a
call to imagebitmaprenderingcontext.transferfromimagebitmap() with the previously rendered and saved imagebitmap from the offscreencanvas, will display the imagebitmap on the canvas and transfer its ownership to the canvas.
...And 2 more matches
PerformanceObserver() - Web APIs
the performanceobserver() constructor creates a new performanceobserver object with the given observer
callback.
... the observer
callback is invoked when performance entry events are recorded for the entry types that have been registered, via the observe() method.
... syntax var observer = new performanceobserver(
callback); parameters
callback a performanceobserver
callback
callback that will be invoked when observed performance events are recorded.
...And 2 more matches
RTCOfferOptions.iceRestart - Web APIs
note: rather than manually creating and submitting an offer with icerestart set to true, you should consider
calling the rtcpeerconnection method restartice() instead.
...you should ideally do this by
calling the rtcpeerconnection's restartice() method, if it's available.
...echange = function(evt) { if (pc.iceconnectionstate === "failed") { if (pc.restartice) { pc.restartice(); } else { pc.createoffer({ icerestart: true }) .then(pc.setlocaldescription) .then(sendoffertoserver); } } } if the state changes to failed, this handler starts by looking to see if the rtcpeerconnection includes the restartice() method; if it does, we
call that to request an ice restart.
...And 2 more matches
RTCRtpStreamStats - Web APIs
while the dictionary has a base set of properties that are present in each of these cases, there are also additional properties added depending on which interface the method is
called on.
... note: this interface was
called rtcrtpstreamstats until a specification update in the spring of 2017.
...previously
called mediatype.
...And 2 more matches
Reporting API - Web APIs
a reportingobserver object is created using the reportingobserver() constructor, which is passed two parameters: a
callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same reportingobserver object, so observation can be controlled directly from inside the
callback.
... the
callback runs when observation starts an options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (buffered: true).
...f 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 the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constraints, success, failure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be gene...
...And 2 more matches
ResizeObserver() - Web APIs
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.
... observer a reference to the resizeobserver itself, so it will definitely be accessible from inside the
callback, should you need it.
...And 2 more matches
Screen Wake Lock API - Web APIs
you acquire a wakelocksentinel object by
calling the navigator.wakelock.request() promise based method that resolves if the platform allows it.
...get an instance of the object by
calling wakelock.request.
...the ui also updates if the wake lock is released automati
cally for any reason.
...And 2 more matches
Using server-sent events - Web APIs
you'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identi
cally to websockets in part of handling incoming events.
... you can also listen for events with addeventlistener(): evtsource.addeventlistener("ping", function(event) { const newelement = document.createelement("li"); const time = json.parse(event.data).time; newelement.innerhtml = "ping at " + time; eventlist.appendchild(newelement); }); this code is similar, except that it will be
called automati
cally whenever the server sends a message with the event field set to "ping"; it then parses the json in the data field and outputs that information.
...you can take action on this programmati
cally by implementing the onerror
callback on the eventsource object: evtsource.onerror = function(err) { console.error("eventsource failed:", err); }; closing event streams by default, if the connection between the client and server closes, the connection is restarted.
...And 2 more matches
Storage API - Web APIs
one of the most likely methods—one which the specification specifi
cally encourages, in fact—would be to consider the popularity and/or usage levels of individual sites to determine what their quotas should be.
... box modes the actual data storage within each site storage unit is
called its box.
... if a box is marked as "persistent", the contents won't be cleared by the user agent without either the data's origin itself or the user specifi
cally doing so.
...And 2 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
this includes whether the text is displayed horizontally or verti
cally.
...there are five cue settings: vertical indicates that the text will be displayed verti
cally rather than horizontally, such as in some asian languages.
... table 1 - vertical values vertical:rl writing direction is right to left vertical:lr writing direction is left to right line specifies where text appears verti
cally.
...And 2 more matches
Using the Web Speech API - Web APIs
speech recognition speech recognition involves receiving speech through a device's microphone, which is then checked by a speech recognition service against a list of grammar (basi
cally, the vocabulary you want to have recognised in a particular app.) when a word or phrase is successfully recognised, it is returned as a result (or list of results) as a text string, and further actions can be initiated as a result.
... demo to show simple usage of web speech recognition, we've written a demo
called speech color changer.
...this is achieved by
calling speechrecognition.start().
...And 2 more matches
Window.close() - Web APIs
the window.close() method closes the current window, or the window on which it was
called.
... this method can only be
called on windows that were opened by a script using the window.open() method.
... note also that close() has no effect when
called on window objects returned by htmliframeelement.contentwindow.
...And 2 more matches
Window.getSelection() - Web APIs
when
called on an <iframe> that is not displayed (eg.
... examples function foo() { var selobj = window.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's tostring() method is
called and the returned value is passed to the function.
... in the above example, selobj.tostring() is automati
cally
called when it is passed to window.alert().
...And 2 more matches
Window.requestFileSystem() - Web APIs
window.requestfilesystem(type, size, success
callback[, error
callback]); parameters type the type of storage to request.
... success
callback a function which is invoked when the file system has been successfully obtained.
... the
callback receives a single parameter: a filesystem object representing the file system the app has permission to use.
...And 2 more matches
XRReferenceSpace: reset event - Web APIs
this is common when the user calibrates or recalibrates an xr device, or if the device automati
cally changes its origin after losing tracking of the user, then re-gaining it.
...the event is sent before any animation frame
callbacks are executed to render the pending frame, to ensure that those
callbacks have the updated coordinate system available.
...when that happens, you typi
cally hold down a button somewhere and it causes the world to resynchronize to the device's current orientation.
...And 2 more matches
XRView - Web APIs
transform read only an xrrigidtransform which describes the current position and orientation of the viewpoint in relation to the xrreferencespace specified when getviewerpose() was
called on the xrframe being rendered.
... usage notes positions and number of xrviews per frame while rendering a scene, the set of views that are used to render the scene for the viewer as of the current frame are obtained by
calling the xrframe object's getviewerpose() method to get the xrviewerpose representing (in essence) the position of the viewer's head.
... all positions and orientations within the views for a given xrviewerpose are specified in the reference space that was passed to xrframe.getviewerpose(); this is
called the viewer reference space.
...And 2 more matches
ARIA live regions - Accessibility
using javascript, it is possible to dynami
cally change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction.
...aria live regions fill this gap and provide a way to programmati
cally expose dynamic content changes in a way that can be announced by assistive technologies.
... including an aria-live attribute or a specialized live region role (such as role="alert") on the element you want to announce changes to works as long as you add the attribute before the changes occur — either in the original markup, or dynami
cally using javascript.
...And 2 more matches
Web applications and ARIA FAQ - Accessibility
along with placing them directly in the markup, aria attributes can be added to the element and updated dynami
cally using javascript code like this: // find the progress bar <div> in the dom.
...progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be
called at any time to update the value of the progress bar.
...instead, use javascript to dynami
cally add aria to your page, as shown in the answer to can you show me an example of aria in action?
...And 2 more matches
Cognitive accessibility - Accessibility
people who are less technologi
cally literate.
... if moving, blinking, scrolling, or auto-updating information starts automati
cally, lasts more than five seconds, and is presented in parallel with other content, the user must able to pause, stop, hide or control it, unless it's an essential functionality.
...enable the user to postpone content updates by providing a way to request content updates rather than updating automati
cally.
...And 2 more matches
Text labels and names - Accessibility
figures with optional captions should be labeled for best accessibility, include a <figcaption> within a <figure> element, even though doing so is techni
cally optional.
...since mglyph elements are used for non-standard symbols without unicode definitions, screen readers won't automati
cally be able to name them.
...screen reader users typi
cally "skim" a page's headings, much like sighted users; non-heading text that is marked-up with heading elements can cause confusion.
...And 2 more matches
Border-radius generator - CSS: Cascading Style Sheets
ue(topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) return; if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setattribute('data-value', value); if (send_notify !== undefined && send_notify === false) { slider.input.value = value + slider.unit; return; } notify.
call(slider); } var setmax = function setmax(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.max = value; setvalue(topic, slider.value); } var setmin = function setmin(topic, value) { var slider = sliders[topic]; if (slider === undefined) return; slider.min = value; setvalue(topic, slider.value); } var setunit = function setunit(to...
...pic, unit) { var slider = sliders[topic]; if (slider === undefined) return; slider.unit = unit; setvalue(topic, slider.value); } var getnode = function getnode(topic) { return sliders[topic].node; } var subscribe = function subscribe(topic,
callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(
callback); } var unsubscribe = function 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++) ...
...type', 'checkbox'); checkbox.checked = state; label.setattribute('for', id); if (name) { label.classname = 'text'; if (align) label.classname += ' ' + align; label.textcontent = name; } node.appendchild(checkbox); node.appendchild(label); this.node = node; this.topic = topic; this.checkbox = checkbox; checkbox.addeventlistener('change', function(e) { notify.
call(this); }.bind(this)); buttons[topic] = this; } var getnode = function getnode(topic) { return buttons[topic].node; } var setvalue = function setvalue(topic, value) { try { buttons[topic].checkbox.checked = value; } catch(error) { console.log(error); } } var subscribe = function subscribe(topic,
callback) { if (subscribers[topic] === undefined) subscribers[topic...
...And 2 more matches
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
each item contains a heading, some text of varying height, and a
call to action link.
... <ul class="listing"> <li> <h2>item one</h2> <div class="body"><p>the content of this listing item goes here.</p></div> <div class="cta"><a href="">
call to action!</a></div> </li> <li> <h2>item two</h2> <div class="body"><p>the content of this listing item goes here.</p></div> <div class="cta"><a href="">
call to action!</a></div> </li> <li class="wide"> <h2>item three</h2> <div class="body"><p>the content of this listing item goes here.</p> <p>this one has more text than the other items.</p> <p>quite a lot more</p> <p>perhaps we could do something different with it?</p></div> <div class="cta"><a href="">
call to action!</a></div> </li> <li> <h2>item four</h2> <div class="body"><p>the content of this listin...
...g item goes here.</p></div> <div class="cta"><a href="">
call to action!</a></div> </li> <li> <h2>item five</h2> <div class="body"><p>the content of this listing item goes here.</p></div> <div class="cta"><a href="">
call to action!</a></div> </li> </ul> * {box-sizing: border-box;} img {max-width: 100%; display: block;} body { font: 1.2em helvetica, arial, sans-serif; } a:link, a:visited { text-decoration: none; color: #f08c00; } h2 { background-color: #f08c00; color: #fff; text-align: center; margin: 0; padding: 20px; } we are going to create a grid with a flexible number of flexible columns.
...And 2 more matches
Visual formatting model - CSS: Cascading Style Sheets
we most often see this as scrolling in the block dimension — verti
cally in a horizontal, top-to-bottom language.
...a box generated by an element with display: block is
called a "block box" or just a "block".
... floats in the float model, a box is first laid out according to the normal flow, then taken out of the flow and positioned, typi
cally to the left or right.
...And 2 more matches
Creating and triggering events - Developer guides
such events are commonly
called synthetic events, as opposed to the events fired by the browser itself.
...he custom "awesome" event and then consoles the output of the passed text() method form.addeventlistener('awesome', e => console.log(e.detail.text())); // as the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.addeventlistener('input', e => e.target.dispatchevent(eventawesome)); creating and dispatching events dynami
cally elements can listen for events that haven't been created yet: <form> <textarea></textarea> </form> const form = document.queryselector('form'); const textarea = document.queryselector('textarea'); form.addeventlistener('awesome', e => console.log(e.detail.text())); textarea.addeventlistener('input', function() { // create and dispatch/trigger an event on the fly // note: optionally, ...
...we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element this.dispatchevent(new customevent('awesome', { bubbles: true, detail: { text: () => textarea.value } })) }); triggering built-in events this example demonstrates simulating a click (that is programmati
cally generating a click event) on a checkbox using dom methods.
...And 2 more matches
Localizations and character encodings - Developer guides
for most locales, the fallback encoding is windows-1252 (often
called iso-8859-1), which was the encoding emitted by most windows applications in the 1990s and a superset of the encoding emitted by most unix applications in the 1990s as a deployed in the america has and in western europe.
...in these locales, legacy content that doesn't declare its encoding is typi
cally encoded using a legacy encoding other than windows-1252.
...it typi
cally needs to be set to something other than windows-1252 for central and eastern european locales, middle eastern locales and east asian locales.
...And 2 more matches
<input type="hidden"> - HTML: Hypertext Markup Language
this specifi
cally can't be edited or seen by the user via the user interface, although you could edit the value via browser developer tools.
...however, when the form is submitted, a hidden input whose name is set to _charset_ will automati
cally be reported with the value set to the character encoding used to submit the form.
...when the form is submitted in step 3, the id is automati
cally sent back to the server with the record content.
...And 2 more matches
<input type="range"> - HTML: Hypertext Markup Language
this is typi
cally represented using a slider or dial control rather than a text entry box like the number input type.
... because this kind of widget is imprecise, it shouldn't typi
cally be used unless the control's exact value isn't important.
...values include horizontal, meaing the range is rendered horizontally, and vertical, where the range is rendered verti
cally.
...And 2 more matches
<tr>: The Table Row element - HTML: Hypertext Markup Language
this uses the char and charoff to establish the alignment character (typi
cally "." or "," when aligning numerical data) and the number of characters that should follow the alignment character.
...for example, when displaying money values for currencies that use hundredths of a unit (such as the dollar, which is divided into 100 cents), you would typi
cally specify a value of 2, so that in tandem with char being set to ".", the values in a column would be cleanly aligned on the decimal points, with the number of cents properly displayed to the right of the decimal point.
... middle each cell's text is verti
cally centered.
...And 2 more matches
MIME types (IANA media types) - HTTP
examples include message/rfc822 (for forwarded or replied-to message quoting) and message/partial to allow breaking a large message into smaller ones automati
cally to be reassembled by the recipient.
...specifi
cally if they download a text/plain file from a <link> element declaring a css file, they will not recognize it as a valid css file if presented with text/plain.
...the codecs used by webrtc guide expands upon this by specifi
cally covering the codecs supported by the major web browsers, so you can choose the codecs that best cover the range of browsers you wish to support.
...And 2 more matches
HTTP conditional requests - HTTP
such values are
called validators, and are of two kinds: the date of last modification of the document, the last-modified date.
... an opaque string, uniquely identifying each version,
called the entity tag, or the etag.
... conditional headers several http headers,
called conditional headers, lead to conditional requests.
...And 2 more matches
HTTP Messages - HTTP
get http://developer.mozilla.org/docs/web/http/messages http/1.1 the authority component of a url, consisting of the domain name and optionally the port (prefixed by a ':'), is
called the authority form.
...this is typi
cally associated with html forms.
... http responses status line the start line of an http response,
called the status line, contains the following information: the protocol version, usually http/1.1.
...And 2 more matches
JavaScript data types and data structures - JavaScript
a bigint is created by appending n to the end of an integer or by
calling the constructor.
...in some programming languages, symbols are
called "atoms".
... accessor property associates a key with one of two accessor functions (get and set) to retrieve or store a value, and has the following attributes: attributes of an accessor property attribute type description default value [[get]] function object or undefined the function is
called with an empty argument list and retrieves the property value whenever a get access to the value is performed.
...And 2 more matches
Public class fields - JavaScript
static methods aren't
called on instances of the class.
... instead, they're
called on the class itself.
... class classwithstaticmethod { static staticmethod() { return 'static method has been
called.'; } } console.log(classwithstaticmethod.staticmethod()); // expected output: "static method has been
called." the static methods are added to the class constructor with object.defineproperty() at class evaluation time.
...And 2 more matches
TypeError: Reduce of empty array with no initial value - JavaScript
these functions optionally take an initialvalue (which will be used as the first argument to the first
call of the
callback).
... similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list: var names = document.getelementsbyclassname("names"); var name_list = array.prototype.reduce.
call(names, (acc, name) => acc + ", " + name); valid cases these problems can be solved in two different ways.
... var ints = [0, -1, -2, -3, -4, -5]; ints.filter(x => x > 0) // removes all elements .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition another way would be two to handle the empty case, either before
calling reduce, or in the
callback after adding an unexpected dummy initial value.
...And 2 more matches
TypeError: invalid 'instanceof' operand 'x' - JavaScript
an object which has a prototype property and is
callable.
... message typeerror: invalid 'instanceof' operand "x" (firefox) typeerror: "x" is not a function (firefox) typeerror: right-hand side of 'instanceof' is not an object (chrome) typeerror: right-hand side of 'instanceof' is not
callable (chrome) error type typeerror what went wrong?
...an object which has a prototype property and is
callable.
...And 2 more matches
Array.prototype.indexOf() - JavaScript
if (!array.prototype.indexof) array.prototype.indexof = (function(object, max, min) { "use strict" return function indexof(member, fromindex) { if (this === null || this === undefined) throw typeerror("array.prototype.indexof
called on null or undefined") var that = object(this), len = that.length >>> 0, i = min(fromindex | 0, len) if (i < 0) i = max(0, len + i) else if (i >= len) return -1 if (member === void 0) { // undefined for (; i !== len; ++i) if (that[i] === void 0 && i in that) return i } else if (member !== member) { // nan return -1 // since nan !== nan, it ...
...let o be the result of
calling toobject passing // the this value as the argument.
...let lenvalue be the result of
calling the get // internal method of o with the argument "length".
...And 2 more matches
Array.prototype.pop() - JavaScript
description the pop method removes the last element from an array and returns that value to the
caller.
... pop is intentionally generic; this method can be
called or applied to objects resembling arrays.
... if you
call pop() on an empty array, it returns undefined.
...And 2 more matches
Array.prototype.push() - JavaScript
return value the new length property of the object upon which the method was
called.
...this method can be used with
call() or apply() on objects resembling arrays.
...instead, we store the collection on the object itself and use
call on array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way javascript allows us to establish the execution context in any way we want.
...And 2 more matches
Array.prototype.reverse() - JavaScript
description the reverse method transposes the elements of the
calling array object in place, mutating the array, and returning a reference to the array.
... reverse is intentionally generic; this method can be
called or applied to objects resembling arrays.
...the
call to reverse() returns a reference to the reversed array a.
...And 2 more matches
Array - JavaScript
several of the built-in array methods (e.g., join(), slice(), indexof(), etc.) take into account the value of an array's length property when they're
called.
... array.prototype.filter() returns a new array containing all elements of the
calling array for which the provided filtering function returns true.
... array.prototype.foreach()
calls a function for each element in the array.
...And 2 more matches
Date.prototype[@@toPrimitive] - JavaScript
if hint is "string" or "default", [@@toprimitive]() tries to
call the tostring method.
... if the tostring property does not exist, it tries to
call the valueof method and if the valueof does not exist either, [@@toprimitive]() throws a typeerror.
... if hint is "number", [@@toprimitive]() first tries to
call valueof, and if that fails, it
calls tostring.
...And 2 more matches
Object.prototype.valueOf() - JavaScript
description javascript
calls the valueof method to convert an object to a primitive value.
... you rarely need to invoke the valueof method yourself; javascript automati
cally invokes it when encountering an object where a primitive value is expected.
...when you create a custom object, you can override object.prototype.valueof() to
call a custom method instead of the default object method.
...And 2 more matches
RegExp.prototype[@@replace]() - JavaScript
the replacement can be a string or a function to be
called for each match.
... description this method is
called internally in string.prototype.replace() if the pattern argument is a regexp object.
... if pattern argument is not a regexp object, string.prototype.replace() doesn't
call this method, nor creates a regexp object.
...And 2 more matches
String.prototype.normalize() - JavaScript
description unicode assigns a unique numerical value,
called a code point, to each character.
... you can use normalize() using the "nfd" or "nfc" arguments to produce a form of the string that will be the same for all canoni
cally equivalent strings.
... all canoni
cally equivalent sequences are also compatible, but not vice versa.
...And 2 more matches
String.prototype.replaceAll() - JavaScript
the pattern can be a string or a regexp, and the replacement can be a string or a function to be
called for each match.
... 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".
...a regexp without the global ("g") flag will throw a typeerror: "replaceall must be
called with a global regexp".
...And 2 more matches
Logical AND (&&) - JavaScript
it is typi
cally used with boolean (logical) values.
... if a value can be converted to true, the value is so-
called truthy.
... if a value can be converted to false, the value is so-
called falsy.
...And 2 more matches
Logical OR (||) - JavaScript
it is typi
cally used with boolean (logical) values.
... if a value can be converted to true, the value is so-
called truthy.
... if a value can be converted to false, the value is so-
called falsy.
...And 2 more matches
Spread syntax (...) - JavaScript
spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
... 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.
... examples spread in function
calls replace apply() it is common to use function.prototype.apply() in cases where you want to use the elements of an array as arguments to a function.
...And 2 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 normal function
calls, new.target is undefined.
... examples new.target in function
calls in normal function
calls (as opposed to constructor function
calls), new.target is undefined.
...And 2 more matches
async function - JavaScript
for example: async function foo() { await 1 } ...is equivalent to: function foo() { return promise.resolve(1).then(() => undefined) } code after each await expression can be thought of as existing in a .then
callback.
...progress through foo is then suspended and control is yielded back to the function that
called foo.
... however, the await
calls still run in series, which means the second await will wait for the first one to finish.
...And 2 more matches
Populating the page: how browsers work - Web Performance
if you’ve ever heard of the 14kb rule for initial page load, tcp slow start is the reason why the initial response is 14kb, and why web performance optimization
calls for focusing optimizations with this initial 14kb response in mind.
... the first time the size and position of nodes are determined is
called layout.
... subsequent recalculations of node size and locations are
called reflows.
...And 2 more matches
Optimizing startup performance - Web Performance
the source application might have a main loop that can easily be made to operate asynchronously (by running each main loop iteration separately); startup is often just a continuous, monolithic procedure that might periodi
cally update a progress meter.
...in addition, the browser may automati
cally parallelize these decoders.
...the most important thing to do to try to help with the main code's startup process is to refactor the code into small pieces that can be done in chunks interspersed across multiple
calls to your app's main loop, so that the main thread gets to handle input and the like.
...And 2 more matches
Types of attacks - Web security
(click-jacking is sometimes
called "user interface redressing", though this is a misuse of the term "redress".) cross-site request forgery (csrf) cross-site scripting (xss) cross-site scripting (xss) is a security exploit which allows an attacker to inject into a website malicious client-side code.
... xss attacks can be put into three categories: stored (also
called persistent), reflected (also
called non-persistent), or dom-based.
...for endpoints that require a post request, it's possible to programmati
cally trigger a <form> submit (perhaps in an invisible <iframe>) when the page is loaded: <form action="https://bank.example.com/withdraw" method="post"> <input type="hidden" name="account" value="bob"> <input type="hidden" name="amount" value="1000000"> <input type="hidden" name="for" value="mallory"> </form> <script>window.addeventlistener('domcontentloaded', (e) => { document.queryselector('...
...And 2 more matches
Introduction to using XPath in JavaScript - XPath
this adapter works like the dom level 3 method lookupnamespaceuri on nodes in resolving the namespaceuri from a given prefix using the current information available in the node's hierarchy at the time lookupnamespaceuri is
called.
...es the xpath expression count(//p) to obtain the number of <p> elements in an html document: var paragraphcount = document.evaluate( 'count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.numbervalue + ' paragraph elements' ); although javascript allows us to convert the number to a string for display, the xpath interface will not automati
cally convert the numerical result if the stringvalue property is requested, so the following code will not work: var paragraphcount = document.evaluate('count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.stringvalue + ' paragraph elements' ); instead, it will return an exception with the code ns_dom_type_error.
...after iterating through all the h2 elements returned from our expression, any further
calls to iteratenext() will return null.
...And 2 more matches
An Overview - XSLT: Extensible Stylesheet Language Transformations
although xsl is the conventionally used shorthand name (
called the prefix), it is not mandatory and it is quite possible to choose a different one.
... the xslt transformation engine,
called the processor, does not work directly on documents.
...this representation,
called the tree, is what is actually manipulated by the processor.
...And 2 more matches
Converting WebAssembly text format to wasm - WebAssembly
histori
cally, a .wast extension was also used, however that's now used for the scripting language used by the webassembly testsuite.
... a first look at the text format let’s look at a simple example of this — the following program imports a function
called imported_func from a module
called imports, and exports a function
called exported_func: (module (func $i (import "imports" "imported_func") (param i32)) (func (export "exported_func") i32.const 42
call $i ) ) the webassembly function exported_func is exported for use in our environment (e.g.
...when it is
called, it
calls an imported javascript function
called imported_func, which is run with the value (42) provided as a parameter.
...And 2 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
$ git clone https://github.com/webmproject/libwebp to start off simple, expose webpgetencoderversion() from encode.h to javascript by writing a c file
called webp.c: #include "emscripten.h" #include "src/webp/encode.h" emscripten_keepalive int version() { return webpgetencoderversion(); } this is a good simple program to test whether you can get the source code of libwebp to compile, as it doesn't require any parameters or complex data structures to invoke this function.
...
call encoder ...
...it is time to
call the webp encoder to do its job.
...And 2 more matches
port - Archive of obsolete content
it may be
called with any number of parameters, but is most likely to be
called with a name for the message and an optional payload.
...the button sends the content script a message
called "get-first-para" when it is clicked: // main.js pageworker = require("sdk/page-worker").page({ contentscriptfile: require("sdk/self").data.url("listener.js"), contenturl: "http://en.wikipedia.org/wiki/chalk" }); require("sdk/ui/button/action").actionbutton({ id: "get-first-para", label: "get-first-para", icon: "./icon-16.png", onclick: function() { console.log("sending 'get-f...
...when it receives this message, the script logs the first paragraph of the document and then
calls removelistener() to stop listening.
...when messages are sent their payloads are automati
cally serialized, and when messages are received their payloads are automati
cally deserialized, so you don't need to worry about serialization.
page-worker - Archive of obsolete content
in the sdk these scripts are
called "content scripts" because they're explicitly used for interacting with web content.
...we can
call this "trusted" content, because unlike content loaded from a source outside the add-on, the add-on author knows exactly what it's doing.
... so given an add-on that loads trusted content and uses content scripts to access it, there are typi
cally three changes you have to make, if you want to use normal page scripts instead: in the content script: change occurrences of self to addon.
... the page worker is loaded as soon as the page object is created and stays loaded until its destroy method is
called or the add-on is unloaded.
request - Archive of obsolete content
examples outlined in this document are no longer relevent in regards to the twitter api
calls and need to be updated make simple network requests.
... oncomplete function this function will be
called when the request has received a response (or in terms of xhr, when readystate == 4).
...optionally the user may specify a collection of headers and content to send alongside the request and a
callback which will be executed once the request completes.
... once a request object has been created a get request can be executed by
calling its get() method, a post request by
calling its post() method, and so on.
io/text-streams - Archive of obsolete content
writeasync(str,
callback) writes a string on a background thread.
...
callback :
callback
callback, if given, must be a function.
... it's
called as
callback(error) when the write completes.
...inside
callback, this is the textwriter object.
Modifying Web Pages Based on URL - Archive of obsolete content
for example, if we save the script above under the add-on's data directory in a file
called my-script.js: // import the page-mod api var pagemod = require("sdk/page-mod"); // import the self api var self = require("sdk/self"); // 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", contentscriptfile: self.data.url("my-script.js") }); or from firefox 34 onwards: // i...
... communicating with the content script your add-on script and content scripts can't directly access each other's variables or
call each other's functions, but they can send each other messages.
... to send a message from one side to the other, sender
calls port.emit() and receiver listens using port.on().
...ript replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentscriptfile: self.data.url("my-script.js"), // send the content script a message inside onattach onattach: function(worker) { worker.port.emit("replacepage", "page matches ruleset"); } }); the replacepage message isn't a built-in message: it's a message defined by the add-on in the port.emit()
call.
Modifying the Page Hosted by a Tab - Archive of obsolete content
for example, if we save the script above under the add-on's data directory in a file
called my-script.js: var self = require("sdk/self"); var button = require("sdk/ui/button/action").actionbutton({ id: "style-tab", label: "style tab", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").activetab.attach({ contentscriptfile: self.data.url("my-script.js") }); } }); you can load more than one script, and the scripts can interact directly with each ...
...actionbutton({ id: "load-several", label: "load several scripts", icon: "./icon-16.png", onclick: function () { tabs.activetab.attach({ contentscriptfile: [self.data.url('first.js'), self.data.url('second.js')] }); } }); communicating with the content scripts your add-on script and content scripts can't directly access each other's variables or
call each other's functions, but they can send each other messages.
... to send a message from one side to the other, sender
calls port.emit() and receiver listens using port.on().
...n = require("sdk/ui/button/action").actionbutton({ id: "style-tab", label: "style tab", icon: "./icon-16.png", onclick: function() { var worker = tabs.activetab.attach({ contentscriptfile: self.data.url("my-script.js") }); worker.port.emit("drawborder", "red"); } }); the drawborder message isn't a built-in message, it's one that this add-on defines in the port.emit()
call.
Using third-party modules (jpm) - Archive of obsolete content
the current tool is
called jpm, and is based on node.js.
... 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".
... you'll now see a new directory in "my-menuitem"
called "node_modules".
Dialogs and Prompts - Archive of obsolete content
passing arguments and displaying a dialog the following code demonstrates how to pass custom arguments to a dialog, process those arguments in the dialog, and return user-modified arguments to the
caller.
...typi
cally, nothing is done here.
...e://myext/content/mydialog.js"/> <grid> <columns><column/><column/></columns> <rows> <row align="center"><label value="name:"/><textbox id="name"/></row> <row align="center"><label value="description:"/><textbox id="description"/></row> <row align="center"><spacer/><checkbox id="enabled" label="check to enable"/></row> </rows> </grid> </dialog> mydialog.js: //
called once when the dialog displays function onload() { // use the arguments passed to us by the
caller document.getelementbyid("name").value = window.arguments[0].inn.name; document.getelementbyid("description").value = window.arguments[0].inn.description; document.getelementbyid("enabled").checked = window.arguments[0].inn.enabled; } //
called once if and only if the user clicks ok functio...
... // notice if user clicks cancel, window.arguments[0].out remains null // because this function is never
called window.arguments[0].out = {name:document.getelementbyid("name").value, description:document.getelementbyid("description").value, enabled:document.getelementbyid("enabled").checked}; return true; } see also passing parameter to a dialog and getting return values from it.
JS XPCOM - Archive of obsolete content
an interface is simply a list of constants and methods that can be
called on the object, an example is nsifile.
... 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).
...la.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.
... getting an xpcom service var preferences = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice); you can then
call any methods in the nsiprefservice interface on the preferences object.
Local Storage - Archive of obsolete content
others feel concerned about privacy and storing private information lo
cally without deleting it.
...the logger is
called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above.
...don't log inside functions that are
called too often, such as mouseover event handlers, or certain http activity listeners.
...they allow you to automati
cally generate xul content using information from a datasource, and automati
cally update the content once the datasource changes.
Using Dependent Libraries In Extension Components - Archive of obsolete content
the basic strategy of the stub is to dynami
cally load the dependent libraries, then load the component library and continue registration.
...we want to load the dependent libraries // of the real component, then the component itself, and
call nsgetmodule on // the component.
...we want to load the dependent libraries // of the real component, then the component itself, and
call nsgetmodule on // the component.
...// deprecated api
calls have been removed.
Search Extension Tutorial (Draft) - Archive of obsolete content
in particular, changing the location bar search keyword url in a way which is not automati
cally reset when the add-on is removed will result in a reset prompt for users.
...the most techni
cally sound method of achieving this, and the only acceptable way of changing preferences such that they are automati
cally restored on add-on uninstall, is to make such changes in the default preference branch, as explained below.
...adding a new search engine search engines may be added either directly via an api
call, or indirectly via an xml description file.
... catch (e) {} } // observer
called after our engine has been successfully added function searchobserver(engine, topic, data) { if (data != "engine-added") return; engine.queryinterface(ci.nsisearchengine); if (engine.name == engine_details.name) { // remove our observer now that we're done with it.
Creating a Web based tone generator - Archive of obsolete content
this function is
called at a certain interval through the setinterval() function.
... the function mozwriteaudio() is
called to write those samples produced in the audio stream.
... 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 currentposition = audio.mozcurrentsampleoffset(); var available = currentposition + prebuffersize - currentwriteposition; if(available > 0) { // request some sound data from the
callback function.
Source code directories overview - Archive of obsolete content
although not required, these common names are typi
cally used for a common purpose.
... tools contains scripts for automati
cally generating certain source code and other special tools for building this module.
....png, .gif), allowing drop-in java virtual machines (
called oji, for "open java interface"), supporting plug-ins and reading various compression formats (e.g.
...xpcom is the mechanism that allows mozilla to export interfaces and have them automati
cally available to javascript scripts, to microsoft com and to regular mozilla c code.
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
the control itself is implemented in a dll
called pluginhostctrl.dll which is standalone from the rest of the mozilla project.
... if you're wondering how microsoft used to support the np api, look for a file
called plugin.ocx in your windows system directory.
...you may optionally specify a codebase attribute if you have packaged the control into a cab file and wish for it to be installed automati
cally.
...if you need scripting functionality, consider shipping a modified pluginhostctrl.dll that exposes methods you wish to
call on your plugin.
Bookmark Keywords - Archive of obsolete content
practi
cally every web surfer has bookmarks, of course, and power surfers usually have hundreds stuffed into folders within folders.
...mozilla will automati
cally expand the keyword to the corresponding bookmarked url, and load up the site.
...in figure 2, we can see the bookmark has been filed into a folder
called "widgets." you can create a folder with another name, or not put your keymarks into a folder at all.
...however, the two should not be a case-sensitive match-- that is, if your keyword is av, then your title should be "av" or "av" or anything besides "av." (see bugzilla entry 119201 for details.) since this bookmark is intended to look up bugzilla entries, we'll
call it "bz," as shown in figure 3.
Download Manager preferences - Archive of obsolete content
browser.download.manager.closewhendone a boolean value indicating whether or not the downloads window should close automati
cally when downloads are completed.
...0 indicates that the downloads should be paused and resumed automati
cally the next time firefox is run; 1 indicates that the downloads should be paused but will not automati
cally resume when the application is restarted; and 2 indicates that the downloads will be canceled on quit.
...0 indicates that the download should be removed upon completion; 1 indicates that completed and canceled downloads should be removed on quit; 2 indicates that downloads should never be removed automati
cally.
... browser.download.usedownloaddir a boolean value that indicates whether or not the user's preference is to automati
cally save files into the download directory.
Layout System Overview - Archive of obsolete content
this presentation is typi
cally formatted in accordance with the requirements of the css1 and css2 specifications from the w3c.
...the css formatting requirements present two distinct layout models: 1) the in-flow model, where the geometry of an element is influenced by the geometry of the elements that precede it, and 2) the positioned model, where the geometry of an element is not influenced by the geometry of the elements that precede it, or in any case, is influenced more lo
cally.
...the later case,
called 'out of flow' puts the document author in control of the layout, and the author must specify the locations and sizes of all of the elements that are positioned.
...additionally, the presshell provides a specialized storage heap for frames,
called an arena, that is used to make allocation and deallocation of frames faster and less likely to fragment the global heap.
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.
... of course, this strategy only works when your strings either do not need localization, or are programmati
cally localizable (for example, simply adding the locale to a url, like http://<locale>.example.com/).
...they allow for upgrades to be delivered by mozilla specifi
cally for your distribution, if need be, and because of that they are the most important preferences you need to set.
...click the "choose" button to select the xpi file containing your extension; the id and name fields will be filled out automati
cally.
Me - Archive of obsolete content
onfirstrun() accepts a
callback which is
called after installation.
... note that this mechanism is independent of the first-run page; in particular, the
callback is not a load event listener or jquery ready
callback.
... onfirstrun() may be
called anywhere in your jetpack, but if it is
called as the result of some asynchronous operation such as a timeout or xmlhttprequest, it is ignored.
... if you
call it multiple times, all but the final
call are ignored.
LIR - Archive of obsolete content
ldf2d double load float and extend to a double store 25 sti2c void store int truncated to char 26 sti2s void store int truncated to short 27 sti void store int 28 stq void 64 bit store quad 29 std void store double 30 std2f void store double as a float (losing precision) 31 not in use
call 32 not in use 33
callv void
call subroutine that returns void 34
calli integer
call subroutine that returns an int 35
callq quad 64 bit
call subroutine that returns a quad 36
calld double
call subroutine that returns a double branch 37 j void jump always 38 jt void jump if true 39 jf void ...
...the back-ends cannot generate code for it.it's used in tracemonkey briefly but is always demoted to a lir_modl or converted to a function
call before nanojit has to do anything serious with it.
...uad 64 bit add quad and branch on overflow 123 subjovq quad 64 bit subtract quad and branch on overflow softfloat 124 dlo2i integer softfloat get the low 32 bits of a double as an int 125 dhi2i integer softfloat get the high 32 bits of a double as an int 126 ii2d double softfloat join two ints (1st arg is low bits, 2nd is high) 127 h
calli integer lir_h
calli is a hack that's only used on 32-bit platforms that use softfloat.
... its operand is always a lir_
calli, but one that specifies a function that returns a double.
Scripting - Archive of obsolete content
the web application bundle is allowed to hold a javascript file named webapp.js (
called the webapp script).
... prism exposes desktop integration features through an property of the window object
called platform.
...methods of the window.platform object can be
called from webapp.js or from web content.
...this level of functionality is commonly
called chrome-level privileges.
Prism - Archive of obsolete content
prism is based on a concept
called site-specific browsers (ssb).
...refractor adds a new menu item to
call up the shortcut creation dialog for inside firefox.
...refractor automati
cally takes this information into account.
...bundles can be installed lo
cally, or directly from a website using the prism for firefox extension.
Creating XPI Installer Modules - Archive of obsolete content
this new packaging scheme is
called xpi (pronounced "zippy"), and interacts with xpinstall.
... a xpi file typi
cally contains the resources to be installed (in this case the barley.jar we want to have installed in the mozilla/bin/chrome/ directory) and an install script that guides the installation process.
...mozilla is alerted to these content specifications and the resources they manage either through registration as part of an installation process (as described in this tutorial) or by way of a shortcut file
called installed-chrome.txt, in which developers can point at their new contents.rdf files and have them registered as they develop (a process we do not describe here).
...one of the buttons, labeled "show aphids", displays an alert dialog by
calling a function defined in the javascript file barley.js.
Install Wizards (aka: Stub Installers) - Archive of obsolete content
an installer package is an archive file (
called xpi--pronounced "zippies"--because of its .xpi extensions) in phil katz zip format.
...it then proceeds to extract the xpinstall engine and feed it the downloaded software packages to install.) the stub installer code includes: the logic to display the install wizard widgets and dialogs the code that reads in the configuration file (config.ini) and dynami
cally installs from the net or from local xpi modules found next to the installer binary the code that processes user selections the code that
calls the xpinstall engine through xpistub the libxpnet code that is stati
cally linked in the stub installers are written in code native to the platform using native widget toolkits including the windows api for windows, the mac toolbox for the mac, and gtk...
... the xpinstall engine is not
called directly by the stub installer.
... the stub installer
calls some glue code: xpistub which resides at: < http://lxr.mozilla.org/seamonkey/sou...pinstall/stub/> this "glue" code initialized xpcom and registers the xpinstall engine and requisite components to prepare for use by the stub installer.
initInstall - Archive of obsolete content
you must
call this method immediately after the constructor.
... it is an error to
call any other install methods before
calling initinstall.
... after
calling initinstall, your script must
call performinstall or cancelinstall before it finishes.
... if your script does not
call performinstall or cancelinstall, netscape 6 will not be able to clean up properly after your script finishes.
onpopuphidden - Archive of obsolete content
example: <menupopup id="top" onpopuphidden="console.log('the onpopuphidden method of id=top was
called.');"> <menuitem label="item 1"/> <menuitem label="item 2"/> <menu id="submenu1" label="submenu 1"> <menupopup id="submenu1-popup"> <menuitem label="submenu1 item 1"/> <menuitem label="submenu1 item 2"/> </menupopup> </menu> <menu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2...
... item 2"/> </menupopup> </menu> <menupopup/> with the above structure, the onpopuphidden method of <menupopup id="top"> will be
called every time either <menupopup id="submenu1-popup"> or <menupopup id="submenu2-popup"> are hidden.
... this results in the method repeatedly
called as the user runs the mouse up and down the menu opening the sub-menus.
... you can test for the current popup actually being hidden with: <menupopup id="top" onpopuphidden="if(this.state != 'open'){console.log('the onpopuphidden method of id=top was
called.');};" > ...
Reading from Files - Archive of obsolete content
next, nsiscriptableio.newinputstream() is
called to create a new input stream for reading from the file.
...this is done automati
cally as long as you specify the 'text' flag to nsiscriptableio.newinputstream().
...the readstring method is
called to read a 20 character string from the file.
...you can use the available method to check if data is available for reading: var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); var str = stream.readstring(stream.available()); stream.close(); in this example, the available method is
called to determine the number of available bytes for reading.
MenuModification - Archive of obsolete content
<script> function addtomenu() { var menu = document.getelementbyid("edit-menu"); menu.appenditem("insert", "insert"); } </script> <menu id="edit-menu"/> <button label="add" oncommand="addtomenu()"/> in this example, the addtomenu function is
called when the button is pressed.
...also, need replace newmenu.label= "new" by newmenu.setattribute("label", "new"); (all when creating from bootstrap.js in a bootstrapped addon) the addsubmenu function is
called during the popupshowing event, which will be fired when an attempt to open the menu is made.
...the effect is that a submenu with two items is added dynami
cally to the menu.
...the first time the function is
called, the haschildnodes method will return false, however the second time, the method will return true as the items have already been added to the menu.
OpenClose - Archive of obsolete content
opening menus menus will display themselves automati
cally when needed without extra work.
... closing menus menus will close automati
cally once the user has made a selection from the menu.
... the openpopup method regardless of the type of popup, you may wish to open the popup programati
cally.
...it should be obvious from how you are
calling openpopup what to set this argument to.
Panels - Archive of obsolete content
closing a panel a panel is closed automati
cally when the user clicks outside of the panel.
... add a button which closes the panel when pressed: <script> function dosearch() { document.getelementbyid("search-panel").hidepopup(); } </script> <toolbarbutton label="search" type="panel"> <panel id="search-panel" position="after_start"> <textbox id="search"/> <button label="search" oncommand="dosearch();"/> </panel> </toolbarbutton> in this example, the dosearch() function is
called when the "search" button is pressed.
... this function retrieves the popup and
calls the hidepopup method.
... preventing panels from automati
cally closing a panel will be closed when a user clicks outside of the panel or when the escape key is pressed.
Result Generation - Archive of obsolete content
the text in red are the labels for the arrows,
called predicates.
...in xul template terminology, the starting point is
called the container or reference point and the endpoint is
called the member.
... it is so
called because it is most common to gather the list of the members, or children, of a container.
...the builder begins with a single possible result,
called the seed.
SQLite Templates - Archive of obsolete content
in this case, you will often be setting the datasources attribute dynami
cally after determining the file path.
...sqlite files typi
cally have the 'sqlite' extension.
... as with xml datasources, the ref attribute isn't currently used for sqlite sources, so you should just set the ref attribute to a dummy value; '*' is typi
cally used.
...the resulting query that gets used will be: select name, email from myfriends where gender = 'male' this technique is used as quotes or other special characters are handled automati
cally.
Accesskey display rules - Archive of obsolete content
xul elements display their accesskeys in their label automati
cally if it's necessary.
... this document
calls the appended text "accesskey text".
...because typi
cally, japanese language doesn't use spaces as word separator.
... when you cannot use dtd, e.g., when you need to generate some uis dynami
cally, you can use .properties file or something.
Grids - Archive of obsolete content
flexibility of grids one advantage that grids have over a set of nested boxes is that you can create cells that are flexible both horizontally and verti
cally.
...in addition, every cell will be flexible verti
cally because both rows are flexible, although the first row is more so.
... the cell in the first column and first row (the cherry button) will be flexible by a factor of 5 horizontally and flexible by a factor of 10 verti
cally.
... the next cell, (lemon) will only be flexible verti
cally.
Open and Save Dialogs - Archive of obsolete content
to add filters,
call the appendfilters() function to set the file types that you wish to have displayed.
...you can
call appendfilter as many times as necessary to add additional filters.
...typi
cally, the first one added is selected by default.
... getting the selected file finally, you can show the dialog by
calling the show() function.
Splitters - Archive of obsolete content
splitter element this feature is accomplished using an element
called a splitter.
...when a splitter is placed inside a vertical box, it will allow resizing verti
cally.
...the content of the frame is contained in a file
called 'results.html'.
...it should be noted that the window does not resize itself automati
cally.
Tabboxes - Archive of obsolete content
tabboxes tabboxes are typi
cally used in an application in the preferences window.
... tabbox example example 1 : source view <tabbox> <tabs> <tab label="mail"/> <tab label="news"/> </tabs> <tabpanels> <tabpanel id="mailtab"> <checkbox label="automati
cally 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'.
...in this case, the page with the check box labeled 'automati
cally check for mail' will appear.
... for example, to place the tabs along the left side, change the orientation of the tabs element to vertical to make the tabs appear verti
cally stacked.
The Chrome URL - Archive of obsolete content
another advantage over other url types is that they automati
cally handle multiple themes and locales.
...the chrome urls are independent of where the files might physi
cally be located.
...this type of reference will automati
cally select an appropriate file from that right directory.
...while it is common to put the content files in a directory
called 'content', this is purely out of convention, and these files may be placed in an entirely different structure.
Using Spacers - Archive of obsolete content
(java uses layout managers for example.) xul provides the capability for elements to position and resize automati
cally.
...xul uses a layout system
called the 'box model'.
...in this syntax above, the spacer has one attribute,
called flex.
...you may have noticed that when you resize the find file dialog verti
cally, the buttons resize themselves to fit the height of the window.
XPCOM Examples - Archive of obsolete content
em) { var mediator = components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"].getservice(); mediator.queryinterface(components.interfaces.nsiwindowdatasource); var resource = elem.getattribute('id'); switchwindow = mediator.getwindowforresource(resource); if (switchwindow){ switchwindow.focus(); } } </script> a command handler was added to the menu element which
calls the function switchfocus() with a parameter of the element that was selected from the menu.
... this means that you can
call any of the functions provided by it, one of which is the focus() function.
... var iter = cookiemanager.enumerator; while (iter.hasmoreelements()){ var cookie = iter.getnext(); if (cookie instanceof components.interfaces.nsicookie){ if (cookie.host == "www.mozillazine.org") menu.appenditem(cookie.name,cookie.value); } } } </script> <hbox> <menulist id="cookiemenu" onpopupshowing="getcookies();"/> </hbox> the getcookies() function will be
called whenever the menu is opened, as indicated by the onpopupshowing attribute on the menulist.
...this is done because getcookies() is
called every time the menu is opened and we don't want to leave the old items there each time.
browser - Archive of obsolete content
get firefox most of the properties and methods of the browser will rarely be used and can only be
called from chrome urls.
... droppedlinkhandler type: function this function is
called when links are dropped to the browser element, with the following arguments.
...most of its methods are
callable directly on the element itself, such as goback and goforward.
... (see nsiwebnavigation.loaduri() for details on the referrer and postdata parameters.) reload() return type: no return value reloads the document in the browser element on which you
call this method.
command - Archive of obsolete content
it will be
called no matter how it is invoked by the user.
... in addition, disabling the command will automati
cally disable the menu items and keyboard shortcuts.
...typi
cally, this will be the currently focused element.
... oncommand type: script code this event handler is
called when the command is activated.
dialog - Archive of obsolete content
the buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automati
cally.
...typi
cally, this means that the button will be activated when the enter key is pressed.
...the buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automati
cally.
...typi
cally, this means that the button will be activated when the enter key is pressed.
tab - Archive of obsolete content
this is automati
cally set when needed and you shouldn't adjust it manually.
...this is set automati
cally set when needed and you shouldn't adjust it manually.
...this typi
cally means that the tab is in the process of appearing or disappearing.
... oncommand type: script code this event handler is
called when the command is activated.
tabbrowser - Archive of obsolete content
onnewtab not in firefox type: script code this script will be
called when the new tab button is clicked.
...most of its methods are
callable directly on the element itself, such as goback and goforward.
...there's also no owner parameter as the owner tab is specified automati
cally.
... reload() return type: no return value reloads the document in the browser element on which you
call this method.
toolbarbutton - Archive of obsolete content
typi
cally, it is expected to have an image.
... oncommand type: script code this event handler is
called when the command is activated.
... orient type: one of the values below used to specify whether the children of the element are oriented horizontally or verti
cally.
...this will typi
cally cause the button to be displayed differently.
Mozilla release FAQ - Archive of obsolete content
i get library errors in dist/bin there's a script
called mozilla.
... use that to launch mozilla for you -- it sets ld_library_path automati
cally.
...dynami
cally generated pages make this nearly impossible.
...i would suggest that before you devote much time and effort to your port, you consider: how many users the os has that are likely to use mozilla does the os support multitasking well enough for mozilla does the os have a sufficiently evolved gui for mozilla to work does the os have sufficient networking support for mozilla is the os typi
cally run on systems that have the resources to run mozilla does gcc or some other easily available compiler exist for the target platform if many of these answers are no, then there will be large issues that will hamper the port.
Browser-side plug-in API - Archive of obsolete content
this chapter describes methods in the plug-in api that are provided by the browser; these allow
call back to the browser to request information, tell the browser to repaint part of the window, and so forth.
... the names of all of these methods begin with npn_ to indicate that they are implemented by the browser and
called by the plug-in.
... warning: you must only
call these from the main thread;
calling them from other threads is not supported and may have unpredictable results.
... 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_pluginthreadasync
call npn_poppopupsenabledstate npn_posturl npn_posturlnotify npn_pushpopupsenabledstate npn_reloadplugins npn_requestread npn_setvalue npn_setvalueforurl npn_status npn_useragent npn_version npn_write ...
NPN_MemAlloc - Archive of obsolete content
description the plug-in
calls npn_memalloc to allocate a specified amount of memory in the browser's memory space.
...since npn_memalloc automati
cally frees cached information if necessary to fulfill the request,
calls to npn_memalloc may succeed where direct
calls to newptr fail.
... existing
calls to npn_memflush have no effect.
... you only need to use npn_memflush in situations where you cannot use npn_memalloc, for example, when
calling system methods that allocate memory indirectly.
NPN_MemFlush - Archive of obsolete content
description the plug-in
calls npn_memflush() when it is not possible to
call npn_memalloc(), for example, when
calling system apis that indirectly allocate memory.
... to request that the browser free as much memory as possible,
call npn_memflush() repeatedly until it returns 0.
... on the mac, you can use this method to free memory before
calling memory-intensive system
calls.
... in general, plug-ins should use npn_memalloc() to allocate memory in the browser's memory space, since this function automati
cally frees cached data if necessary to fulfill the request.
NPP_SetWindow - Archive of obsolete content
description the browser
calls npp_setwindow after creating the instance to allow drawing to begin.
... subsequent
calls to npp_setwindow indicate changes in size or position; these
calls pass the same npwindow object each time, but with different values.
...this window is valid for the life of the instance, or until npp_setwindow is
called again with a different value.
... for windowless plugins, npp_setwindow is
called with a cliprect of 0,0,0,0 to signal that the plugin is not visible.
NPStream - Archive of obsolete content
the browser cannot delete the object until after it
calls npp_destroystream or the plug-in
calls npn_destroystream.
...all api
calls that operate on the stream (such as npp_writeready and npp_write) use a pointer to this stream.
...streams produced by the plug-in: the browser creates the npstream object and returns it as an output parameter when the plug-in
calls npp_newstream.
... the plug-in must pass a pointer to the npstream to all api
calls that operate on the stream, such as npn_write and npn_destroystream.
Digital Signatures - Archive of obsolete content
tamper detection and related authentication techniques rely on a mathematical function
called a one-way hash (also
called a message digest).
... the content of the hashed data cannot, for all practical purposes, be deduced from the hash-which is why it is
called "one-way." similarly, in public key encryption, a key pair is generated for digital signing.
...the keys are related mathemati
cally, but the parameters are chosen so that calculating the private key from the public key is either impossible or prohibitively expensive.the encrypted hash, along with other information, such as the hashing algorithm, is known as a digital signature.
... figure 1 shows two items transferred to the recipient of some signed data: the original data and the digital signature, which is basi
cally a one-way hash (of the original data) that has been encrypted with the signer's private key.
Table Reflow Internals - Archive of obsolete content
it gains, loses children) style changed - a target changed stylisticly (re
call, size is a style property) content changed - a target's content changed (e.g.
...caption is a target when it changes stylisti
cally (style changed).
... table, row group, row, col group, col is a target when a child is added or removed (dirty) or it changes stylisti
cally (style changed).
...typi
cally, a reflower accomplishes this by putting the continuation (c) on an overflow list which the reflower owns.
Settings - Archive of obsolete content
the debugger has its own settings menu, which you can access from an icon in the toolbar: each setting is a simple on/off switch: auto prettify minified sources with this option enabled, the debugger will automati
cally detect minified js files and pretty-print them.
... pause on exceptions when this option is enabled, execution of the script will automati
cally pause whenever a javascript exception is thrown.
... automati
cally black box minified sources new in firefox 33.
... automati
cally black box sources whose url ends with ".min.js".
Browser Detection and Cross Browser Support - Archive of obsolete content
</script> </body> </html> using netscape navigator 4's css limitations it is possible to use netscape navigator 4's limitations for css support to automati
cally exclude certain css rules from ever being seen by navigator 4.
...this will automati
cally use any such features in gecko if they are available in the version of gecko being used.
... how (and when) to use the navigator object when detecting gecko unless you specifi
cally need to detect if gecko is being used, do not use these methods.
...in this example, netscape 7 and internet explorer 5+ will automati
cally use clientwidth while netscape navigator 4, netscape 6, compuserve 7 and opera will use innerwidth.
E4X for templating - Archive of obsolete content
while it may be obvious after a study of the basics of e4x that it can be used for this purpose, if one adds a few common purpose functions (especially along with the convenience of javascript 1.8 expression closures), the templates can function more dynami
cally, offering the power and readability of templating languages such as smarty for php (though admittedly without the currently wider cross-browser support of xslt or the strictly-xml approach of phptal or seethrough templating).
... createbundle('chrome://myeext/locale/myext.properties'); if (args){ args = array.prototype.slice.
call(arguments, 1); return strs.formatstringfromname(msg,args,args.length); } return strs.getstringfromname(msg); } for example, <toolbarbutton label={$s('mytoolbar.label')}/> conditionals function _if (cond, h, _else) { if (cond && cond != undefined) { // we need undefined condition for e4x return h(cond); } else if (_else) { return _else(cond); } ...
... } 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.text() /* text()
call may not be necessary */ )} </output>.toxmlstring() ); /* <output> <item>banana</item> <item>grapes</item> <item>pear</item> </output> */ the above utility also works if the input is an htmlcollection, an array of strings, an array of dom objects, or an array of e4x objects (assuming the comparison function is changed or adapted accordingly).
...nt = <></>; for each (var el in a) { el.@att = 'val'; content += el; } return content; }()}</bar>; giving: <bar> <b att="val"/> <c att="val"/> <d att="val"/> </bar> one may still wish to remove complex business logic and supply as variables to the e4x, but the above allows the shaping of resulting content to be made more clear (and sometimes design logic also
calls for extra processing).
Processing XML with E4X - Archive of obsolete content
var h = 'html'; var text = "here's some text"; var doc = <{h}><body>{text}</body></{h}>; alert(doc.toxmlstring()); // gives <html> <body>here's some text</body> </html> working with attributes xml literal syntax has a significant advantage over the xml constructor when you need to create markup dynami
cally.
...variables and expressions can be used to create attribute values by simply wrapping them with braces ({}) and omitting quotation marks that would normally go around an attribute value, as the following example illustrates: var a = 2; var b = <foo bar={a}>"hi"</foo>; upon execution the variable is evaluated and quotes are automati
cally added where appropriate.
...continuing the above example, we can access an xmllist of the <lang> elements in the page as follows: var langs = languages.lang; xmllist provides a length() method which can be used to find the number of contained elements: alert(languages.lang.length()); note that unlike javascript arrays length is a method, not a property, and must be
called using length().
...literal syntax without needing to create a well-formed xml document, using the following syntax: var xmllist = <> <lang>javascript</lang> <lang>python</lang> </>; the += operator can be used to append new elements to an xmllist within a document: languages.lang += <lang>ruby</lang>; note that unlike node lists returned by regular dom methods, xmllists are static and are not automati
cally updated to reflect changes in the dom.
Object.observe() - Archive of obsolete content
syntax object.observe(obj,
callback[, acceptlist]) parameters obj the object to be observed.
...
callback the function
called each time changes are made, with the following argument: changes an array of objects each representing a change.
... acceptlist the list of types of changes to be observed on the given object for the given
callback.
... description
callback is
called each time a change is made to obj, with an array of all changes in the order in which they occurred.
JSObject - Archive of obsolete content
method summary the netscape.javascript.jsobject class has the following methods:
call calls a javascript method.
...
call method.
...
calls a javascript method.
... declaration public object
call(string methodname, object args[]) equals method.
Using the Right Markup to Invoke Plugins - Archive of obsolete content
<param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <p>you need flash -- get the latest version from <a href="http://www.macromedia.com/downloads/"> here.</a></p> </object> </object> web authors have to specify anobtainment mechanism in mozilla-based browsers -- the browser won't automati
cally retrieve plugins that are missing if you don't specify where to get the plugin from using the codebase attribute.
... recommendation in order to overcome the shortcomings that you can't nest object elements in ie and that there isn't a way you can simply use one object element in a cross-browser way (with architecture specific obtainment mechanisms), the best course of action is to dynami
cally write object elements based on architecture.
...once again, ie typi
cally invokes the plugin by way of an object element used in conjunction with a classid attribute that points to an activex unique identifier.
...typi
cally, the embed element is nested within an object element, such that the outer object element invokes an activex control for ie, whereas the inner embed element invokes a netscape plugin.
XUL Parser in Python - Archive of obsolete content
results the results from the script are written to a file
called res.html.
...note also that i wrote the build number into the header myself, and haven't figured out yet how to get that written automati
cally.
...if you want to look for certain widgets within the xul files, you can get the filename from the
calling method p.feed(data) and create a condition that only gets the elements specified in sys.argv[1].
...extending on the approach in this script, then, you could imagine a kind of introspective xul chrome that could modify and replicate itself by
calling services from the xulparser and xulwriter xpcom objects.
Common causes of memory leaks in extensions - Extensions
verlay: gbrowser.addeventlistener("domcontentloaded", function(evt) { var contentdoc = evt.originaltarget; var i = 0; // refresh the title once each second setinterval(function() { contentdoc.title = ++i; }, 1000); }, false); one would normally expect that the interval (or timer) would be destroyed as soon as the document unloads, in the same way that event listeners are automati
cally destroyed.
...another solution would be to use the setinterval()/settimeout() instances content windows provide, but there is a big drawback with this idea: if the user disables javascript globally or lo
cally (such as by using an add-on like noscript), then using the content window functions won't work.
... to avoid this problem explicitly
call nsiobserverservice.removeobserver() in an unload event listener.
... you may also specify ownsweak = true in the
call to nsiobserverservice.addobserver(), but that might require you to properly implement weak references as well.
Index - Game development
webgl is basi
cally an opengl es 2.0 for the web — it's a javascript api providing tools to build rich interactive animations and of course, also games.
... 35 tiles and tilemaps overview 2d, canvas, games, javascript, static, webgl, tilemap, tiles tilemaps are a very popular technique in 2d game development, consisting of building the game world or level map out of small, regular-shaped images
called tiles.
...we can make the game scale to fit on any screen size automati
cally during the preload stage, so we don't have to worry about it later.
...techni
cally, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies.
Bounding volume collision detection with THREE.js - Game development
keep in mind that in order for this property to be defined, you need to manually
call geometry.computeboundingbox beforehand.
...we assume our scene variable to be simply
called scene.
...we need to
call the update() method so the boxhelper instance matches its linked mesh.
... we also need to
call setfromobject again in order to make the box3 follow the mesh.
3D collision detection - Game development
the diagram below shows the test we'd perform over the x-axis — basi
cally, do the ranges aminx–amaxx and bminx–bmaxx overlap?
... mathemati
cally this would look like so: f(a,b)=(aminx<=bmaxx∧amaxx>=bminx)∧(aminy<=bmaxy∧amaxy>=bminy)∧(aminz<=bmaxz∧amaxz>=bminz)f(a,b) = and in javascript, we'd use this: function intersect(a, b) { return (a.minx <= b.maxx && a.maxx >= b.minx) && (a.miny <= b.maxy && a.maxy >= b.miny) && (a.minz <= b.maxz && a.maxz >= b.minz); } bounding spheres using bounding spheres to detect collisions is a bit more complex than aabb, but still fairly quick to test.
...sphere collision detection would work out like so: f(p,s)=sradius>=(px-sx)2+(py-sy)2+(pz-sz)2f(p,s) = s_{radius} >= \sqrt{(p_x - s_x)^2 + (p_y - s_y)^2 + (p_z - s_z)^2} or in javascript: function ispointinsidesphere(point, sphere) { // we are using multiplications because is faster than
calling math.pow var distance = math.sqrt((point.x - sphere.x) * (point.x - sphere.x) + (point.y - sphere.y) * (point.y - sphere.y) + (point.z - sphere.z) * (point.z - sphere.z)); return distance < sphere.radius; } the code above features a square root, which can be expensive to calculate.
... mathemati
cally, this looks like: f(a,b)=(ax-bx)2+(ay-by)2+(az-bz)2<=aradius+bradiusf(a,b) = \sqrt{(a_x - b_x)^2 + (a_y - b_y)^2 + (a_z - b_z)^2} <= a_{radius} + b_{radius} or in javascript: function intersect(sphere, other) { // we are using multiplications because it's faster than
calling math.pow var distance = math.sqrt((sphere.x - other.x) * (sphere.x - other.x) + (sphere.
Audio for Web games - Game development
many browsers will simply ignore any requests made by your game to automati
cally play audio; instead playback for audio needs to be started by a user-initiated event, such as a click or tap.
... let's look at some web audio api techniques for dynami
cally adjusting music from its base tracks.
...ake sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audioctx.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when
calling this function, which ensures that we can run subsequent code when it has finished executing.
... let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: async function loadfile(filepath) { const track = await getfile(filepath); return track; } let's also create a playtrack() function, which we can
call once a file has been fetched.
HTTP - MDN Web Docs Glossary: Definitions of Web-related terms
the hypertext transfer protocol (http) is the underlying network protocol that enables transfer of hypermedia documents on the web, typi
cally between a browser and a server so that humans can read them.
... the current version of the http specification is
called http/2.
... as part of a uri, the "http" within "http://example.com/" is
called a "scheme".
... resources using the "http" schema are typi
cally transported over unencrypted connections using the http protocol.
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
the type will get determined automati
cally while the program is being processed.
... a signature in javascript can still give you some information about the method: myobject.prototype.myfunction(value) the method is installed on an object
called myobject.
... the method accepts one parameter, which is
called value and is not further defined.
... public static void main(string[] args) the public keyword is an access modifier and indicates that this method can be
called by any object.
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
in a javascript runtime environment, a symbol value is created by invoking the function symbol, which dynami
cally produces an anonymous, unique value.
... note: if you are familiar with ruby's (or another language) that also has a feature
called "symbols", please don’t be misguided.
... if you really want to show a symbol, we need to
call .tostring() on it.
... let sym = symbol("sym") alert(sym.tostring()) // symbol(sym), now it works or you can use the symbol.description property to get its description: let _sym = symbol("sym"); alert(_sym.description); // sym well-known symbols the symbol class has constants for so-
called well-known symbols.
Safe - MDN Web Docs Glossary: Definitions of Web-related terms
what is important here is that by
calling a safe method, the client doesn't request any server change itself, and therefore won't create an unnecessary load or burden for the server.
... browsers can
call safe methods without fearing to cause any harm to the server; this allows them to perform activities like pre-fetching without risk.
... web crawlers also rely on
calling safe methods.
... a
call to a safe method, not changing the state for the server: get /pagex.html http/1.1 a
call to a non-safe method, that may change the state of the server: post /pagex.html http/1.1 a
call to an idempotent but non-safe method: delete /idx/delete http/1.1 learn more general knowledge definition of safe in the http specification.
Accessible multimedia - Learn web development
create a new file
called main.js and save it in the same directory.
...upload a video/audio file to the site, and it automati
cally transcribes it for you.
...in such cases, you should make sure that the resources are provided along with the audio + transcript, and specifi
cally link to them in the places where they are referred to in the transcript.
...these text strings are
called cues.
What is accessibility? - Learn web development
test early and often, ideally running automated tests to pick up on programmati
cally detectable missing features (such as missing image alternative text or bad link text — see element relationships and context) and doing some testing with disabled user groups to see how well more complex site features work for them.
... if content updates dynami
cally, do visually impaired people know about it?
...these are
called the web content accessibility guidelines (wcag), and they are not a short read by any means.
...this information is structured in a tree of information
called the accessibility tree.
Introduction to CSS layout - Learn web development
the block direction runs verti
cally in a language such as english, which has a horizontal writing mode.
...i don’t need to put any rules on the child elements; they are automati
cally placed into the cells our grid has created.
...this worked at the time, but it has many problems — table layouts are inflexible, very heavy on markup, difficult to debug, and semanti
cally wrong (e.g., screen reader users have problems navigating table layouts).
...the <form>, <div>s, and <label>s and <input>s have been told to display like a table, table rows, and table cells respectively — basi
cally, they'll act like html table markup, causing the labels and inputs to line up nicely by default.
Positioning - Learn web development
to try this out, add the following declarations to the .positioned rule in your css: top: 30px; left: 30px; note: the values of these properties can take any units you'd logi
cally expect — pixels, mm, rems, %, etc.
...you may re
call from previous points in the course where we discussed web pages using horizontal (x-axis) and vertical (y-axis) coordinates to work out positioning for things like background images and drop shadow offsets.
... position: sticky there is another position value available
called position: sticky, which is somewhat newer than the others.
... this is basi
cally a hybrid between relative and fixed position, which allows a positioned element to act like it is relatively positioned until it is scrolled to a certain threshold point (e.g.
How CSS is structured - Learn web development
here are three examples: <!-- inside a subdirectory
called styles inside the current directory --> <link rel="stylesheet" href="styles/style.css"> <!-- inside a subdirectory
called general, which is in a subdirectory
called styles, inside the current directory --> <link rel="stylesheet" href="styles/general/style.css"> <!-- go up one directory level, then inside a subdirectory
called styles --> <link rel="stylesheet" href="../styles/style.css"> inte...
...these rules are
called cascade and specificity.
... when a property is paired with a value, this pairing is
called a css declaration.
... shorthands some properties like font, background, padding, border, and margin are
called shorthand properties.
What is CSS? - Learn web development
what you are seeing is the browser's default styles — very basic styles that the browser applies to html to make sure it will be basi
cally readable even if no explicit styling is specified by the author of the page.
... note: a browser is sometimes
called a user agent, which basi
cally means a computer program that represents a person inside a computer system.
... css specifications all web standards technologies (html, css, javascript, etc.) are defined in giant documents
called specifications (or simply "specs"), which are published by standards organizations (such as the w3c, whatwg, ecma, or khronos) and define precisely how those technologies are supposed to behave.
... css is no different — it is developed by a group within the w3c
called the css working group.
What is the difference between webpage, website, web server, and search engine? - Learn web development
these are also often
called just "pages." website a collection of web pages which are grouped together and usually connected together in various ways.
... often
called a "web site" or simply a "site." web server a computer that hosts a website on the internet.
... note: browsers can also display other documents such as pdf files or images, but the term web page specifi
cally refers to html documents.
...such a website is sometimes
called a single-page website.
What is a URL? - Learn web development
absolute urls vs relative urls what we saw above is
called an absolute url, but there is also something
called a relative url.
... examples of absolute urls full url (the same as the one we used before) https://developer.mozilla.org/docs/learn implicit protocol //developer.mozilla.org/docs/learn in this case, the browser will
call that url with the same protocol as the one used to load the document hosting that url.
... examples of relative urls to better understand the following examples, let's assume that the urls are
called from within the document located at the following url: https://developer.mozilla.org/docs/learn sub-resources skills/infrastructure/understanding_urls because that url does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource.
...people are at the core of the web, and so it is considered best practice to build what is
called semantic urls.
Basic native form controls - Learn web development
the value can be dynami
cally set via javascript.
... <input type="checkbox" id="carrots" name="carrots" value="carrots" checked> including the checked attribute makes the checkbox checked automati
cally when the page loads.
...only one button in a given group may be checked at a time; this means that when one of them is checked all the others automati
cally get unchecked.
...you've met some of these already, but below is a list of those common attributes, for your reference: attribute name default value description autofocus false this boolean attribute lets you specify that the element should automati
cally have input focus when the page loads.
Other form controls - Learn web development
its possible values are: both: the default — allows resizing horizontally and verti
cally.
... vertical: allows resizing only verti
cally.
... autocomplete box you can provide suggested, automati
cally-completed values for form widgets using the <datalist> element with child <option> elements to specify the values to display.
... once a data list is affiliated with a form widget, its options are used to auto-complete text entered by the user; typi
cally, this is presented to the user as a drop-down box listing possible matches for what they've typed into the input.
Sending forms through JavaScript - Learn web development
sending arbitrary data asynchronously is generally
called ajax, which stands for "asynchronous javascript and xml".
...histori
cally, xmlhttprequest was designed to fetch and send xml as an exchange format, which has since been superceded by json.
...something went wrong.' ); } ); // set up our request xhr.open( 'post', 'https://example.com/cors.php' ); // send our formdata object; http headers are set automati
cally xhr.send( fd ); } btn.addeventlistener( 'click', function() { senddata( {test:'ok'} ); } ) here's the live result: using formdata bound to a form element you can also bind a formdata object to an <form> element.
... dealing with binary data if you use a formdata object with a form that includes <input type="file"> widgets, the data will be processed automati
cally.
Styling web forms - Learn web development
this has histori
cally been difficult — form controls vary greatly in how easy they are to customize with css — but it is getting easier as old browsers are retired and modern browsers give us more features to use.
... and even with css available to style html, browser vendors have histori
cally been reluctant to make form controls stylable because users were so accustomed to the visual appearance of their respective platforms.
... inside the unzipped contents you will find some font files (at the time of writing, two .woff files and two .woff2 files; they might vary in the future.) copy these files into a directory
called fonts, in the same directory as before.
...lds gains focus, we highlight them with a light grey, transparent, background (it is always important to have focus style, for usability and keyboard accessibility): input:focus, textarea:focus { background : rgba(0,0,0,.1); border-radius: 5px; } now that our text fields are complete, we need to adjust the display of the single and multiple line text fields to match, since they won't typi
cally look the same using the defaults.
Responsive images - Learn web development
this is
called the resolution switching problem.
...an find an example of what this looks like in srcset-resolutions.html (see also the source code): <img srcset="elva-fairy-320w.jpg, elva-fairy-480w.jpg 1.5x, elva-fairy-640w.jpg 2x" src="elva-fairy-640w.jpg" alt="elva dressed as a fairy"> in this example, the following css is applied to the image so that it will have a width of 320 pixels on the screen (also
called css pixels): img { width: 320px; } in this case, sizes is not needed — the browser simply works out what resolution the display is that it is being shown on, and serves the most appropriate image referenced in the srcset.
...realisti
cally, you probably won't want to do this kind of thing very often.
...for example, you couldn't load the <img> element, then detect the viewport width with javascript, and then dynami
cally change the source image to a smaller one if desired.
Test your skills: Multimedia and embedding - Learn web development
the audio is
called audio.mp3, and it is in a folder inside the current folder
called media.
...the files are
called video.mp4 and video.webm, and are in a folder inside the current folder
called media.
... display the text tracks contained in the media folder, in a file
called subtitles_en.vtt, when the video is playing.
...the pdf is
called mypdf.pdf, and is contained in the media folder.
Image gallery - Learn web development
starting point to get this assessment started, you should go and grab the zip file for the example, unzip it somewhere on your computer, and do the exercise lo
cally to begin with.
... it sets the width of any images inside the thumb-bar <div> (so-
called "thumbnail" images) to 20%, and floats them to the left so they sit next to one another on a line.
... 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.
... writing a handler that runs the darken/lighten button that just leaves our darken/lighten <button> — we've already provided a line that stores a reference to the <button> in a constant
called btn.
Useful string methods - Learn web development
you could use this to, for example, find the first letter of a series of strings and order them alphabeti
cally.
...to actually update the value of the browsertype variable in a real program, you'd have to set the variable value to be the result of the operation; it doesn't just update the substring value automati
cally.
...or in this case, does the method
call on the left return the result on the right?
... hint: in this case it is probably more useful to test whether the method
call isn't equal to a certain result.
Server-side web frameworks - Learn web development
continuing the "youngest team" example from the previous section, the html template is passed a list variable
called youngest_teams by the view.
... scalability: once your website is fantasti
cally successful you will exhaust the benefits of caching and even reach the limits of vertical scaling (running your web application on more powerful hardware).
... at this point you may need to scale horizontally (share the load by distributing your site across a number of web servers and databases) or scale "geographi
cally" because some of your customers are based a long way away from your server.
... back in the early days of the web, many people learned perl because of a wonderful perl library
called cgi.
Getting started with Ember - Learn web development
previous overview: client-side javascript frameworks next in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain lo
cally, create a sample app, and then do some initial setup to get it ready for development.
... for more information on the technical aspects of the glimmer vm, the github repository has some documentation — specifi
cally, references and validators may be of interest.
...this creates a new directory inside the current directory you are in
called todomvc, containing the scaffolding for a new ember app.
...ember-cli-build.js is responsible for configuring details about how your project is built — including bundling all your files together, asset minification, and creating sourcemaps — with reasonable defaults, so you don't typi
cally need to worry about this file.
Accessibility in React - Learn web development
let's see this in action; put the following useeffect()
call just above the return statement in the body of todo(), and pass into it a function that logs the words "side effect" to your console: useeffect(() => { console.log("side effect"); }); to illustrate the difference between the main render process and code run inside useeffect(), add another log – put this one below the previous addition: console.log("main render"); now, open the app in your...
...let's try it now — update your useeffect()
call like so: useeffect(() => { if (isediting) { editfieldref.current.focus(); } else { editbuttonref.current.focus(); } }, [isediting]); this kind of mostly works.
...we want this constant to track the previous value of isediting, so we
call useprevious with isediting as an argument: const wasediting = useprevious(isediting); with this constant, we can update our useeffect() hook to implement the pseudocode we discussed before — update it as follows: useeffect(() => { if (!wasediting && isediting) { editfieldref.current.focus(); } if (wasediting && !isediting) { editbuttonref.current.focus(); } }, [wasediting, is...
...this isn't a problem — we can make any element programmati
cally focusable by adding the attribute tabindex="-1" to it.
Accessibility API cross-reference
checkbutton check_box check_box checkbox or switch <input type=checkbox> pretty obvious what this is for clock n/a n/a timer <time> column of cells in a table - how would the user specifi
cally point to this, as opposed to the column header or cells?
...in such a case, they should be wrapped in a <reference> pragmati
cally however, user agents should expect to find <link> tags as direct children of <toci> abstract role - a perceivable section containing content that is relevant to a specific, author-specified purpose and sufficiently important that users will likely want to be able to navigate to the section easily and to have it listed in a summary of the page.
... such a page summary could be generated dynami
cally by a user agent or assistive technology.
...in such a case, they should be wrapped in a <reference> pragmati
cally 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.
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 fr...
...eed with pl_strfree() nscrt::strdup/nscrt::strndup must be freed with nscrt::free allocating memory within plugins there are special memory allocation routines specifi
cally intended for use from plugins, which must not be used from within mozilla itself.
...these should only be used to allocate objects that are guaranteed to have a shorter lifetime than the presshell in question (typi
cally layout data structures), because the presshell destructor will wipe out the arena, leaving any pointers to memory allocated from it dangling.
Command line options
firefox -createprofile "joeluser c:\internet\joelusers-moz-profile" note: profile_dir must not exist and you must not already have a profile
called profile_name.
...this should not be specified unless the
caller provides all of the functionality provided by the os shell when launching the application (bug 384384).
...this should not be specified unless the
caller provides all of the functionality provided by the os shell when launching the application (bug 354005).
... --sync make x
calls synchronous.
Simple Instantbird build
first, cd into the comm-central subdirectory (created automati
cally by the previous command): cd comm-central then run: python client.py checkout note: unless you have a very good network connection, "hg clone" might fail because it gets interrupted.
...the normal way to specify build options is to place them in a file
called '.mozconfig' at the root of your mozilla source tree, i.e.
... building instantbird what you need to do to build instantbird rather than firefox is: echo 'ac_add_options --enable-application=im' >> .mozconfig to start the build, cd into the comm-central subdirectory (created automati
cally by the hg clone command), and run: ./mozilla/mach build mach is our command-line tool to streamline common developer tasks.
...so, for instantbird, you would run mach build im which has been configured to automati
cally rebuild /chat as well.
Message manager overview
in the initial version of multiprocess firefox there are two processes: the chrome process, also
called the parent process, runs the browser ui (chrome) code and code inserted by extensions the content processes, also
called the child processes, run all web content.
...these scripts are
called frame scripts, and as the name suggests, they are scoped to a specific browser frame.
... frame message managers in multiprocess firefox, when chrome code needs to interact with web content, it needs to: factor the code that needs direct access to content into separate scripts, which are
called "frame scripts" use a frame message manager to load these frame scripts into the content process use the frame message manager api to communicate with the frame script some older articles on multiprocess firefox and the message manager might refer to "content scripts" instead of "frame scripts", but this usage is deprecated because the add-on sdk uses "content script" to refer to a similar...
...these scripts are
called "frame scripts".
Browser API
mozbrowserclose sent when window.close() is
called within a browser <iframe>.
... mozbrowseropenwindow sent when window.open() is
called within a browser <iframe>.
... mozbrowsershowmodalprompt sent when alert(), confirm(), or prompt() are
called within a browser <iframe>.
... mozbrowservisibilitychange sent when the visibility state of the current browser iframe <iframe> changes, for example due to a
call to setvisible().
MozBeforePaint
whenever you're ready to refresh your animation, you
call the window.requestanimationframe() method.
... once you've
called this, the mozbeforepaint event will be fired one time, when it's time for animations to be updated for the window's next animation frame.
...tart; d.style.left = math.min(progress/10, 200) + "px"; if (progress < 2000) { window.mozrequestanimationframe(); } else { window.removeeventlistener("mozbeforepaint", step, false); } } window.addeventlistener("mozbeforepaint", step, false); window.mozrequestanimationframe(); </script> </body> </html> as you can see, each time the mozbeforepaint event fires, our step() method is
called.
... this computes the current position for the animating box and updates the box's position on screen, and, if the animation sequence is not yet complete,
calls window.requestanimationframe() to schedule the next animation frame to be drawn.
Roll your own browser: An embedding how-to
i have created a directory under embedding
called config.
...all of this is somewhat generic and has been isolated into a static library that you can simply
call on.
... if you build mozilla/embedding/base/, a static library (on windows)
called baseembed_s.lib is built.
...ns_initembedding() must be
called from the main thread of your application, otherwise it won't work.
PBackground
at build time the ipdl compiler automati
cally generates a large amount of c++ glue code from the ipdl files.
...these actors can live in different processes due to ipdl, which automati
cally serializes
calls on one side and transmits them to the other.
...this protocol is
called pcompositor, and allows us to bypass the main thread of the parent process, which trims the latency of texture uploads since they will not get bogged down if that thread is busy.
...instead, it simply turns all of its operations into ipdl
calls on a set of pbackground-based actors and the processing, file i/o, etc, can be controlled from the pbackground thread regardless of where the dom
calls are being made.
JavaScript Tips
don't
call methods that you don't have to.
... don't
call queryinterface unless you expect to succeed.
...for instance the offline observer declared above is a javascript object that is registered with an xpcom object, so that the
call back from xpcom executes the javascript method.
... don't
call getattribute to see if an attribute exists,
call hasattribute instead.
DownloadList
the following methods may be defined: ondownloadadded: optional this function is
called with a single download argument, after the download is added to the end of the list.
... ondownloadchanged: optional this function is
called with a single download argument, after the properties of the download change.
... ondownloadremoved: optional this function is
called with a single download argument, after the download is removed from the list.
...promise removefinished( function afilterfn ); parameters afilterfn the filter function is
called with each download as its only argument, and should return true to remove the download and false to keep it.
DownloadTarget
this is a dynamic property, which is updated when the download is completed or when the download.refresh() method is
called.
... you can use this instead of using file system
calls to check for the existence of the file in order to reduce io overhead.
... this is a dynamic property, which is updated when the download finishes or whenever the download.refresh() method is
called.
...
calling this method lets the download object's properties be updated if the user moves or deletes the target file or its associated ".part" file, which contains a partially-downloaded file's contents.
OSFile.jsm
if the operation is
called on the main thread, this means that the whole user experience is stuck for several seconds, which is quite bad.
... i/o efficiency is all about minimizing the number of actual i/o
calls.
...
calling os.file from the main thread asynchronous, off-main thread file i/o, main thread api.
...
calling os.file.directoryiterator from the main thread asynchronous, off-main thread file directory access, main thread api.
Promise.jsm
a reference to an existing promise may be received by different means, for example as the return value of a
call into an asynchronous api.
...this method registers
callback functions that are
called as soon as the promise is either fulfilled or rejected.
... 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.
Mozilla Web Developer FAQ
this document answers questions that web authors ask frequently specifi
cally in connection with firefox and other gecko-based browsers.
... when the paragraph markup is
called for but the default margins are unwanted, zero margins can be suggested using css.
...however, that functionality only exists for compatibility with sites authored specifi
cally for ie.
...the correct way to access an element by id is to
call the document.getelementbyid() method with the id as a string as the argument.
about:memory
single memory report files can also be loaded automati
cally when about:memory is loaded by appending a file query string, for example: about:memory?file=/home/username/reports.json.gz this is most useful when loading memory reports files obtained from a firefox os device.
... 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).
... this "explicit" value at the root of the tree represents all the memory allocated via explicit
calls to allocation functions.
...this is typi
cally 10--20% of "explicit".
A guide to searching crash reports
specifi
cally, crash-stats offers two basic functions: searching you can search the crash reports database by over 100 criteria: crash signature, date, platform, product, version, etc.
... this immediately shows which moz_crash
calls are being hit frequently by users.
... only a subset of crash reports have the "moz crash reason" field -- those that crashed due to hitting a moz_crash
call -- so all crashes that lack that field are omitted from this tab.
... there is also an api through which searches can be performed programmati
cally.
Localization Use Cases
slovenian uses the locative case with its about preposition: <aboutbrowser "o {{ browserbrandshortname.locative }}"> for the official branding, we get: o firefoxu and for the unofficial branding, we end up with: o brskalniku genders in the system app's apps/system/locales/system, there's a string
called crash-banner-os2.
...in order to construct a grammati
cally-correct and naturally-sounding message, we must know the gender of the subject.
...e function is used like so: // application storage updateappfreespace: function storage_updateappfreespace() { var self = this; this.getfreespace(this.appstorage, function(freespace) { devicestoragehelper.showformatedsize(self.appstoragedesc, 'availablesize', freespace); }); }, problem definition for all values of freespace, the following string is enough to construct a grammati
cally-correct sentence in english: availablesize = {{$size}} {{$unit}} available however, other languages might need to pluralize this string with different forms of the available adjective.
... byteunit-b = b byteunit-kb = kb byteunit-mb = mb byteunit-gb = gb byteunit-tb = tb for example in french, the unit abbreviations are as follows: byteunit-b = o byteunit-kb = ko byteunit-mb = mo byteunit-gb = go byteunit-tb = to solution in l20n, the french localizer could provide the translation of unit abbreviations lo
cally in the localization file, without impacting the english localization file.
Nonblocking IO In NSPR
a thread is typi
cally created to attend to one of the simultaneous i/o operations that may potentially block.
...typi
cally, this central thread invokes <tt>pr_poll()</tt> on a set of nonblocking file descriptors.
...the socket returned by <tt>pr_accept()</tt> or <tt>pr_acceptread()</tt> on a blocking, listening socket may be a recycled socket previously used in a <tt>pr_transmitfile()</tt>
call.
...the current implementation of <tt>pr_select()</tt> simply
calls <tt>pr_poll()</tt>, so it is sure to have worse performance.
Dynamic Library Linking
it also provides a method by which to condition symbols of stati
cally linked code so that to other clients it appears as though they are dynami
cally loaded.
...you can then
call pr_findsymbol on lib to look up other symbols defined in the main program.
... remember to
call pr_unloadlibrary(lib) to close the library handle when you are done.
...these systems typi
cally use dlopen to load a dynamic library.
Memory Management Operations
nspr provides heap-based memory management functions that map to the familiar malloc(),
calloc(), realloc(), and free().
... memory allocation functions are: pr_malloc pr_
calloc pr_realloc pr_free pr_malloc(), pr_
calloc(), pr_realloc(), and pr_free() have the same signatures as their libc equivalents malloc(),
calloc(), realloc(), and free(), and have the same semantics.
... (note that the argument type size_t is replaced by pruint32.) memory allocated by pr_malloc(), pr_
calloc(), or pr_realloc() must be freed by pr_free().
... 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 ...
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.
...further information can be obtained by
calling pr_geterror.
... description the socket fd is a rendezvous socket that has been bound to an address with pr_bind and is listening for connections after a
call to pr_listen.
... pr_accept blocks the
calling thread until either a new connection is successfully accepted or an error occurs.
PR_CNotify
the
calling thread must be in the monitor defined by the value of the address.
... returns pr_success indicates that the
calling thread is the holder of the mutex for the monitor referred to by the address parameter.
... pr_failure indicates that the monitor has not been entered by the
calling thread.
...if a thread is waiting on the monitor (having
called pr_cwait), then that thread is made ready.
PR_ConnectContinue
if pr_connectcontinue() returns pr_failure,
call pr_geterror(): - pr_in_progress_error: the nonblocking connect is still in progress and has not completed yet.
... the
caller should poll the file descriptor for the in_flags pr_poll_write|pr_poll_except and retry pr_connectcontinue later when pr_poll() returns.
...after a nonblocking connect is initiated with pr_connect() (which fails with pr_in_progress_error), one should
call pr_poll() on the socket, with the in_flags pr_poll_write | pr_poll_except.
... when pr_poll() returns, one
calls pr_connectcontinue() on the socket to determine whether the nonblocking connect has completed or is still in progress.
PR_DetachThread
the
call returns after the nspr thread object is destroyed.
... this
call is needed only if you attached the thread using pr_attachthread.
...a native thread not created by nspr is automati
cally attached the first time it
calls an nspr function, and automati
cally detached when it exits.
... in nspr release 19980529b and earlier, it is necessary for a native thread not created by nspr to
call pr_attachthread before it
calls any nspr functions, and
call pr_detachthread when it is done
calling nspr functions.
PR_GetHostByAddr
buf a pointer to a buffer, allocated by the
caller, that is filled in with host data on output.
...this buffer is referenced by the runtime during a
call to pr_enumeratehostent.
... hostentry this structure is allocated by the
caller.
...you can retrieve the reason for the failure by
calling pr_geterror.
PR_GetHostByName
buf a pointer to a buffer, allocated by the
caller, that is filled in with host data on output.
...this buffer is referenced by the runtime during a
call to pr_enumeratehostent.
... hostentry this structure is allocated by the
caller.
...you can retrieve the reason for the failure by
calling pr_geterror.
PR ImportTCPSocket
the
caller gives up control of the native tcp socket osfd and should use the prfiledesc* returned by pr_importtcpsocket instead.
...the
caller needs to understand what nspr will do to the native file descriptor and make sure that nspr can use the native file descriptor successfully.
... for example, on posix systems, nspr will put the native file descriptor (an int) in non-blocking mode by
calling fcntl to set the o_nonblock file status flag on the native file descriptor, and then nspr will
call socket functions such as recv, send, and poll on the native file descriptor.
... the
caller must not do anything to the native file descriptor before the pr_importtcpsocket
call that will prevent the native file descriptor from working in non-blocking mode.
PR_InitializeNetAddr
the storage for the network address structure is allocated by, and remains the responsibility of, the
calling client.
...you can retrieve the reason for the failure by
calling pr_geterror.
...this allows the
caller to change the network address' port number assignment without affecting the host address.
...this wildcard value is typi
cally used to establish a socket on which to listen for incoming connection requests.
PR_NewTCPSocket
typi
cally, the server binds its socket to a well-known port with pr_bind,
calls pr_listen to start listening for connection setup requests, and
calls pr_accept to accept a connection.
...to receive data, one can
call pr_read or pr_recv.
... to send data, one can
call pr_write, pr_writev, pr_send, or pr_transmitfile.
... pr_acceptread is suitable for use by the server to accept a new client connection and read the client's first request in one function
call.
PR_Open
pr_sync 0x40 if set, each write will wait for both the file data and file status to be physi
cally updated.
...ion, group pr_irwxo 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 dynami
cally allocated prfiledesc for the newly opened file.
... the prfiledesc should be freed by
calling pr_close.
...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_OpenTCPSocket
typi
cally, the server binds its socket to a well-known port with pr_bind,
calls pr_listen to start listening for connection setup requests, and
calls pr_accept to accept a connection.
...to receive data, one can
call pr_read or pr_recv.
... to send data, one can
call pr_write, pr_writev, pr_send, or pr_transmitfile.
... pr_acceptread is suitable for use by the server to accept a new client connection and read the client's first request in one function
call.
PR_Poll
timeout amount of time the
call will block waiting for i/o to become ready.
...the reason for the failure can be obtained by
calling pr_geterror.
... the in_flags field of the prpolldesc data structure should be set to the i/o events (readable, writable, exception, or some combination) that the
caller is interested in.
...pr_poll uses the out_flags fields as scratch variables during the
call.
NSS 3.18 release notes
use -c one, two or three times to print information about the certificates received from a server, and information about the lo
cally found and trusted issuer certificates, to diagnose server side configuration issues.
... in p12.h sec_pkcs12decoderrenamecertnicknames -
call an application provided
callback for each certificate found in a sec_pkcs12decodercontext.
... new types in p12.h sec_pkcs12nicknamerename
callback - a function pointer definition.
... an application that uses sec_pkcs12decoderrenamecertnicknames must implement a
callback function that implements this function interface.
NSS 3.21 release notes
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 module name string, module parameters string, nss specific parameters string, and nss configuration parameter string.
... in ssl.h ssl_getpreliminarychannelinfo - obtains information about a tls channel prior to the handshake being completed, for use with the
callbacks that are invoked during the handshake ssl_signatureprefset - configures the enabled signature and hash algorithms for tls ssl_signatureprefget - retrieves the currently configured signature and hash algorithms ssl_signaturemaxcount - obtains the maximum number signature algorithms that can be configured with ssl_signatureprefset in utilpars.h nssutil_argparsemodulespecex - takes a module spec and breaks it into shared library string, module name strin...
...the returned strings must be freed by the
caller.
... nssutil_mkmodulespecex - take a shared library string, module name string, module parameters string, nss specific parameters string, and nss configuration parameter string and returns a module string which the
caller must free when it is done.
NSS 3.35 release notes
without a prefix, the default database type will be used (dbm in versions prior to 3.35, and sql in version 3.35 and later.) when using the sql type (either explicitly, or because of the new default), with a database directory which already contains a dbm type database, nss will automati
cally perform a one time migration of the information contained in the dbm files to the newer sql files.
... keyupdate will be used automati
cally, if a cipher is used for a sufficient number of records.
... tls servers can screen new tls 1.3 connections, as they are made using the experimental ssl_helloretryrequest
callback function.
... this function allows for
callbacks to be installed, which are
called when a server receives a new tls clienthello.
FC_InitToken
specifi
cally, fc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs.
... (user certs are the certificates that have their associated private keys in the key database.) a user must be able to
call fc_inittoken() without logging into the token (to assume the nss user role) because either the user's password hasn't been set yet or the user forgets the password and needs to blow away the password-encrypted private key database and start over.
... the "reset password" button of the mozilla application suite and seamonkey (in preferences->privacy & security->master passwords)
calls fc_inittoken().
... the "-t" (token reset) command of certutil
calls fc_inittoken().
sslerr.html
ssl_error_bad_certificate -12284 "unable to communicate securely with peer: peers's certificate was rejected." a certificate was received from the remote system and was passed to the certificate authentication
callback function provided by the local application.
... that
callback function returned secfailure, and the bad certificate
callback function either was not configured or did not choose to override the error code returned by the certificate authentication
callback function.
... ssl_error_wrong_certificate -12277 "client authentication failed: private key in key database does not correspond to public key in certificate database." ssl_error_bad_cert_domain -12276 "unable to communicate securely with peer: requested domain name does not match the server's certificate." this error code should be returned by the certificate authentication
callback function when it detects that the common name in the remote server's certificate does not match the hostname sought by the local client, according to the matching rules specified for cert_verifycertname.
... ssl_error_post_warning -12275 (unused) ssl_error_ssl2_disabled -12274 "peer only supports ssl version 2, which is lo
cally disabled." the remote server has asked to use ssl version 2, and ssl version 2 is disabled in the local client's configuration.
NSS_3.12.3_release_notes.html
in sslt.h: ssl_calg_seed new structure for seed support: (see blapit.h) seedcontextstr seedcontext new functions in the nss shared library: cert_rfc1485_escapeandquote (see cert.h) cert_comparecerts (see cert.h) cert_registeralternateocspaiainfo
callback (see ocsp.h) pk11_getsymkeyhandle (see pk11pqg.h) util_setforkstate (see secoid.h) nss_getalgorithmpolicy (see secoid.h) nss_setalgorithmpolicy (see secoid.h) for the 2 functions above see also (in secoidt.h): nss_use_alg_in_cert_signature nss_use_alg_in_cms_signature nss_use_alg_reserved ...
... bug 467298: sql db code uses local cache on local file system bug 468279: softoken crash importing email cert into newly upgraded db bug 468532: trusted ca trust flags not being honored in cert_verifycert bug 469583: coverity: uninitialized variable used in sec_pkcs5createalgorithmid bug 469944: when built with microsoft compilers bug 470351: crlutil build fails on windows because it
calls undeclared isatty bug 471539: stop honoring digital signatures in certificates and crls based on weak hashes bug 471665: nss reports incorrect sizes for (aes) symmetric keys bug 471715: add cert to nssckbi to override rogue md5-collision ca cert bug 472291: crash in libpkix object leak tests due to null pointer dereferencing in pkix_build.c:3218.
... bug 483113: add environment variable to disable/enable hash algorithms in cert/crl signatures bug 483168: nss
callback api for looking up a default ocsp responder url bug 483963: assertion failure in ocsp tests.
... bug 485729: remove lib/freebl/mapfile.solaris bug 485837: vc90.pdb files are output in source directory instead of objdir bug 486060: sec_asn1d_parse_leaf uses argument uninitialized by
caller pbe_pk11algidtoparam documentation for a list of the primary nss documentation pages on mozilla.org, see nss documentation.
NSS Tools modutil
the tasks associated with security module database management are part of a process that typi
cally also involves managing key databases (key3.db files) and certificate databases (cert8.db files).
... -pwfile old-password-file specify a text file containing a token's existing password so that a password can be entered automati
cally when the -changepw tokenname option is used to change passwords.
... -newpwfile new-password-file specify a text file containing a token's new or replacement password so that a password can be entered automati
cally with the -changepw tokenname option.
...typi
cally this string would be used for a setup program provided by a module vendor, such as a self-extracting setup.exe.
Pork Tools
it takes a list of functions as input and rewrites the definition and
call sites of those functions.
... if (!*aresult) return ns_error_failure; return ns_ok; } nsifoo* getter() { nsifoo *result = null; // aresult below is kept for complicated cases // typi
cally it wont be needed and can be removed nsifoo **aresult = &result; // *aresult patterns are replaced with result result = ...
... if (result) return nsnull; // error returns are changed to nsnull //instead ns_ok, actual result is returned return result; }
caller1 { //case 1 nsresult rv; rv = getter(&var); ns_ensure_success(rv,rv); //case 2: naked
call getter(&var); //case 3: nsresult decl nsresult rv2 = getter(&var); ns_ensure_success(rv2,rv2); }
caller1 { // case 1 // figure out that rv was only used for the rewritten // outparam
call + ns_ensure_success.
...in this case all of the
callsites are modified to: a) getter_addrefs case: getter(getter_addrefs(foo)) -> foo = getter() b) all other cases: getter(&foo) -> foo = getter().get() ...
Creating JavaScript tests
jstests automati
cally load js/src/tests/shell.js before they run, which creates a ton of functions.
... jit-tests do not load extra test functionality automati
cally.
...there is basi
cally no cost to adding a new test, so add as many feature tests as needed to cover each feature orthogonally.
... testing your test run your new test lo
cally before checking it in (or posting it for review).
SpiderMonkey Internals: Thread Safety
a program typi
cally has only one jsruntime, even if it has many threads.
...all js code and most jsapi
calls run within a jscontext.
...the program must group jsapi
calls into "requests": js_setcontextthread(cx); js_beginrequest(cx); /* ...
...a
call to js_gc() will block until the latter becomes possible.
JS::Rooted
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...this is typi
cally used for local variables, or for non-rooted values being passed to a function that requires a handle, e.g.
... js::rooted<t> may be automati
cally coerced to a js::handle<t>.
... js::rooted<t> should be used whenever a local variable's value may be held live across a
call which can trigger a gc.
JSConvertOp
description jsconvertop
callback specifies conversion behavior for objects having this class, implementing the ecmascript [[defaultvalue]] behavior for them.
... implementations of this hook have histori
cally been required to accept any type.
...(support for the other types may eventually be removed.) the
callback returns true to indicate success or false to indicate failure.
... jsclass hooks jsclass offers the following hook: the jsclass.convert
callback implements the [[defaultvalue]] behavior for objects having that class.
JSFunctionSpec
syntax struct jsfunctionspec { const char *name; jsnativewrapper
call; uint16_t nargs; uint16_t flags; const char *selfhostedname; }; typedef struct jsnativewrapper { jsnative op; const jsjitinfo *info; } jsnativewrapper; name type description name const char * the function's name.
...
call jsnativewrapper the built-in js
call wrapped by this function.
... if the function does not wrap a native js
call, set this value to null.
...an application typi
cally has an array of jsfunctionspec to define all the functions for an object and
calls js_definefunctions or js_initclass to create the functions and assign them to an object.
JSObjectOps.enumerate
the jsobjectops.enumerate
callback implements iteration over object properties.
... 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.
... if the flag is present, enumerate simply delegates the
call to jsclass.enumerate.
JSObjectOps.lookupProperty
the jsobjectops.lookupproperty
callback is
called for every property access (except when a higher-level
callback, such as jsobjectops.getproperty, is overloaded in a way that does not
call lookupproperty).
...if the property is found, the
callback stores the object on which the property was found in *objp.
...on success, the
callback stores in *propp a pointer to the property, if it exists, or null if it doesn't.
... note: a successful return with non-null *propp means the implementation may have locked *objp and added a reference count associated with *propp, so
callers should not risk deadlock by nesting or interleaving other lookups or any obj-bearing ops before dropping *propp.
JSPrincipalsTranscoder
jsprincipalstranscoder is the type of a security
callback that can be configured using js_setprincipalstranscoderjsapi 1.8 and earlier or js_setruntimesecurity
callbacksadded in spidermonkey 1.8.1.
...
callback syntax typedef jsbool (*jsprincipalstranscoder)(jsxdrstate *xdr, jsprincipals **principalsp); name type description xdr jsxdrstate * the xdr reader/writer.
... description the javascript engine uses this
callback to serialize and deserialize principals.
... the
callback xdr-encodes or -decodes a principals instance, based on whether xdr->mode is jsxdr_encode, in which case *principalsp should be encoded; or jsxdr_decode, in which case implementations must return a held (via jsprincipals_hold), non-null *principalsp out parameter.
JSTraceOp
description jstraceop is the function type for trace operation of the class
called to enumerate all traceable things reachable from obj's private data structure.
... for each such thing, a trace implementation must
call one of the js_
call*tracer variants on the thing.
...in that case the embedding can check if the traversal is a part of the marking phase through
calling js_isgcmarkingtracer and apply a special code like emptying caches or marking its native structures.
... jsclass hooks jsclass offers the following hook: the jsclass.trace
callback is
called to enumerate all traceable things reachable.
JS_AlreadyHasOwnProperty
this article covers features introduced in spidermonkey 1.8 determine whether a property is already physi
cally present on a jsobject.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
... the object's jsclass.resolve hook is not
called, so lazily defined properties are not found.
...this
calls the jsobjectops.lookupproperty hook.
JS_CheckAccess
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...if obj has custom jsobjectops, the access check is delegated to the jsobjectops.checkaccess
callback.
... otherwise, if obj's class has a non-null jsclass.checkaccess
callback, then it is
called to perform the check.
... otherwise, if a runtime-wide check-object-access
callback has been installed by
calling js_setcheckobjectaccess
callback, then that is
called to perform the check.
JS_DecompileFunction
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... if you decompile a function that does not make a native c
call, then the text created by js_decompilefunction is a complete function declaration suitable for re-parsing.
... if you decompile a function that makes a native c
call, the body of the function contains the text "native code'" and cannot be re-parsed.
... 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_setbranch
callback js_valuetofunction ...
JS_DecompileFunctionBody
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...if you decompile a function that makes a native c
call, the body of the function only contains the text "[native code]".
... notes to decompile a complete function, including its body and declaration,
call js_decompilefunction instead.
... 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_setbranch
callback js_valuetofunction ...
JS_DeleteProperty2
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true and obj's jsclass.delproperty hook is
called (which may change *succeeded).
...in this case, *succeeded is set to true and obj's jsclass.delproperty hook is
called (which may change *succeeded).
...there is no longer any way to get this behavior.) to remove all properties from an object,
call js_clearscope.
JS_GetExternalStringClosure
this article covers features introduced in spidermonkey 6 returns the string closure stored in a jsstring created by
calling js_newexternalstringwithclosure.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...the result is null if the external string was created without one (that is, by
calling js_newexternalstring rather than js_newexternalstringwithclosure).
... description to determine if a string was created as an external string, you can
call js_isexternalstring.
JS_Init
once this method has succeeded, it is safe to
call js_newruntime and other jsapi methods.
... this method must be
called before any other jsapi method is used on any thread.
... once it has been used, it is safe to
call any jsapi method, and it remains safe to do so until js_shutdown is correctly
called.
... it is currently not possible to initialize spidermonkey multiple times (that is,
calling js_init, jsapi methods, then js_shutdown in that order, then doing so again).
JS_MaybeGC
calling js_maybegc when the application is idle can help prevent garbage collection from happening at less convenient times.
...
calling js_maybegc periodi
cally when the application is busy, from a jsbranch
callback or jsoperation
callback added in spidermonkey 1.8, can keep memory usage down and improve performance.
...in both cases, frequent
calls js_maybegc are safe and will not cause the application to spend a lot of time doing redundant garbage collection work.
...such applications can benefit from implementing their own custom-tuned maybe-gc function that conditionally
calls js_gc on the basis of some application-specific analysis, and using that instead of js_maybegc.
JS_NewContext
in a debug build, large chunk sizes can degrade performance dramati
cally.
... the application must
call js_destroycontext when it is done using the context.
... the new jscontext is associated with the
calling thread.
... see also mxr id search for js_newcontext js_destroycontext js_contextiterator js_setcontext
callback ...
JS_NewObjectForConstructor
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.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
... args js::
callargs &
call argument to get a constructor as
callee.
...with js_newobjectforconstructor, the prototype and parent are determined by the constructor, and class is still determined by the
caller.
JS_NewRuntime
call js_newruntime before making any other api
calls except js_init.
... the returned jsruntime can be used from the
calling thread only.
... (the engine may use helper threads internally, though.) on success, js_newruntime returns a pointer to the newly created runtime, which the
caller must later destroy using js_destroyruntime.
... notes ordinarily, js_newruntime should be the first jsapi
call in an application, and js_destroyruntime and js_shutdown should be the last ones.
JS_ReportError
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...the resulting error message is passed to the context's jserrorreporter
callback, if any.
... 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.
... the
callback must then return js_false to cause the exception to be propagated to the
calling script.
JS_ReportOutOfMemory
description
call js_reportoutofmemory to report that an operation failed because the system is out of memory.
... when the javascript engine tries to allocate memory and allocation fails, it reports an error as though by
calling this function.
...
call js_reportallocationoverflow if an operation fails because it tries to use more memory (or more of some other resource) than the application is designed to handle.
... when a script tries to grow an array beyond 230-1 elements, for example, or concatenate strings such that the result is more than 229-1 characters long, the javascript engine reports an error as though by
calling this function.
JS_ReportPendingException
forward the current pending exception in a given jscontext to the current jserrorreporter
callback.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...on success, it clears the exception as though by
calling js_clearpendingexception and returns true.
...note that certain jsapi functions automati
cally do this for uncaught exceptions; see "automatic handling of uncaught exceptions" in the jsapi user guide.
JS_SetArrayLength
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...you can
call js_setarraylength either to set the number of elements for an array object you created without specifying an initial number of elements, or to change the number of elements allocated for an array.
...to initialize an element
call js_defineelement.
... if you
call js_setarraylength on an existing array, and length is less than the highest index number for previously defined elements, all elements greater than or equal to length are automati
cally deleted.
JS_SetPrincipalsTranscoder
set the runtime-wide principals transcoder
callback.
...in spidermonkey 1.8.1 or later, use js_setruntimesecurity
callbacks instead.
... description js_setprincipalstranscoder sets a runtime-wide
callback which the javascript engine uses to serialize and deserialize principals.
... this
callback is described at jsprincipalstranscoder.
JS_YieldRequest
syntax void js_yieldrequest(jscontext *cx); name type description cx jscontext * the jscontext that is currently in a request on the
calling thread.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...a program can
call this function periodi
cally to ensure that a long-running request does not block garbage collection indefinitely.
... the effect is the same as a
call to js_suspendrequest immediately followed by a
call to js_resumerequest.
Running Automated JavaScript Tests
there are two test suites, affectionately
called "jstests" and "jit-tests".
... sometimes jstests are
called js reftests because of how they are run in the browser.
... running jit-tests on treeherder when viewing treeherder after a push to the mozilla repositories, jit-tests are run by
calling make check, and appear under b.
...the test harness will automati
cally find the test and run it.
WebReplayRoadmap
we would like to use web replay to radi
cally improve not just the debugging experience but the entire web development experience.
... aggregate
call graph and data flow (not yet implemented) when developing a complex web app it is often hard to find where a function is
called, the
callees at a
call site, where some data in an object came from or where it is used, or what type a value has.
... an alternate use of the types that appear in practice would be to provide seed information for automati
cally populating the types in an app that is being converted to use flow or typescript.
... all features should be accessible to users operating lo
cally.
Gecko object attributes
applied to: listitem, option exposed in aria: aria-setsize live region attribues atomic true when the entire region should be presented as a whole, when changes within it are considered important enough to automati
cally present.
... applied to: any role exposed via aria: aria-atomic live a hint as to whether changes within the current region or subtree should be automati
cally presented.
...in this case action 0 is
called "cycles", which moves to the next option in the same way a manual click does.
...for example, a heading, paragraph, or list item is typi
cally formatted as a block, but there is no requirement to do so.
Embedded Dialog API
part of gecko's embedding api is
callbacks into the embedding application for creating new windows.
...this is accomplished using a
callback into the embedding application.
... responsibilities of mozilla/gecko component authors writing replaceable dialogs dialogs posed by the browser ("up
calls") any component which may be included in an embedded browser distribution and wishes to pose a dialog must group its ui (code which runs its dialogs) into a unique interface built just for that purpose.
...the print dialogs should be available soon.) dialogs posed by the embedding app ("down
calls") some components will not pose dialogs directly, but maintain a database of information an embedding app may wish to display as a dialog.
Using the Places annotation service
c++
callers will want to use getpageswithannotationcomarray which returns a com array, making memory management much easier and reducing the chance of leaks.
...c++
callers will want to use getpageannotationnamestarray which returns a com array, making memory management much easier and reducing the chance of leaks.
...you can get an annotation uri for a given uri/name pair by
calling: getannotationuri(auri, aname); in order for the annotation protocol to work, the annotation in question must have been declared with a mime type.
...the objects must implement four methods, which are
called when an annotation is set/removed on a uri or item respectively: onpageannotationset(auri, aname); onitemannotationset(aitemid, aname); onpageannotationremoved(auri, aname); onitemannotationremoved(aitemid, aname); var observer = { onpageannotationset : function(auri, aname) { }, onitemannotationset : function(aitemid, aname) { }, onpageannotationremoved : function(auri, aname) { ...
Detailed XPCOM hashtable guide
good hashtable implementations will automati
cally resize the hashtable in memory if extra space is needed, or if too much space has been allocated.
... nsthashtable - low-level c++ wrapper around pldhash; generates
callback functions and handles most casting automagi
cally.
...it hides many of the complexities of pldhash (
callback functions, the ops structure, etc).
...they provide the following features: hashtable operations can be completed without using an entry class, making code easier to read; optional thread-safety: the hashtable can manage a read-write lock around the table; predefined key classes provide automatic cleanup of strings/interfaces nsinterfacehashtable and nsclasshashtable automati
cally release/delete objects to avoid leaks.
Components.utils.waiveXrays
waives xray vision for an object, giving the
caller a transparent wrapper to the underlying object.
...waiving xrays is transitive, so waiving it for an object automati
cally waives it for any properties of that object (and their properties, and so on).
...to undo waivexrays and get xray vision back,
call components.utils.unwaivexrays on the object.
... the result of waivexrays is just like the wrappedjsobject property for xrayed objects, but it's more useful because you can
call it on primitives or objects that aren't xrays, in which case it just returns the argument you passed in.
Components object
constructor constructor for constructor of components exception constructor for xpconnect exceptions id constructor for xpcom nsids interfaces array of interfaces by interface name interfacesbyid array of interfaces by iid issuccesscode function to determine if a given result code is a success code lastresult result code of most recent xpconnect
call manager the global xpcom component manager results array of known result codes by name returncode pending result for current
call stack current javascript
call stack utils provides access to several useful features utils.atline provides access to the value of the atline property in the javascript environment.
...may only be
called from javascript code.
...may only be
called from javascript code.
... utils.scheduleprecisegc requests that garbage collection occur sometime in the future when no javascript code is running; accepts a
callback function to receive notification once collection is complete.
XPConnect wrappers
this wrapper is responsible for mapping
calls from javascript into c++.
... this means that when you say window.focus(), you're
calling into xpcwrappednative code.
... if you
call 'tostring()' and get "[xpconnect wrapped nsifoo]" then the reference is to a xpcwrappednative object with interface nsifoo.
...c++
calls are routed through xpcwrappedjs code into your javascript implementation.
NS_ShutdownXPCOM
« xpcom api reference summary the ns_shutdownxpcom function terminates use of xpcom in the
calling process.
... remarks you must
call this method once you are finished using xpcom.
...
calling this method triggers the "xpcom-shutdown" notification to be dispatched to observers.
... once this function has been
called, the nsicomponentmanager and nsiservicemanager will refuse to return object instances.
NS_ConvertASCIItoUTF16
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
NS_ConvertUTF16toUTF8
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
NS_ConvertUTF8toUTF16
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
NS_LossyConvertUTF16toASCII
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsACString_internal
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsAString_internal
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsAdoptingCString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsAdoptingString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsAutoString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsCAutoString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsCString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsDependentCString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsDependentCSubstring
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsDependentString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsDependentSubstring
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsFixedCString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsFixedString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsPromiseFlatCString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsPromiseFlatString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
nsString
call this version when you know the length of 'data'.
...
call this version when 'data' is null-terminated.
... the
caller must not modify the characters at the returned address.
... the
caller may modify the characters at the returned address (up to but not exceeding the length of the string).
XPCOM glue classes
this class is typi
cally used to represent ascii or utf-8 character arrays.nsacstring (external)class declarationnsacstring_internalclass declarationnsadoptingcstringclass declarationnsadoptingstringclass declarationnsastringthe nsastring abstract class represents a character string composed of double-byte storage units.
... this class is typi
cally used to represent unicode character arrays.nsastring (external)class declarationnsastring_internalclass declarationnsautorefnsautoref<t> is a template class implementing an object that holds a handle to a resource that must be released, typi
cally on destruction of the object.</t>nsautoreftraitsnsautoreftraits<t> is a template class describing traits of resources held by objects of class nsautoref<t> and/or nscountedref<t>.</t>nsautostringclass declarationnsautostring (external)class declarationnscautostringclass declarationnscautostring (external)class declarationnscomptrthis utility class simplifies managing xpcom interface references from c++ code.nscountedrefnscountedref<t> is a template class implementing an object that takes a strong reference to a reference-count...
...ed resource that must be released, typi
cally on destruction of the object.</t>nscstringclass declarationnscstring externalclass declarationnscstringcontainer (external)class declaration nscstringencodingthe nscstringencoding enumeration describes the set of character encodings understood by the ns_cstringtoutf16 and ns_utf16tocstring functions.nsdependentcstringclass declarationnsdependentcstring externalclass declarationnsdependentcsubstringclass declarationnsdependentcsubstring externalclass declarationnsdependentstringclass declarationnsdependentstring externalclass declarationnsdependentsubstringclass declarationnsdependentsubstring externalclass declarationnsembedcstringthe nsembedcstring concrete class provides a way to construct a nsacstring object that allocates null-terminated sto...
...this is done using the functions addref() and release(), which respectively modify a variable of type nsautorefcnt, which basi
cally is a wrapper around a count of the number of references refering to the class.nsstringclass declarationnsstring externalclass declarationnsstringcontainer (external)class declarationnssupportsweakreferenceinherit from this c++ class to add canonical support for nsisupportsweakreference.nsxpidlcstringclass declarationnsxpidlstringclass declarationpromiseflatcstring (external)class declarationprom...
IAccessibleTable
1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) typi
cally all accessible objects that represent cells or cell-clusters of a table will be at the same time children of the table.
... in this case iaccessible2.indexinparent() will return the child index which then can be used when
calling rowindex() and columnindex().
...typi
cally this is the value returned from iaccessible2.indexinparent(), but in the case where the table cells are not direct children of the table this is the cell index specified by the "table-cell-index" object attribute obtained from parsing the attributes string returned by
calling iaccessible2.attributes() on the cell object.
...typi
cally this is the value returned from iaccessible2.indexinparent(), but in the case where the table cells are not direct children of the table this is the cell index specified by the "table-cell-index" object attribute obtained from parsing the attributes string returned by
calling iaccessible2.attributes() on the cell object.
amIInstallTrigger
toolkit/mozapps/extensions/amiinstalltrigger.idlscriptable
called when an install completes or fails.
... 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 boolean enabled(); boolean install(in nsivariant aargs, [optional] in amiinstall
callback a
callback); boolean installchrome(in pruint32 atype, in astring aurl, in astring askin); deprecated since gecko 2.0 boolean startsoftwareupdate(in astring aurl, [optional] in print32 aflags); deprecated since gecko 2.0 boolean updateenabled(); deprecated since gecko 2.0 constants retained for backwards compatibility.
... boolean install( in nsivariant aargs, in amiinstall
callback a
callback optional ); parameters aargs the add-ons to install.
... a
callback optional a
callback to
call as each installation succeeds or fails.
mozIColorAnalyzer
toolkit/components/places/mozicoloranalyzer.idlscriptable provides methods to analyze colors in an image 1.0 66 introduced gecko 17.0 inherits from: nsisupports last changed in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) method overview void findrepresentativecolor(in nsiuri imageuri, in mozirepresentativecolor
callback
callback); methods findrepresentativecolor() given an image uri, find the most representative color for that image based on the frequency of each color.
...void findrepresentativecolor( in nsiuri imageuri, in mozirepresentativecolor
callback
callback ); parameters imageuri a uri pointing to the image - ideally a data: uri, but any scheme that will load when setting the src attribute of a dom img element should work.
...
callback function to
call when the representative color is found or an error occurs.
... remarks below are some images with the result of findrepresentativecolor: image representative color 0xb28d3a 0x502e1e 0x53ba3f 0x00a400 see also mozirepresentativecolor
callback bug 634139 ...
mozIRegistry
in this section, i'll discuss a number of different components, their requirements for dynami
cally binding to other components, and how they might utilize the core xpcom components to satisfy those requirements.
... nsrepository this is basi
cally the same as is provided today (see mozilla/xpcom/public/nsrepository.h).
... the primary change to this component is that we will modify it to utilize the new moziregistry interface versus the nsreg.h functions it
calls today.
...basi
cally, we envision such services to be based on the moziregistry interface.
mozIStorageService
the database should not be open, or you should ensure that no database activity is happening when you
call this method.
...if this method throws ns_error_file_corrupted, it's recommended that you
call mozistorageservice.backupdatabasefile() to back up the database so that user data is not lost (although we have no way of recovering this data yet).
...note: you should only access the profile database from the main thread since other
callers may also be using it.
...if this method throws ns_error_file_corrupted, it's recommended that you
call mozistorageservice.backupdatabasefile() to back up the database so that user data is not lost (although we have no way of recovering this data yet).
mozIStorageVacuumParticipant
/storage/public/mozistoragevacuumparticipant.idlscriptable components can implement this interface to provide information to allow a database to be periodi
cally vacuumed by the storage service.
... methods onbeginvacuum()
called when a vacuum operation begins.
... once you receive this notification, you should avoid using the database until onendvacuum() is
called.
...onendvacuum()
called when a vacuum operation ends.
nsIAccessible
getaccessibletoright this method returns an accessible node geometri
cally to the right of this one.
... getaccessibletoleft this method returns an accessible node geometri
cally to the left of this one.
... getaccessibleabove this method returns an accessible node geometri
cally above this one.
... getaccessiblebelow this method returns an accessible node geometri
cally below this one.
nsIAccessibleText
it represents the current input position and will therefore typi
cally be queried by at more often than other positions.
...its height typi
cally being the maximal height of all the characters in the text or the height of the preceding character, its width being at least one pixel so that the bounding box is not degenerate.
...it represents the current input position and will therefore typi
cally be queried by at more often than other positions.
...its height typi
cally being the maximal height of all the characters in the text or the height of the preceding character, its width being at least one pixel so that the bounding box is not degenerate.
nsIApplicationCacheChannel
inherits from: nsiapplicationcachecontainer last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void markofflinecacheentryasforeign(); attributes attribute type description chooseapplicationcache boolean when true, the channel will choose an application cache if one was not explicitly provided and none is available from the notification
callbacks.
...exceptions thrown ns_error_already_opened if set after
calling asyncopen() on the channel.
... inheritapplicationcache boolean true if the channel will ask its notification
callbacks for an application cache if one is not explicitly provided.
...exceptions thrown ns_error_already_opened if set after
calling asyncopen() on the channel.
nsICache
that is typi
cally in system ram.
...that is typi
cally on a system's hard disk.
...this constant specify that cache session is not a stream based entry when
calling nsicacheservice.createsession() method.
...this constant specify that cache session is a stream based entry when
calling nsicacheservice.createsession() method.
nsIComponentRegistrar
this method may only be
called from the main thread.
...this method may only be
called from the main thread.
...this value is passed into the nsimodule.registerself()
callback and must be forwarded unmodified when registering factories via their location.
...this value is passed into thensimodule.registerself()
callback and must be forwarded unmodified when registering factories via their location.
nsICookieManager
mplemented by the @mozilla.org/cookiemanager;1 component, but should generally be accessed via services.cookies method overview void remove(in autf8string ahost, in acstring aname, in autf8string apath, in boolean ablocked, in jsval aoriginattributes); void removeall(); attributes attribute type description enumerator nsisimpleenumerator
called to enumerate through each cookie in the cookie list.
... methods remove() this method is
called to remove an individual cookie from the cookie list, specified by host, name, and path.
...typi
cally, the arguments to this method will be obtained directly from the desired nsicookie object.
... removeall() this method is
called to remove all cookies from the cookie list.
nsIDirectoryService
this method must be
called before an nsidirectoryservice instance can be used.
... in the case of the xpcom directory service, this method is
called as part of xpcom initialization.
... must not be
called by external code;
called internally by xpcom initialization.
...
call unregisterprovider() to force the directory service to relinquish ownership of a particular provider instance.
nsIDownloadManager
note: adding a download doesn't automati
cally begin the transfer.
... if you want to both add and start a download, you need to create an nsiwebbrowserpersist object,
call this method, set the progresslistener to the returned nsidownload object, and then
call the nsiwebbrowserpersist.saveuri() method.
...this
calls cancel(ns_binding_aborted) on the nsicancelable provided by the download.
...
called when the download manager front end is closed.
nsIFileInputStream
close_on_eof 1<<2 if this is set, the file will close automati
cally when the end of the file is reached.
...(the file will only be reopened if it is closed for some reason.) defer_open 1<<4 if this is set, the file will be opened (i.e., a
call to pr_open() done) only when we do an actual operation on the stream, or more specifi
cally, when one of the following is
called: seek() tell() available() read() readline() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well.
... note: using this flag results in the file not being opened during the
call to init.
...also, the file is not locked when init is
called, so it might be deleted before we try to read from it.
nsILoadGroup
notification
callbacks nsiinterfacerequestor notification
callbacks for the load group.
...if this is a foreground request then the groupobserver's onstartrequest will be
called.
...if this is a foreground request then the groupobserver's onstoprequest will be
called.
... by the time this
call ends, arequest will have been removed from the loadgroup, even if this function throws an exception.
nsIMIMEInputStream
sses["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.nsimimeinputstream); method overview void addheader(in string name, in string value); void setdata(in nsiinputstream stream); attributes attribute type description addcontentlength boolean when true a "content-length" header is automati
cally added to the stream.
... the value of the content-length is automati
cally calculated using the available() method on the data stream.
...may not be
called once the stream has been started to be read.
...may not be
called once the stream has been started to be read.
nsIModule
return value indicates to the
caller whether or not the component module can be unloaded.
...if the component module is native (that is, as part of a dll), then this method may be
called to determine whether or not the dll may be unloaded from memory.
... registerself() when the nsimodule is discovered, this method will be
called so that any setup registration can be preformed.
... unregisterself() when the nsimodule is being unregistered, this method will be
called so that any unregistration can be preformed.
nsIMsgDatabase
boolean containskey(in nsmsgkey key); parameters key createnewhdr() must
call addnewhdrtodb after creating.
... the idea is that you create a new header, fill in its properties, and then
call addnewhdrtodb.
...if deleteviafolder is true, we'll
call nsimsgfolder.deletemessages() to delete the messages.
...the
caller should free when done using nsmemory.free().
nsIMsgWindow
notification
callbacks nsiinterfacerequestor these are currently used to set notification
callbacks on protocol channels to handle things like bad cert exceptions.
... promptdialog nsiprompt readonly: this is the equivalent of
calling getinterface on the rootdocshell object.
...this is equivalent to
calling loaduri on the nsiwebnavigation object with a data: url specifying the html.
... stopurls() this is equivalent to
calling stop(nsiwebnavigation::stop_network) on the nsiwebnavigation object.
nsIObserver
inherits from: nsisupports last changed in gecko 0.9.6 method overview void observe(in nsisupports asubject, in string atopic, in wstring adata); methods observe() this method will be
called when there is a notification for the topic that the observer has been registered for.
... a single nsiobserver implementation can observe multiple types of notification, and is responsible for dispatching its own behavior on the basis of the parameters for a given
callback.
... in general, atopic is the primary criterion for such dispatch; nsiobserver implementations should take care that they can handle being
called with unknown values for atopic.
...with this implementation, it's safe (and common practice) for an implementation of nsiobserver to remove itself as an observer during the observe
callback, or to add or remove other observers.
nsIPluginHost
the
caller is required to free the resulting memory with nsimalloc.free().
...the
caller is responsible for opening the channel.
... it may or may not be already opened when this function is
called.
...it will *always malloc()* output buffer (
caller is responsible to free it) if input buffer starts with lf, which comes from 4.x spec http://developer.netscape.com/docs/manuals/communicator/plugin/pgfn2.htm#1007754 "if no custom headers are required, simply add a blank line ('\n') to the beginning of the file or buffer.", it skips that '\n' and considers rest of the input buffer as data.
nsIPrefBranch2
for example holding the "root" prefbranch and
calling addobserver("foo.bar.", ...) will observe changes to foo.bar.baz and foo.bar.bzip.
... note: you must
call removeobserver method on the same nsiprefbranch2 instance on which you
called addobserver() method in order to remove aobserver; otherwise, the observer will not be removed.
...however, the observers are not guaranteed to be notified in any particular order, so you can't be sure whether the added/removed observer will be
called during the notification when it is added/removed.
... it is not safe to change observers during this
callback in releases before gecko 1.9.
nsIProcess
once initialized, you can start the process executing by
calling run().
... runasync() asynchronously runs the process with which the object was initialized, optionally
calling an observer when the process finishes running.
... runwasync() asynchronously runs the process with which the object was initialized, optionally
calling an observer when the process finishes running.
...// if first param is true,
calling thread will be blocked until //
called process terminates.
nsIScriptableUnescapeHTML
this is equivalent to
calling nsiparserutils::parsefragment(fragment, 0, isxml, baseuri, element).
... you should
call nsiparserutils::parsefragment() instead of
calling this method.
... this is equivalent to
calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0).
... you should
call nsiparserutils::converttoplaintext() instead of
calling this method.
nsISelectionController
scroll_center_verti
cally 1<<4 if set, the specified location will be scrolled to the center of the view.
...note: if issynchronous is true,
calling this method may flush the pending reflow.
...can be
called any time.
...can be
called any time.
nsISessionStore
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in versions of firefox prior to 3.5, the user preference browser.sessionstore.enabled must be true for these
calls to be successful.
... if the preference browser.sessionstate.enabled is false when this method is
called, then you will get an exception about "awindows[i] has no properties".
... note: this function is intended for use only by the browser; extensions shouldn't
call it.
... note:
calling setbrowserstate immediately replaces the current session, restoring the state of the entire application to the state passed in the astate parameter.
nsISocketTransport
to create an instance,
call nsisockettransportservice.createtransport() method overview prnetaddr getpeeraddr(); native code only!
... security
callbacks nsiinterfacerequestor security notification
callbacks passed to the secure socket provider via nsisslsocketcontrol at socket creation time.
... 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.
... remarks this is a free-threaded interface, meaning that the methods on this interface may be
called from any thread.
nsISound
note that nsisound instances may play the sounds using another thread; however, this is not controlled by the
caller.
...other methods will
call init if they need to.
...if you wish to use this method for playing sounds, you should check the platform before you
call playsystemsound().
... typi
cally, it will be more useful to request that appropriate sounds be played based on which event you wish to represent by the sound effect.
nsIStreamConverter
you can supply data directly to the converter by
calling it's nsistreamlistener.ondataavailable() method.
... it will then convert that data from type x to your desired output type and return converted data to you via the nsistreamlistener you passed in by
calling its nsistreamlistener.ondataavailable() method.
...ring atotype, in nsistreamlistener alistener, in nsisupports actxt); nsiinputstream convert(in nsiinputstream afromstream, in string afromtype, in string atotype, in nsisupports actxt); methods asyncconvertdata() asynchronous version: converts data arriving via the converter's nsistreamlistener.ondataavailable() method from one type to another, pushing the converted data out to the
caller via alistener::ondataavailable().
... use this method when you want to proxy (and convert) nsistreamlistener
callbacks asynchronously.
nsIStringBundleService
this is typi
cally a locale url, e.g.
... on the return value object on you can
call functions like getstringfromname and formatstringfromname see nsistringbundle.
...(automati
cally
called for the memory-pressure and chrome-flush-caches global observer topics.) void flushbundles(); parameters none.
...typi
cally used to format a message received by a nsiprogresseventsink's onstatus method.
nsIThreadInternal
the observer will be released on the thread corresponding to this thread object after all other events have been processed during a
call to shutdown.
... methods popeventqueue() reverts a
call to pusheventqueue().
... pusheventqueue() causes any events currently enqueued on the thread to be suppressed until popeventqueue() is
called.
...
calls to pusheventqueue() may be nested, and must each be paired with a corresponding
call to popeventqueue() to restore the original state of the thread.
nsITraceableChannel
each listener
call through to the previous listener for every
call, in order to establish a
call chain to allow all interested parties a chance to act on each event.
... 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.
...in particular, listeners typi
cally should not be replaced after onstartrequest has been
called.
... now i didnt set up rejection, but i should listen to on abort or bade status code then reject maybe } ).catch( function(acatch) { console.error('something went wrong, a typo by dev probably:', acatch); } ); } }; services.obs.addobserver(httpresponseobserver, 'http-on-examine-response', false); // services.obs.removeobserver(httpresponseobserver, 'http-on-examine-response'); //
call this when you dont want to listen anymore ...
nsIUpdatePrompt
if the app.update.silent preference is true or the user interface is already displayed the
call will be a no-op.
...if background is true (for example the download was not user initiated) and the app.update.silent preference is true the
call will be a no-op.
...if the app.update.silent preference is true the
call will be a no-op.
...if the app.update.silent preference is true, the app.update.showinstalledui preference is false, or the user interface is already displayed the
call will be a no-op.
nsIUpdateTimerManager
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void registertimer(in astring id, in nsitimer
callback
callback, in unsigned long interval); methods registertimer() presents a user interface that checks for and displays the available updates.
... void registertimer( in astring id, in nsitimer
callback
callback, in unsigned long interval ); parameters id an id used to identify the timer interval; used for persistence.
...
callback an nsitimer
callback object that is notified when the interval expires.
... in order to avoid having to instantiate a component to
call the registertimer() method, the component can instead register an update-timer category with comma-separated values as a single string representing the timer, like this: _xpcom_categories: [{ category: "update-timer", value: "contractid," + "method," + "id," + "preference," + "interval" }], this allows you to schedule the timer without actually having to instantiate the component; instead, the component is instant...
nsIWebContentHandlerRegistrar
typi
cally they will prompt the user to confirm adding an entry to the local list.
... contentwindow the dom content window from which the method has been
called.
... contentwindow the dom content window from which the method has been
called.
... permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler'permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler' when
calling method: [nsiwebcontenthandlerregistrar::registerprotocolhandler] if the host names do match then a confirmation like this will be seen: this domain check can be bypassed by setting the preference of gecko.handlerservice.allowregisterfromdifferenthost to true as in this code here: var {classes: cc, interfaces: ci, utils: cu} = components; cu.import("resource://gre/modules/services.jsm"); ...
nsIZipReader
parsemanifest must be
called first.
... if aentryname is an entry in the jar, getinputstream() must be
called after parsemanifest.
... if aentryname is an external file which has meta-information stored in the jar, verifyexternalfile (not yet implemented) must be
called before getprincipal.
... note: prior to gecko 1.9 you first had to
call init()"." void open( in nsifile zipfile ); parameters zipfile the zip file to open.
wrappedJSObject
in this example we use getservice, but as long as we get the reference from xpcom, our component gets wrapped by xpconnect in the same way: var comp = components.classes["@myself.com/my-component;1"].getservice(); if we try to
call the hello() method we defined in our component implementation, we get: > comp.hello(); typeerror on line 1: comp.hello is not a function this happens because, as we mentioned earlier, comp is not the helloworld js object itself, but an xpconnect wrapper around it: > dump(comp); [xpconnect wrapped nsisupports] the idea of these wrappers is to make the javascript-implemented xpcom components ...
...
calling queryinterface on the wrapper works, because it is defined in the nsisupports interface, and the wrapper knows the underlying object implements nsisupports: > comp.queryinterface(components.interfaces.nsihelloworld); [xpconnect wrapped (nsisupports, nsihelloworld)] as you can see, the queryinterface
call also made the wrapper know about the other interface our component supports.
... assuming the nsihelloworld interface defines the hello method, we can now
call it: > comp.hello() hello world!
... more specifi
cally, as xpconnect source comments say, you can get comp.wrappedjsobject if three conditions are met: comp really is an xpconnect wrapper around a js object.
XUL Overlays
loading overlays overlays can be loaded explicitly or dynami
cally.
...loading overlays dynami
cally the chrome registry makes it possible to load xul overlays dynami
cally -- or only when necessary.
...when a component such as the "super stream player" from the examples above is registered there, overlays associated with that component are loaded automati
cally.
...the master skin file for the bookmarks package, for example, is
called bookmarks.css, and is located in the skin/default subdirectory.
Address book sync client design
the static information that is held on the client for address book sync operations is stored in a file
called absync.dat which is located in the root directory of the users profile information.
... * * this method is
called regardless of whether the the operation was * successful.
...this method is *
called only once, at the beginning of a sync transaction * */ void onstartoperation(in print32 atransactionid, in pruint32 amsgsize); /** * notify the observer that progress as occurred for the ab sync operation */ void onprogress(in print32 atransactionid, in pruint32 aprogress, in pruint32 aprogressmax); /** * notify the observer with a status messag...
... * * this method is
called regardless of whether the the operation was * successful.
Mail event system
if the object just needs to be notified about one folder, it should
call that folder's addlistener method.
...the folder
calls notifyintpropertychanged on itself with the atom that represents "totalmessages": this->notifyintpropertychanged(ktotalmessagesatom, 4, 5);.
... notifypropertychanged broadcasts this event to each its nsifolderlisteners by
calling onitemintpropertychanged on each listener: listener->onintpropertychanged(this, ktotalmessagesatom, 4, 5); the dialog is one of these folder-specific listeners.
...for each global listener, it
calls onintpropertychanged: listener->onintpropertychanged(folder, ktotalmessagesatom, 4, 5); the folder datasource is a listener on all folders and receives this notification.
Mailnews and Mail code review requirements
flag should be set on the bug until the framework has been completed and the test code is running automati
cally.
... (you could still ask a reviewer to approve such things, though.) the patch does not change public test frameworks, specifi
cally, nothing in mailnews/test/resources/ or mail/test/mozmill/shared-modules/.
... for xpcshell tests, it has either passed on try or has been run lo
cally on the appropriate platform(s).
... specifi
cally, if the xpcshell test will do different things on windows than it will do on os x or linux, it must be run on windows and one of os x / linux.
CType
functiontype these represent
callable c functions.
...this is the result of
calling ctypes.pointertype(the_type).
... methods available on all ctype objects array() returns a new ctype representing an array of elements of the type on which it was
called.
...this is the same as
calling ctypes.arraytype(the_type[, n]).
Browser Side Plug-in API - Plugins
the names of all of these methods begin with npn_ to indicate that they are implemented by the browser and
called by the plug-in.
... warning: you must only
call these from the main thread;
calling them from other threads is not supported and may have unpredictable results.
... npn_getauthenticationinfo this function is
called by plug-ins to get http authentication information from the browser.
... npn_pluginthreadasync
call thread-safe way to request that the browser
calls a plug-in function on the browser or plug-in thread (the thread on which the plug-in was initiated).
Accessibility Inspector - Firefox Developer Tools
roles and other information exposed by browser accessibility apis are presented in a hierarchical structure
called the accessibility tree.
...for this reason, you should keep it turned off when you aren't specifi
cally using it.
...starting in firefox 79, it is automati
cally enabled when you do one of the following: choose accessibility in the tools > web developer menu.
... if you don't wish to allow the accessibility features to be automati
cally enabled, you can use the configuration editor (also known as about:config) to define the preference devtools.accessibility.auto-init.enabled, and set it to false.
Break on DOM mutation - Firefox Developer Tools
examples for when this breakpoint is triggered are
calling node.appendchild() and node.removechild(),
calling childnode.remove() or setting element.innerhtml on one of the subnodes.
... examples for when this breakpoint is triggered are
calling element.setattribute(), element.removeattribute(), and element.classlist.add(), or setting element.id.
... examples for when this breakpoint is triggered are
calling element.remove() or node.removechild() on its parent node.
... the panel on the right shows that execution is "paused on dom mutation" and you, as with any other breakpoint, you can see the
call stack and view any watch expressions you may have set up.
Set an XHR breakpoint - Firefox Developer Tools
to turn on the feature: open the debugger click on "pause on any url" which acts as a wild card, causing the code to pause on any
call, or, click the plus sign next to the xhr breakpoints header, enter the url in which you are interested, and press enter.
... note: if you enter a key word instead of a url, code execution will pause on any
call to a url that contains that keyword.
... when your code breaks on an xhr request, the righthand pane will have two additional sections:
call stack the list of functions that were executed in order ot get to the currently executing code.
... click on an item in the
call stack to jump to the associated line in the code display.
Debugger-API - Firefox Developer Tools
here is a javascript program in the process of running a timer
callback function: a running javascript program and its debugger shadows this diagram shows the various types of shadow objects that make up the debugger api (which all follow some general conventions): a debugger.object represents a debuggee object, offering a reflection-oriented api that protects the debugger from accidentally invoking getters, setters, proxy traps, and so on.
...you can set functions to be
called when new stack frames are pushed; when new code is loaded; and so on.
...a debugger.source can furnish a full copy of its source code, and explain how the code entered the system, whether via a
call to eval, a <script> element, or otherwise.
... showing how many objects different
call paths allocate.
Network request list - Firefox Developer Tools
this feature is
called race cache with network (rcwn).
... copy > copy as fetch copies the request as a
call to the fetch() method, including the url and any settings object.
... start performance analysis use as fetch in console submits the request as a
call to the fetch() method in the console.
...this means that the response will be automati
cally decompressed.
Sorting algorithms comparison - Firefox Developer Tools
this article describes a simple example program that we use in two of the performance guides: the guide to the
call tree and the guide to the flame chart.
...iteratively (200 iterations) generates a randomized array and
calls sort().
... sort()
calls each of bubblesort(), selectionsort(), quicksort() in turn and logs the result.
... its
call graph looks like this: sortall() // (generate random array, then
call sort) x 200 -> sort() // sort with each algorithm, log the result -> bubblesort() -> swap() -> selectionsort() -> swap() -> quicksort() -> partition() the implementations of the sorting algorithms in the program are taken from https://githu...
The JavaScript input interpreter - Firefox Developer Tools
there are three ways to select an iframe using cd(): you can pass the iframe dom element: var frame = document.getelementbyid("frame1"); cd(frame); you can pass a css selector that matches the iframe: cd("#frame1"); you can pass the iframe's global window object: var frame = document.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 commands the javascript command line provided by the web console offers a few built-in helper functions that make certain tasks easier.
...equivalent to document.queryselector() or
calls the $ function in the page, if it exists.
...otherwise, json.stringify will be
called on the argument, and the result will be copied to the clipboard.
AudioNode.connect() - Web APIs
the connect() method of the audionode interface lets you connect one of the node's outputs to a target, which may be either another audionode (thereby directing the sound data to the specified node) or an audioparam, so that the node's output data is automati
cally used to change the value of that parameter over time.
...while you can only connect a given output to a given input once (repeated attempts are ignored), you can connect an output to multiple inputs by
calling connect() repeatedly.
... return value if the destination is a node, connect() returns a reference to the destination audionode object, allowing you to chain multiple connect()
calls.
... // connect the gain to the destination so we hear sound gain.connect(audioctx.destination); // start the oscillator that will produce audio oscillator.start(); // start the oscillator that will modify the gain value lfo.start(); audioparam notes it is possible to connect an audionode output to more than one audioparam, and more than one audionode output to a single audioparam, with multiple
calls to connect().
AudioWorkletProcessor.process - Web APIs
the method is
called synchronously from the audio rendering thread, once for each block of audio (also known as a rendering quantum) being directed through the processor's corresponding audioworkletnode.
...if the combination of the return value and the state of the node causes the browser to decide to stop the node, process() will not be
called again.
...for example, take the audiobuffersourcenode — the processor behind such a node should return true from the process method while the buffer is playing, and start returning false when the buffer playing has ended (there's no way to
call play on the same audiobuffersourcenode again).
... a node that transforms its input, but has a so-
called tail-time — this means that it will produce an output for some time even after its inputs are disconnected or are inactive (producing zero-channels).
Beacon API - Web APIs
beacon requests use the http post method and requests typi
cally do not require a response.
... the beacon interface addresses the needs of analytics and diagnostics code that typi
cally attempts to send data to a web server before unloading the document.
... user agents will typi
cally ignore asynchronous xmlhttprequests made in an unload handler.
... to solve this problem, analytics and diagnostics code will typi
cally make a synchronous xmlhttprequest in an unload or beforeunload handler to submit the data.
Blob.stream() - Web APIs
usage notes with stream() and the returned readablestream, you gain several interesting capabilities:
call getreader() on the returned stream to get an object to use to read the data from the blob using methods such as the readablestreamdefaultreader interface's read() method.
...
call the returned stream's pipeto() method to pipe the blob's data to a writable stream.
...
call the returned stream's tee() method to tee the readable stream.
...
call the returned stream's pipethrough() method to pipe the stream through a transformstream or any other readable and writable pair.
CanvasRenderingContext2D.scale() - Web APIs
the canvasrenderingcontext2d.scale() method of the canvas 2d api adds a scaling transformation to the canvas units horizontally and/or verti
cally.
...the transformation matrix scales it by 9x horizontally and by 3x verti
cally.
... flipping things horizontally or verti
cally you can use scale(-1, 1) to flip the context horizontally and scale(1, -1) to flip it verti
cally.
... note that the
call to filltext() specifies a negative x coordinate.
Using images - Web APIs
importing images into a canvas is basi
cally a two step process: get a reference to an htmlimageelement object or to another canvas element as a source.
...n the document.getelementsbytagname() method if you know the id of the specific image you wish to use, you can use document.getelementbyid() to retrieve that specific image using images from other domains using the crossorigin attribute of an <img> element (reflected by the htmlimageelement.crossorigin property), you can request permission to load an image from another domain for use in your
call to drawimage().
... if you try to
call drawimage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception).
...we then simply use drawimage() to slice the rhino out of the first image and scale him onto the canvas, then draw the frame on top using a second drawimage()
call.
ConstantSourceNode - Web APIs
you can also create a constantsourcenode whose properties are initialized to their default values by
calling audiocontext.createconstantsource().
...then the constantsourcenode is created by
calling audiocontext.createconstantsource(), and the gain parameters of each of the two gain nodes are connected to the constantsourcenode.
... after starting the constant source by
calling its start() method.
... finally, the two gain nodes are connected to the audio destination (typi
cally speakers or headphones).
DOMTokenList.forEach() - Web APIs
the foreach() method of the domtokenlist interface
calls the
callback given in parameter once for each value pair in the list, in insertion order.
... syntax tokenlist.foreach(
callback [, thisarg]); parameters
callback function to execute for each element, eventually taking three arguments: currentvalue the current element being processed in the array.
... thisarg optional value to use as this when executing
callback.
...selector("span"); let classes = span.classlist; let iterator = classes.values(); classes.foreach( function(value, key, listobj) { span.textcontent += `${value} ${key}/${this} ++ `; }, "arg" ); result polyfill this polyfill adds compatibility to all browsers supporting es5: if (window.domtokenlist && !domtokenlist.prototype.foreach) { domtokenlist.prototype.foreach = function (
callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < this.length; i++) {
callback.
call(thisarg, this[i], i, this); } }; } specifications specification status comment domthe definition of 'foreach() (as iterable<node>)' in that specification.
DedicatedWorkerGlobalScope - Web APIs
some additional global functions, namespaces objects, and constructors, not typi
cally associated with the worker global scope, but available on it, are listed in the javascript reference.
... dedicatedworkerglobalscope.onmessage is an eventhandler representing the code to be
called when the message event is raised.
... these events are of type messageevent and will be
called when the worker receives a message from the document that started it (i.e.
... from the worker.postmessage method.) dedicatedworkerglobalscope.onmessageerror is an eventhandler representing the code to be
called when the messageerror event is raised.
DirectoryReaderSync - Web APIs
basic concepts before you
call the only method in this interface, readentries(), create the directoryentrysync object.
... but directoryentrysync (as well as fileentrysync) is not a data type that you can pass between a
calling app and web worker thread.
...
call this method until an empty array is returned.
... invalid_state_err the directory has been modified since the first
call to readentries was processed.
Document.createElement() - Web APIs
when
called on an html document, createelement() converts tagname to lower case before creating the element.
... html <!doctype html> <html> <head> <title>||working with elements||</title> </head> <body> <div id="div1">the text above has been created dynami
cally.</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...
... // create a class for the element class expandinglist extends htmlulistelement { constructor() { // always
call super first in constructor super(); // constructor definition left out for brevity ...
... } } // define the new element customelements.define('expanding-list', expandinglist, { extends: "ul" }); if we wanted to create an instance of this element programmati
cally, 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.
DocumentOrShadowRoot.getSelection() - Web APIs
example function foo() { var selobj = document.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert()), the object's tostring() method is
called and the returned value is passed to the function.
... in the above example, selobj.tostring() is automati
cally
called when it is passed to window.alert().
...to use a selection object as a string,
call its tostring() method directly: var selectedtext = selobj.tostring(); selobj is a selection object.
... related objects you can
call window.getselection(), which works identi
cally to document.getselection().
Element.getElementsByClassName() - Web APIs
usage notes as always, the returned collection is live, meaning that it always reflects the current state of the dom tree rooted at the element on which the function was
called.
... examples matching a single class to look for elements that include among their classes a single specified class, we just provide that class name when
calling getelementsbyclassname(): element.getelementsbyclassname('test'); this example finds all elements that have a class of test, which are also a descendant of the element that has the id of main: document.getelementbyid('main').getelementsbyclassname('test'); matching multiple classes to find elements whose class lists include both the red and test classes: element.getelementsbyclassname('r...
...atches[i].classlist.remove('colorbox'); matches.item(i).classlist.add('hueframe'); } instead, use another method, such as: var matches = element.getelementsbyclassname('colorbox'); while (matches.length > 0) { matches.item(0).classlist.add('hueframe'); matches[0].classlist.remove('colorbox'); } this code finds descendant elements with the "colorbox" class, adds the class "hueframe", by
calling item(0), then removes "colorbox" (using array notation).
...here we'll find all <div> elements that have a class of test: var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.
call(testelements, function(testelement) { return testelement.nodename === 'div'; }); specifications specification status comment domthe definition of 'element.getelementsbyclassname()' in that specification.
Event.preventDefault() - Web APIs
the event continues to propagate as usual, unless one of its event listeners
calls stoppropagation() or stopimmediatepropagation(), either of which terminates propagation at once.
... as noted below,
calling preventdefault() for a non-cancelable event, such as one dispatched via eventtarget.dispatchevent(), without specifying cancelable: true has no effect.
...x.innerhtml = msg; if (document.body.contains(warningbox)) { window.cleartimeout(warningtimeout); } else { // insert warningbox after mytextbox mytextbox.parentnode.insertbefore(warningbox, mytextbox.nextsibling); } warningtimeout = window.settimeout(function() { warningbox.parentnode.removechild(warningbox); warningtimeout = -1; }, 2000); } result notes
calling preventdefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
...
calling preventdefault() for a non-cancelable event has no effect.
EventSource - Web APIs
the connection remains open until closed by
calling eventsource.close().
... event handlers eventsource.onerror is an eventhandler
called when an error occurs and the error event is dispatched on an eventsource object.
... eventsource.onmessage is an eventhandler
called when a message event is received, that is when a message is coming from the source.
... eventsource.onopen is an eventhandler
called when an open event is received, that is when the connection was just opened.
EventTarget.dispatchEvent() - Web APIs
return value the return value is false if event is cancelable and at least one of the event handlers which received event
called event.preventdefault().
... the dispatchevent() method throws unspecified_event_type_err if the event's type was not specified by initializing the event before the method was
called, or if the event's type is null or an empty string.
...the event handlers run on a nested
callstack; they block the
caller until they complete, but exceptions do not propagate to the
caller.
...all applicable event handlers will execute and return before the code continues on after the
call to dispatchevent().
FileReader.readyState - Web APIs
none of the read methods
called yet.
... 1 loading a read method has been
called.
... empty the filereader has been created, but no readas method was
called yet.
...this could mean that: the entire file or blob has been read into memory, a file read error occurred, or abort() was
called and the read was cancelled.
FileSystemDirectoryEntry.createReader() - Web APIs
example this example creates a method
called readdirectory(), which fetches all of the entries in the specified filesystemdirectoryentry and returns them in an array.
...entries = []; let getentries = function() { dirreader.readentries(function(results) { if (results.length) { entries = entries.concat(toarray(results)); getentries(); } }, function(error) { /* handle error -- error is a fileerror object */ }); }; getentries(); return entries; } this works by creating an internal function, getentries(), which
calls itself recursively to get all the entries in the directory, concatenating each batch to the array.
... each iteration, readentries() is
called to get more entries.
...once control is returned to readdirectory(), the array is returned to the
caller.
FileSystemEntry.remove() - Web APIs
to recursively remove a directory as well as all of its contents and its subdirectories,
call filesystemdirectoryentry.removerecursively() instead.
... syntax filesystementry.remove(success
callback[, error
callback]); parameters success
callback a function which is
called once the file has been successfully removed.
... error
callback optional an optional
callback which is
called if the attempt to remove the file fails.
... fileerror.security_err the entry couldn't be removed due to permissions or other access constraints, or because there are too many
calls being made on file resources.
Geolocation.watchPosition() - Web APIs
the geolocation method watchposition() method is used to register a handler function that will be
called automati
cally each time the position of the device changes.
... you can also, optionally, specify an error handling
callback function.
... syntax navigator.geolocation.watchposition(success[, error[, options]]) parameters success a
callback function that takes a geolocationposition object as an input parameter.
... error optional an optional
callback function that takes a geolocationpositionerror object as an input parameter.
Dragging and Dropping Multiple Items - Web APIs
using 0 as the index is equivalent to
calling setdata().
... border: 1px solid black;" ondragenter="document.getelementbyid('output').textcontent = ''; event.stoppropagation(); event.preventdefault();" ondragover="event.stoppropagation(); event.preventdefault();" ondrop="event.stoppropagation(); event.preventdefault(); dodrop(event);"> <div> fix</div> </div> </body> </html> this example cancels both the dragenter and dragover events by
calling the preventdefault().
... the dodrop event hander is
called when dropping an item.
...for each item, the moztypesat() method is
called to get the list of types.
HTML Drag and Drop API - Web APIs
each data item is a string of a particular type — typi
cally a mime type such as text/html.
...it typi
cally affects which cursor the browser displays while dragging.
...tatransfer.dropeffect = "move"; } function drop_handler(ev) { ev.preventdefault(); // get the id of the target and add the moved element to the target's dom const data = ev.datatransfer.getdata("text/plain"); ev.target.appendchild(document.getelementbyid(data)); } </script> <p id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">drop zone</p> note that each handler
calls preventdefault() to prevent additional event processing for this event (such as touch events or pointer events).
... typi
cally, an application uses the getdata() method to retrieve drag items and then process them accordingly.
IDBCursorSync - Web APIs
constants constant value description next 0 this cursor includes duplicates, and its direction is monotoni
cally increasing in the order of keys.
... next_no_duplicate 1 this cursor does not include duplicates, and its direction is monotoni
cally increasing in the order of keys.
... prev 2 this cursor includes duplicates, and its direction is monotoni
cally decreasing in the order of keys.
... prev_no_duplicate 3 this cursor does not include duplicates, and its direction is monotoni
cally decreasing in the order of keys.
IDBDatabase.createObjectStore() - Web APIs
this method can be
called only within a versionchange transaction.
... exceptions this method may raise a domexception with a domerror of one of the following types: exception description invalidstateerror occurs if the method was not
called from a versionchange transaction
callback.
... for older webkit browsers, you must
call first.
... example // let us open our database var request = window.indexeddb.open("todolist", 4); // this handler is
called when a new version of the database // is created, either when one has not been created before // or when a new version number is submitted by
calling // window.indexeddb.open().
IDBTransactionSync - Web APIs
methods abort()
call this method to signal a need to cancel the effects of the operations performed by this transaction.
... when this method is
called, the browser ignores all the changes performed to the objects of this database since this transaction was created.
... commit()
call this method to signal that the transaction has completed normally and satisfactorily.
... when this method is
called, the browser durably stores all the changes performed to the objects of the database since this transaction was created.
IdleDeadline.didTimeout - Web APIs
the read-only didtimeout property on the idledeadline interface is a boolean value which indicates whether or not the idle
callback is being invoked because the timeout interval specified when window.requestidle
callback() was
called has expired.
... idle
callbacks support the concept of a timeout in order to ensure that whatever task they're meant to perform actually happens, even if the user agent never has enough idle time available.
... your
callback will typi
cally 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.
... syntax var timedout = idledeadline.didtimeout; value a boolean which is true if the
callback is running due to the
callback's timeout period elapsing or false if the
callback is running because the user agent is idle and is offering time to the
callback.
IdleDeadline.timeRemaining() - Web APIs
the
callback can
call this method at any time to determine how much time it can continue to work before it must return.
... for example, if the
callback finishes a task and has another one to begin, it can
call timeremaining() to see if there's enough time to complete the next task.
... if there isn't, the
callback can just return immediately, or look for other work to do with the remaining time.
... by the time timeremaining() reaches 0, it is suggested that the
callback should return control to the user agent's event loop.
Keyboard API - Web APIs
histori
cally there has been no way to retrieve that information.
...those keys and key combinations are typi
cally captured by the user agent or the underlying operating system, as illustrated in the following example.
... to capture the "w", "a", "s", and "d" keys,
call lock() with a list that contains the key code attribute value for each of these keys: navigator.keyboard.lock(["keyw", "keya", "keys", "keyd"]); this captures these keys regardless of which modifiers are used with the key press.
... writing system keys the codes passed keyboard.lock and the various methods of the keyboardlayoutmap interface are
called “writing system keys”.
MediaKeyStatusMap.forEach() - Web APIs
the foreach property of the mediakeystatusmap interface
calls
callback once for each key-value pair in the status map, in insertion order.
... if an argument is present it will be passed to the
callback.
... syntax mediakeystatusmap.foreach(
callback[, thisarg]) parameters
callback function to execute for each element, taking three arguments: currentvalue the current element being processed in the array.
... thisarg optional value used as this when executing
callback.
MediaQueryList.removeListener() - Web APIs
this is basi
cally an alias for eventtarget.removeeventlistener(), for backwards compatibility purposes — in older browsers you could use removeeventlistener() instead.
... syntax mediaquerylist.removelistener(func) parameters func a function or function reference representing the
callback function you want to remove.
... in the original implementation, the
callback was a non-standard mediaquerylistlistener object.
... in the new implementation the standard event mechanism is used, and the
callback is a standard function.
MediaRecorder.ondataavailable - Web APIs
when mediarecorder.stop() is
called, all media data which has been captured since recording began or the last time a dataavailable event occurred is delivered in a blob; after this, capturing ends.
... 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.
...so if the method
call looked like this — recorder.start(1000); — the dataavailable event would fire after each second of media capture, and our event handler would be
called every second with a blob of media data that's one second long.
... 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); } ...
MediaSession.setActionHandler() - Web APIs
syntax navigator.mediasession.setactionhandler(type,
callback) parameters type a domstring representing an action type to listen for.
...
callback a function to
call when the specified action type is invoked.
... the
callback receives no input parameters, and should not return a value.
... description to remove a previously-established action handler,
call setactionhandler() again, specifying null as the
callback.
MediaStream - Web APIs
each track is specified as an instance of mediastreamtrack.you can obtain a mediastream object either by using the constructor or by
calling mediadevices.getusermedia().
...the order is not defined, and may not only vary from one browser to another, but also from one
call to another.
...the order is not defined, and may not only vary from one browser to another, but also from one
call to another.
...the order is not defined, and may not only vary from one browser to another, but also from one
call to another.
MediaStreamAudioSourceNode - Web APIs
this media could be from a microphone (through getusermedia()) or from a remote peer on a webrtc
call (using the rtcpeerconnection's audio tracks).
... usage notes typi
cally, you should probably not use this type of node.
...this is why it is typi
cally wiser to use mediastreamtrackaudiosourcenode, which provides similar capabilities but was better-defined upon being added to the specification, so it's more reliable.
... 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.
MediaStream Image Capture API - Web APIs
first, get a reference to a device by
calling mediadevices.getusermedia().
...do this by
calling mediastream.getvideotracks().
...you can do this by
calling applyconstraints() on the track object before doing anything else.
...retrieve a photocapabilities object by
calling imagecapture.getphotocapabilities().
MediaTrackConstraints.cursor - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.cursor as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
... syntax var constraintsobject = { cursor: constraint }; constraintsobject.cursor = constraint; value a constraindomstring which specifies whether or not the mouse cursor should be rendered into the video track in the mediastream returned by the
call to getdisplaymedia().
... usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by
calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's cursor object.
MediaTrackConstraints.deviceId - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.deviceid as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
...that means that a given track will only return one value for the deviceid when you
call getcapabilities().
... because of this, there's no use for the device id when
calling mediastreamtrack.applyconstraints(), since there is only one possible value; however, you can record a deviceid and use it to ensure that you get the same source for multiple
calls to getusermedia().
MediaTrackConstraints.groupId - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.groupid as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
...that means that a given track will only return one value for the groupid when you
call getcapabilities(), and keep in mind that this value will change for each browsing session.
... because of this, there's no use for the group id when
calling mediastreamtrack.applyconstraints(), since there is only one possible value, and you can't use it to ensure the same group is used across multiple browsing sessions when
calling getusermedia().
MediaTrackSettings.deviceId - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.deviceid property you provided when
calling either getusermedia().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.deviceid as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
...that makes the device id not useful for any changes to constraints when
calling mediastreamtrack.applyconstraints().
MediaTrackSettings - Web APIs
this value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when
calling mediadevices.getusermedia().
...this value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when
calling mediadevices.getusermedia().
...the value will be one of: "user" a camera facing the user (commonly known as a "selfie cam"), used for self-portraiture and video
calling.
...this is typi
cally the highest quality camera on the device, used for general photography.
Media Capture and Streams API (Media Stream) - Web APIs
the media capture and streams api, often
called the media streams api or simply mediastream api, is an api related to webrtc which provides support for streaming audio and video data.
... it provides the interfaces and methods for working with the streams and their constituent tracks, the constraints associated with data formats, the success and error
callbacks when using the data asynchronously, and the events that are fired during the process.
...a mediastream object generated by getusermedia() is
called local, and has as its source input one of the user's cameras or microphones.
...this article discusses capabilities and constraints, as well as media settings, and includes an example we
call the constraint exerciser.
MutationObserverInit.attributeOldValue - Web APIs
function
callback(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).
... when observe() is
called, the specified options are attributes and attributeoldvalue, which means that changes to attribute values will be reported, and each mutation record will include the oldvalue property specifying the attribute's previous value.
NodeList.prototype.forEach() - Web APIs
the foreach() method of the nodelist interface
calls the
callback given in parameter once for each value pair in the list, in insertion order.
... syntax somenodelist.foreach(
callback[, thisarg]); parameters
callback a function to execute on each element of somenodelist.
... thisarg optional value to use as this when executing
callback.
...urrentvalue + ', ' + currentindex + ', ' + this); }, 'mythisarg' ); the above code results in the following: [object htmlparagraphelement], 0, mythisarg [object text], 1, mythisarg [object htmlspanelement], 2, mythisarg polyfill this polyfill adds compatibility to all browsers supporting es5: if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = function (
callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < this.length; i++) {
callback.
call(thisarg, this[i], i, this); } }; } or if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = array.prototype.foreach; } the above behavior is how many browsers actually implement nodelist.prototype.foreach() (chrome, for examp...
Page Visibility API - Web APIs
lide unless the user is viewing the page an application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible a page wants to detect when it is being prerendered so it can keep accurate count of page views a site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off) developers have histori
cally used imperfect proxies to detect this.
... policies in place to aid background page performance separately from the page visibility api, user agents typi
cally have a number of policies in place to mitigate the performance impact of background or hidden tabs.
... these may include: most browsers stop sending requestanimationframe()
callbacks to background tabs or hidden <iframe>s in order to improve performance and battery life.
... document.onvisibilitychange an eventlistener providing the code to be
called when the visibilitychange event is fired.
PaymentRequest.canMakePayment() - Web APIs
you can
call this before
calling show() to provide a streamlined user experience when the user's browser can't handle any of the payment methods you accept.
... for instance, you might
call canmakepayment() to determine if the browser will let the user pay using payment request api, and if it won't, you could fall back to another payment method, or offer a list of methods that aren't handled by payment request api (or even provide instructions for paying by mail or by phone).
... note: if you
call this too often, the browser may reject the returned promise with a domexception.
...it wraps the
call to canmakepayment() in feature detection, and
calls an appropriate
callback depending on the resolution of the promise.
PaymentRequest - Web APIs
this property is only populated if the constructor is
called with the requestshipping flag set to true.
...this property is only populated if the constructor is
called with the requestshipping flag set to true.
... methods paymentrequest.canmakepayment() secure context indicates whether the paymentrequest object can make a payment before
calling show().
... events merchantvalidation secure context with some payment handlers (e.g., apple pay), this event handler is
called to handle the merchantvalidation event, which is dispatched when the user agent requires that the merchant validate that the merchant or vendor requesting payment is legitimate.
Performance.onresourcetimingbufferfull - Web APIs
the onresourcetimingbufferfull property is an event handler that will be
called when the resourcetimingbufferfull event is fired.
... syntax
callback = performance.onresourcetimingbufferfull = buffer_full_cb; return value
callback an eventhandler that is invoked when the resourcetimingbufferfull event is fired.
... examples the following example sets a
callback function on the onresourcetimingbufferfull property.
... function buffer_full(event) { console.log("warning: resource timing buffer is full!"); performance.setresourcetimingbuffersize(200); } function init() { // set a
callback if the resource buffer becomes filled performance.onresourcetimingbufferfull = buffer_full; } <body onload="init()"> specifications specification status comment resource timing level 1the definition of 'onresourcetimingbufferfull' in that specification.
PerformanceMeasure - Web APIs
entries of this type are created by
calling performance.measure() to add a named domhighrestimestamp (the measure) between two marks to the browser's performance timeline.
... performanceentry.name returns the name given to the measure when it was created via a
call to performance.measure().
... performanceentry.starttime returns a timestamp given to the measure when performance.measure() was
called.
... performanceentry.duration returns a domhighrestimestamp that is the duration of the measure (typi
cally, the measure's end mark timestamp minus its start mark timestamp).
Performance Timeline - Web APIs
the standard also includes interfaces that allow an application to define performance observer
callbacks that are notified when specific performance events are added to the browser's performance timeline.
... performance observers the performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's
callback function that was specified when the observer was created.
... when the observer (
callback) is invoked, the
callback's parameters include a performance observer entry list that contains only observed performance entries.
...however, note there is one key difference with these methods; the performance observer entry list versions are used to retrieve observed performance entries within the observer
callback.
Using the Permissions API - Web APIs
histori
cally, different apis handle their own permissions inconsistently — for example the notifications api allows for explicit checking of permission status and requesting permission, whereas the geolocation api doesn't (which causes problems if the user denied the initial permission request, as we'll see below).
...for example, it can query whether permission to use a particular api is granted or denied, and specifi
cally request permission to use an api.
... a simple example for this article, we have put together a simple demo
called location finder.
... however, future additions to browser functionality should provide the request() method, which will allow us to programati
cally request permissions, any time we like.
PopStateEvent - Web APIs
if the history entry being activated was created by a
call to history.pushstate() or was affected by a
call to history.replacestate(), the popstate event's state property contains a copy of the history entry's state object.
... note: just
calling history.pushstate() or history.replacestate() won't trigger a popstate event.
... the popstate event is only triggered by doing a browser action such as a clicking on the back button (or
calling history.back() in javascript).
...ate: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate event is still fired when we activate that entry after the second
call to history.back().
RTCDataChannel.close() - Web APIs
either peer is permitted to
call this method to initiate closure of the channel.
... the sequence of events which occurs in response to this method being
called: rtcdatachannel.readystate is set to "closing".
... a background task is established to handle the remainder of the steps below, and close() returns to the
caller.
... in firefox, the rtcdatachannel interface was implemented under the name datachannel until firefox 24, so this method was
called datachannel.close().
RTCIceCandidate.usernameFragment - Web APIs
if you instead
call rtcicecandidate() with a string parameter containing the candidate m-line text, the value of usernamefragment is extracted from the m-line.
... when the web app receives a message from the signaling server that includes a candidate to be added to the rtcpeerconnection, you can (and generally should) simply
call addicecandidate().
... there's not typi
cally a need to manually worry about filtering the candidates.
...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.
RTCIceTransport - Web APIs
getlocalparameters() returns a rtciceparameters object describing the ice parameters established by a
call to the rtcpeerconnection.setlocaldescription() method.
... getremotecandidates() returns an array of rtcicecandidate objects, one for each of the remote device's ice candidates that have been received by the local end of the rtcpeerconnection and delivered to ice by
calling addicecandidate().
... getremoteparameters() returns a rtciceparameters object containing the ice parameters for the remote device, as set by a
call to rtcpeerconnection.setremotedescription().
... if setremotedescription() hasn't been
called yet, the return value is null.
RTCPeerConnection() - Web APIs
if this property isn't specified, a set of certificates is generated automati
cally for each rtcpeerconnection instance.
... this configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future
calls to rtcpeerconnection.setconfiguration().
...you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is
called.
... iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent; these are typi
cally stun and/or turn servers.
RTCPeerConnection.restartIce() - Web APIs
this simplifies the process by allowing the same method to be used by either the
caller or the receiver to trigger an ice restart.
... after restartice() returns, the offer returned by the next
call to createoffer() is automati
cally configured to trigger ice restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well.
... usage notes after
calling restartice(), the next offer created using createoffer() will initiate ice restart once sent to the remote peer over your signaling mechanism.
...however, because you have
called restartice(), your
call to createoffer() which occurs in the handler for negotiationneeded will trigger an ice restart rather than just a regular renegotiation.
RTCPeerConnection.signalingState - Web APIs
"have-local-offer" the local peer has
called rtcpeerconnection.setlocaldescription(), passing in sdp representing an offer (usually created by
calling rtcpeerconnection.createoffer()), and the offer has been applied successfully.
... "have-remote-offer" the remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by
calling rtcpeerconnection.setremotedescription().
... "have-local-pranswer" the offer sent by the remote peer has been applied and an answer has been created (usually by
calling rtcpeerconnection.createanswer()) and applied by
calling rtcpeerconnection.setlocaldescription().
... "have-remote-pranswer" a provisional answer has been received and successfully applied in response to an offer previously sent and established by
calling setlocaldescription().
RTCRtpTransceiver.setCodecPreferences() - Web APIs
the specified set of codecs and configurations will be used for all future connections including this transceiver until this method is
called again.
... when preparing to open an rtcpeerconnection, you can change the codec parameters from the user agent's default configuration by
calling setcodecparameters() before
calling either rtcpeerconnection.createoffer() or createanswer().
...if any unsupported codecs are listed, the browser will throw an invalidaccesserror exception when you
call this method.
... to determine which codecs are supported by the transceiver,
call the sender's getcapabilities() and the receiver's getcapabilities() methods and get the codecs list from the results of each.
Request() - Web APIs
note the following behavioural updates to retain security while making the constructor less likely to throw exceptions: if this object exists on another origin to the constructor
call, the request.referrer is stripped out.
... 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.
...}); note that you could also pass the init object into the fetch
call to get the same effect, e.g.: fetch(myrequest,myinit).then(function(response) { ...
... var myinit = { method: 'get', headers: { 'content-type': 'image/jpeg' }, mode: 'cors', cache: 'default' }; var myrequest = new request('flowers.jpg', myinit); you may also pass a request object to the request() constructor to create a copy of the request (this is similar to
calling the clone() method.) var copy = new request(myrequest); note: this last usage is probably only useful in serviceworkers.
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.
... resizeobserverentry.contentrect read only a domrectreadonly object containing the new size of the observed element when the
callback is run.
SourceBuffer.abort() - Web APIs
}); sourcebuffer.appendbuffer(buf); let's say that after the
call to appendbuffer but before the updateend event fires (i.e.
... 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.
... you can see something similar in action in nick desaulnier's bufferwhenneeded demo — in line 48, an event listener is added to the playing video so a function
called seek() is run when the seeking event fires.
... 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.
Using the Storage Access API - Web APIs
first of all, if the <iframe> is sandboxed, the embedding website needs to add the allow-storage-access-by-user-activation sandbox token to allow storage access requests to be successful, along with allow-scripts and allow-same-origin to allow it to
call the api, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ...
...since it does not know whether it currently has access to storage, it should first
call document.hasstorageaccess().
... if that
call returns false, we can then
call document.requeststorageaccess(), returning the result so that then we can chain it onto the previous promise
call.
...}); note that access requests are automati
cally denied unless the embedded content is currently processing a user gesture such as a tap or click — so this code needs to be run inside some kind of user gesture-based event handler, for example: btn.addeventlistener('click', () => { // run code here }); ...
Using Touch Events - Web APIs
the contact point is typi
cally referred to as a touch point or just a touch.
... browsers typi
cally dispatch emulated mouse and click events when there is only a single active touch point.
... // touchstart handler function process_touchstart(ev) { // use the event's data to
call out to the appropriate gesture handlers switch (ev.touches.length) { case 1: handle_one_touch(ev); break; case 2: handle_two_touches(ev); break; case 3: handle_three_touches(ev); break; default: gesture_not_supported(ev); break; } } access the attributes of a touch point.
... // touchmove handler function process_touchmove(ev) { // set
call preventdefault() ev.preventdefault(); } best practices here are some best practices to consider when using touch events: minimize the amount of work that is done in the touch handlers.
URL.createObjectURL() - Web APIs
to release an object url,
call revokeobjecturl().
... 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.
... each of these must be released by
calling url.revokeobjecturl() when you no longer need them.
... browsers will release object urls automati
cally when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.
Visual Viewport API - Web APIs
it shows a function
called viewporthandler().
... when
called it queries the offsetleft and height properties for values it uses in a css translate() method.
... you invoke this function by passing it to both event
calls.
... one thing that may not be clear in this example is the use of the pendingupdate flag and the
call to requestanimationframe().
WebGLRenderingContext.getUniformLocation() - Web APIs
with this value in hand, you can
call other webgl methods to access the value of the uniform variable.
... errors the following errors may occur; to check for errors after getuniformlocation() returns,
call geterror().
... after setting the current shading program to shaderprogram, this code fetches the three uniforms "uscalingfactor", "uglobalcolor", and "urotationvector",
calling getuniformlocation() once for each uniform.
... having done this, the next time the shading functions are
called, their own variables named uscalingfactor, uglobalcolor, and urotationvector will all have the values provided by the javascript code.
Animating textures in WebGL - Web APIs
and finally, we set the src attribute to start and
call play to start loading and playing the video.
...it's nearly identical to the image onload function in the previous example — except when we
call teximage2d(), instead of passing an image object, we pass in the <video> element.
... then in main() in place of the
call to loadtexture() in the previous example, we
call inittexture() followed by setupvideo() .
... in the definition of render() if copyvideo is true, then we
call updatetexture() each time just before we
call the drawscene() function.
WebSocket - Web APIs
websocket.onclose an event listener to be
called when the connection is closed.
... websocket.onerror an event listener to be
called when an error occurs.
... websocket.onmessage an event listener to be
called when a message is received from the server.
... websocket.onopen an event listener to be
called when the connection is opened.
Writing WebSocket client applications - Web APIs
creating a websocket object in order to communicate using the websocket protocol, you need to create a websocket object; this will automati
cally attempt to open the connection to the server.
...to do this, simply
call the websocket object's send() method for each message you want to send: examplesocket.send("here's some text that the server is urgently awaiting!"); you can send data as a string, blob, or arraybuffer.
... as establishing a connection is asynchronous and prone to failure there is no guarantee that
calling the send() method immediately after creating a websocket object will be successful.
... closing the connection when you've finished using the websocket connection,
call the websocket method close(): examplesocket.close(); it may be helpful to examine the socket's bufferedamount attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network.
WebXR Device API - Web APIs
to get an xrframe,
call the session's requestanimationframe() method, providing a
callback which will be
called with the xrframe once available.
...the x and z components of the origin are typi
cally presumed to be located at or near the center of the room or surface.
...if the context was not initially created with the xrcompatible property set to true, you must
call makexrcompatible() prior to attempting to use the webgl context for webxr rendering.
... rendering and the webxr frame animation
callback starting with how you schedule frames to be rendered, this guide then continues to cover how to determine the placement of objects in the view and how to then render them into the webgl buffer used for each of the two eyes' views of the scene.
Web Audio API - Web APIs
they typi
cally start with one or more sources.
...these could be either computed mathemati
cally (such as oscillatornode), or they can be recordings from sound/video files (like audiobuffersourcenode and mediaelementaudiosourcenode) and audio streams (mediastreamaudiosourcenode).
... there's also a basic concepts behind web audio api article, to help you understand the way digital audio works, specifi
cally in the realm of the api.
...if multiple audio tracks are present on the stream, the track whose id comes first lexicographi
cally (alphabeti
cally) is used.
Using the Web Storage API - Web APIs
the keys and the values are always strings (note that, as with objects, integer keys will be automati
cally converted to strings).
... so, for example, initially
calling localstorage on a document will return a storage object;
calling sessionstorage on a document will return a different storage object.
...we can use localstorage awesomeness } else { // too bad, no localstorage for us } you can test for sessionstorage instead by
calling storageavailable('sessionstorage').
... example to illustrate some typical web storage usage, we have created an example, imaginatively
called web storage demo.
Functions and classes available to Web Workers - Web APIs
38 (38) no support no support no support cache cache api provides the ability to programmati
cally control cache storage associated with current origin.
...the specifics of how it works vary from browser to browser, but there is a de facto set of features that are typi
cally provided.
...it allows access to a cryptographi
cally strong random number generator and to cryptographic primitives.
... workers can also create a new url using the url() constructor and
call any normal method on the returned object.
Window.openDialog() - Web APIs
the
call to opendialog() returns immediately.
... if you want the
call to block until the user has closed the dialog, supply modal as a windowfeatures parameter.
... to be able to pass values back to the
caller, you have to supply some object via the extra parameters.
... var retvals = { address: null, delivery: null }; opendialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retvals); if you set the properties of the retvals object in the dialog code as described below, you can now access them via the retvals array after the opendialog()
call returns.
Window.pageYOffset - Web APIs
syntax yoffset = window.pageyoffset; value a floating-point number specifying the number of pixels the document is scrolled verti
cally within its containing window.
...a value of 0.0 indicates that the window is not scrolled verti
cally, and that the top of the document is located at the top edge of the window's content area.
...it then gets a reference to the element we want to scroll into view
calling getelementbyid() on the frame's htmliframeelement.contentdocument.
... this will automati
cally set the scrolling position to the maximum possible value if the attempted scroll would exceed the maximum.
WindowEventHandlers.onpopstate - Web APIs
if the activated history entry was created by a
call to history.pushstate(), or was affected by a
call to history.replacestate(), the popstate event's state property contains a copy of the history entry's state object.
... note:
calling history.pushstate() or history.replacestate() won't trigger a popstate event.
... the popstate event is only triggered by performing a browser action, such as clicking on the back button (or
calling history.back() in javascript), when navigating between two history entries for the same document.
...te: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate event is still fired, when we activate that entry after the second
call to history.back().
WindowOrWorkerGlobalScope.fetch() - Web APIs
to automati
cally send cookies for the current domain, this option must be provided.
... redirect the redirect mode to use: follow (automati
cally follow redirects), error (abort with an error if a redirect occurs), or manual (handle redirects manually).
... exceptions aborterror the request was aborted due to a
call to the abortcontroller method abort() method.
... 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.
Worker - Web APIs
creating a worker is done by
calling the worker("path/to/worker/script") constructor.
... event handlers abstractworker.onerror an eventlistener
called whenever an errorevent of type error bubbles through to the worker.
... worker.onmessage an eventlistener
called whenever a messageevent of type message bubbles through the worker — i.e.
... worker.onmessageerror is an eventhandler representing the code to be
called when the messageerror event is raised.
WritableStream.getWriter() - Web APIs
it then
calls a function
called sendmessage(), passing the newly created stream and a string.
... inside this function it
calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter.
... a foreach()
call is used to write each chunk of the string to the stream.
...etwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); //
call ready again to ensure that all chunks are written // before closing the writer.
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
it then
calls a function
called sendmessage(), passing the newly created stream and a string.
... inside this function it
calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter.
... a foreach()
call is used to write each chunk of the string to the stream.
...etwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); //
call ready again to ensure that all chunks are written // before closing the writer.
WritableStreamDefaultWriter.close() - Web APIs
it then
calls a function
called sendmessage(), passing the newly created stream and a string.
... inside this function it
calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter.
... a foreach()
call is used to write each chunk of the string to the stream.
...etwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); //
call ready again to ensure that all chunks are written // before closing the writer.
WritableStreamDefaultWriter.write() - Web APIs
it then
calls a function
called sendmessage(), passing the newly created stream and a string.
... inside this function it
calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter.
... a foreach()
call is used to write each chunk of the string to the stream.
...etwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); //
call ready again to ensure that all chunks are written // before closing the writer.
WritableStreamDefaultWriter - Web APIs
it then
calls a function
called sendmessage(), passing the newly created stream and a string.
... inside this function it
calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter.
... a foreach()
call is used to write each chunk of the string to the stream.
...const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); //
call ready again to ensure that all chunks are written // before closing the writer.
XMLHttpRequest.onreadystatechange - Web APIs
an eventhandler that is
called whenever the readystate attribute changes.
... the
callback is
called from the user interface thread.
... the xmlhttprequest.onreadystatechange property contains the event handler to be
called when the readystatechange event is fired, that is every time the readystate property of the xmlhttprequest changes.
... syntax xmlhttprequest.onreadystatechange =
callback; values
callback is the function to be executed when the readystate changes.
XMLHttpRequest.setRequestHeader() - Web APIs
when using setrequestheader(), you must
call it after
calling open(), but before
calling send().
... if this method is
called several times with the same header, the values are merged into one single request header.
... each time you
call setrequestheader() after the first time you
call it, the specified text is appended to the end of the existing header's content.
... if no accept header has been set using this, an accept header with the type "*/*" is sent with the request when send() is
called.
XRInputSource.targetRaySpace - Web APIs
the read-only xrinputsource property targetrayspace returns an xrspace (typi
cally an xrreferencespace) representing the position and orientation of the target ray in the virtual space.
... syntax let targetrayspace = xrinputsource.targetrayspace; value an xrspace object—typi
cally an xrreferencespace or xrboundedreferencespace—which represents the position and orientation of the input controller's target ray in virtual space.
... example this fragment of code shows part of a function to be
called once every frame.
...for tracked pointers, a function myrendertargetrayasbeam() is
called to render a beam from the input controller's virtual position outward in the direction it's pointing.
XRPermissionDescriptor - Web APIs
if the permissions api is found to be available (by checking to see if navigator.permissions is defined), its query() method is
called, specifying the permission descriptor we've established, xrpermissiondesc.
...if permission has been granted, we
call a function setupxr() that handles preparing the webxr environment for use.
... if permission is conditional based on prompting, we
call a function promptandsetupxr() that would handle asking for permission before enabling and starting up the environment.
... if the permissions api isn't available at all, this example simply assumes that webxr will report an appropriate error if permission isn't available, and tries to start up the webxr session using the same setupxr() function
called by the granted case.
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.
...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().
... when the returned promise resolves, we proceed by
calling xrwebgllayer's getnativeframebufferscalefactor() static function to get the scale factor needed to reach the native resolution, and we then pass that into the webgllayer() constructor as the value of the framebufferscalefactor property in its layerinit dictionary, which is an xrwebgllayerinit object.
... 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.
ARIA: alert role - Accessibility
the alert role can be used to tell the user an element has been dynami
cally updated.
... description one of the five live region roles, the alert role is used to provide the user with important, and usually time-sensitive, information, and often to tell the user an element has been dynami
cally updated.
...for example, if a page loads with multiple visible alerts scattered throughout, none would be read because they are not dynami
cally triggered.
...when the display value is changed with css or javascript, it would automati
cally trigger the screen reader to read out the content.
ARIA: Complementary role - Accessibility
these sections are frequently presented as sidebars or
call-out boxes.
... using the <aside> element will automati
cally communicate a section has a role of complementary.
... examples <div role="complementary"> <h2>trending articles</h2> <ul> <li><a href="#">18 tweets that will make you feel all the feels</a></li> <li><a href="#">stop searching for the perfect lunch containers because i've found them</a></li> <li><a href="#">the time has come to finally decide what we should be
calling these foods</a></li> <li><a href="#">17 really good posts we saw on tumblr this week</a></li> <li><a href="#">10 parent hacks we know work because we tried them</a></li> </ul> </div> accessibility concerns landmark roles are intended to be used sparingly, to identify larger overall sections of the document.
... best practices prefer html using the <aside> element will automati
cally communicate a section has a role of complementary.
ARIA: Suggestion role - Accessibility
the suggestion landmark role semanti
cally denotes a single proposed change to an editable document.
...this is the job of role="suggestion", which should be set on an element wrapping both of them like so: <p>freida’s pet is a <span role="suggestion"> <span role="deletion">black cat
called luna</span> <span role="insertion">purple tyrannosaurus rex
called tiny</span> </span>.
... </p> we could even provide an information box saying who made the suggestion and when, and associate it with the suggestion via aria-details: <p>freida’s pet is a <span role="suggestion" aria-details="comment-source"> <span role="deletion">black cat
called luna</span> <span role="insertion">purple tyrannosaurus rex
called tiny</span> </span>.
... best practices prefer html using the <ins> and <del> element will automati
cally communicate a section has a role of insertion or deletion.
ARIA: button role - Accessibility
toggle buttons a toggle button typi
cally has two states: pressed and not pressed.
...if the design were to
call for the button label to change from "mute" to "unmute," a toggle button would not be appropriate, so the the aria-pressed attribute would be omitted.
...if the button closes a dialog, focus should returns to the button that opened the dialog unless the function performed in the dialog context logi
cally leads to a different element.
... if the button alters the current context, then focus typi
cally remains on the button, such as muting and unmuting an audio file.
Web accessibility for seizures and physical reactions - Accessibility
in the case of photosensitive epilepsy, seizures are triggered specifi
cally by flashing lights, but other types of reflex epilepsies may be triggered by the act of reading, or by noises.
...only a few types of epilepsies are photosensitive though, and the vast majority of epilepsies are not." in addition to seizures brought about by photosensitivity, listening to certain pieces of music can also trigger what are
called musicogenic seizures, although these types of seizures seem to be much more rare.
...in the article, "understanding wcag 2.0 three flashes or below threshold" notes generally that: “individuals who have photosensitive seizure disorders can have a seizure triggered by content that flashes at certain frequencies for more than a few flashes” and goes on to note, very specifi
cally that: “people are even more sensitive to red flashing than to other colors, so a special test is provided for saturated red flashing”.
...interestingly, the specification refrains from actually defining the three levels in terms of a measurment of lux, because devices with a light sensor usually adjust the brightess of the screen automati
cally.
Perceivable - Accessibility
success criteria how to conform to the criteria practical resource 1.3.1 info and relationships (a) any content structure—or visual relationship made between content—can also be determined programmati
cally, or be inferred from text description.
...content images should have text available that clearly describes the image's contents, which can be programmati
cally associated with it (e.g., alt text), or otherwise is easy to associate (e.g., describes it and is sat right next to it).
... understanding orientation 1.3.5 identify input purpose (aa) added in 2.1 follow the list of 53 input fields to programmati
cally identify the purpose of a field.
... understanding identify input purpose 1.3.6 identify purpose (aaa) added in 2.1 in content implemented using markup languages, the purpose of user interface components, icons, and regions can be programmati
cally determined.
-webkit-mask-repeat-y - CSS: Cascading Style Sheets
the -webkit-mask-repeat-y property sets whether and how a mask image is repeated (tiled) verti
cally.
... /* keyword values */ -webkit-mask-repeat-y: repeat; -webkit-mask-repeat-y: no-repeat; -webkit-mask-repeat-y: space; -webkit-mask-repeat-y: round; /* multiple values */ -webkit-mask-repeat-y: repeat, no-repeat, space; /* global values */ -webkit-mask-repeat-y: inherit; -webkit-mask-repeat-y: initial; -webkit-mask-repeat-y: unset; syntax values repeat the mask image is repeated verti
cally.
... no-repeat the mask image is not repeated verti
cally; only one copy of the mask image is drawn in vertical direction.
... repeat the mask image is repeated verti
cally.
Block and inline layout in normal flow - CSS: Cascading Style Sheets
for elements with a block formatting context, the spec says: “in a block formatting context, boxes are laid out one after the other, verti
cally, beginning at the top of a containing block.
...the boxes may be aligned verti
cally in different ways: their bottoms or tops may be aligned, or the baselines of text within them may be aligned.
... the rectangular area that contains the boxes that form a line is
called a line box.” - 9.4.2 note that the css 2.1 specification describes documents as being in a horizontal, top to bottom writing mode.
... elements participating in a block formatting context block elements in a horizontal writing mode such as english, layout verti
cally, one below the other.
Basic Concepts of grid layout - CSS: Cascading Style Sheets
.wrapper { display: grid; grid-template-columns: repeat(5, 1fr 2fr); } the implicit and explicit grid when creating our example grid we specifi
cally defined our column tracks with the grid-template-columns property, but the grid also created rows on its own.
...repeat(3, 1fr); grid-auto-rows: 200px; } * {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; } track sizing and minmax when setting up an explicit grid or defining the sizing for automati
cally created rows or columns we may want to give tracks a minimum size, but also ensure they expand to fit any content that is added.
...this means automati
cally created rows will be a minimum of 100 pixels tall, and a maximum of auto.
... subgrid in the working draft of the level 2 grid specification there is a feature
called subgrid, which would let us create nested grids that use the track definition of the parent grid.
Using CSS gradients - CSS: Cascading Style Sheets
because gradients are dynami
cally generated, they can negate the need for the raster image files that traditionally were used to achieve similar effects.
...these are
called color stops.
...if you leave a location unspecified, the position of that particular color stop will be automati
cally calculated for you, with the first color stop being at 0% and the last color stop being at 100%, and any other color stops being half way between their adjacent color stops.
...e conic gradient with keyterms, percentage, or absolute lengths, with the keyword "at" <div class="conic-gradient"></div> div { width: 120px; height: 120px; } .conic-gradient { background: conic-gradient(from 45deg, red, orange, yellow, green, blue, purple); } using repeating gradients the linear-gradient(), radial-gradient(), and conic-gradient() functions don't support automati
cally repeated color stops.
Inline formatting context - CSS: Cascading Style Sheets
in a vertical writing mode they would be laid out verti
cally starting at the top.
...the boxes in the horizontal writing mode run horizontally, and the vertical writing mode boxes run verti
cally.
... boxes forming a line are contained by a rectangular area
called a line box.
... alignment in the block direction inline boxes may be aligned in the block direction in different ways, using the vertical-align property, which will align on the block axis in vertical writing modes (therefore not verti
cally at all!).
Syntax - CSS: Cascading Style Sheets
a property and value pair is
called a declaration, and any css engine calculates which declarations apply to every single element of a page in order to appropriately lay it out, and to style it.
... such blocks are naturally
called declaration blocks and declarations inside them are separated by a semi-colon, ';' (u+003b semicolon).
...a selector group and an associated declarations block, together, are
called a ruleset, or often simply a rule.
... as an element of the page may be matched by several selectors, and therefore by several rules potentially containing a given property several times, with different values, the css standard defines which one has precedence over the other and must be applied: this is
called the cascade algorithm.
Audio and Video Delivery - Developer guides
adaptive streaming media means that the bandwidth and typi
cally quality of the stream can change in real-time in reaction to the user's available bandwidth.
... other tips for audio/video stopping the download of media while stopping the playback of media is as easy as
calling the element's pause() method, the browser keeps downloading the media until the media element is disposed of through garbage collection.
...you must
call load() after removing the attribute, because just removing the src attribute does not invoke the load algorithm.
... if the <video> element also has <source> element descendants, those should also be removed before
calling load().
Audio and video manipulation - Developer guides
var processor = { timer
callback: function() { if (this.video.paused || this.video.ended) { return; } this.computeframe(); var self = this; settimeout(function () { self.timer
callback(); }, 16); // roughly 60 frames per second }, doload: function() { this.video = document.getelementbyid("my-video"); this.c1 = document.getelementbyid("my-canvas"); this.ctx1 = this.c1.getcon...
...text("2d"); var self = this; this.video.addeventlistener("play", function() { self.width = self.video.width; self.height = self.video.height; self.timer
callback(); }, false); }, computeframe: function() { this.ctx1.drawimage(this.video, 0, 0, this.width, this.height); var frame = this.ctx1.getimagedata(0, 0, this.width, this.height); var l = frame.data.length / 4; for (var i = 0; i < l; i++) { var grey = (frame.data[i * 4 + 0] + frame.data[i * 4 + 1] + frame.data[i * 4 + 2]) / 3; frame.data[i * 4 + 0] = grey; frame.data[i * 4 + 1] = grey; frame.data[i * 4 + 2] = grey; } this.ctx1.putimagedata(frame, 0, 0); return; } }; once the page has loaded you can
call processor.doload() result this is a pr...
... playback rate we can also adjust the rate that audio and video plays at using an attribute of the <audio> and <video> element
called playbackrate.
... audio manipulation playbackrate aside, to manipulate audio you'll typi
cally use the web audio api.
Mouse gesture events - Developer guides
if you handle a gesture event and wish to prevent the default action from taking place as well, be sure to
call the event's preventdefault() method.
...this is typi
cally used to zoom in and out on content (this is the default behavior in firefox, for example).
... mozmagnifygestureupdate the mozmagnifygestureupdate event is sent periodi
cally while processing a magnify gesture, to provide updated status information.
...mozrotategestureupdate the mozrotategestureupdate event is sent periodi
cally while processing a rotate gesture, to provide updated status information.
<details>: The Details disclosure element - HTML: Hypertext Markup Language
a disclosure widget is typi
cally presented onscreen using a small triangle which rotates (or twists) to indicate open/closed status, with a label next to the triangle.
... note: the common use of a triangle which rotates or twists around to represent opening or closing the widget is why these are sometimes
called "twisties." a <details> widget can be in one of two states.
...when the user clicks on the widget or focuses it then presses the space bar, it "twists" open, revealing its contents: from there, you can use css to style the disclosure widget, and you can programmati
cally open and close the widget by setting/removing its open attribute.
... fully standards-compliant implementations automati
cally apply the css display: list-item to the <summary> element.
<form> - HTML: Hypertext Markup Language
(in previous versions of html, character encodings could also be delimited by commas.) autocapitalize a nonstandard attribute used by ios safari that controls how textual form elements should be automati
cally capitalized.
... autocomplete indicates whether input elements can by default have their values automati
cally completed by the browser.
...possible values: off: the browser may not automati
cally complete entries.
... (browsers tend to ignore this for suspected login forms; see the autocomplete attribute and login fields.) on: the browser may automati
cally complete entries.
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
the browsing context that embeds the others is
called the parent browsing context.
...while theoreti
cally you can use as many <iframe>s as you like, check for performance problems.
... allowfullscreen set to true if the <iframe> can activate fullscreen mode by
calling the requestfullscreen() method.
...also note that programati
cally removing an <iframe>'s src attribute (e.g.
<input type="image"> - HTML: Hypertext Markup Language
important: while the alt attribute is techni
cally optional, you should always include one to maximize the usability of your content.
...this is typi
cally a new tab in the same window as the current document, but may differ depending on the configuration of the user agent.
...also, if you specify only one dimension, the other is automati
cally adjusted so that the image maintains its original aspect ratio.
... using the x and y data points when you submit a form using a button created with <input type="image">, two extra data points are submitted to the server automati
cally by the browser — x and y.
<input type="radio"> - HTML: Hypertext Markup Language
radio buttons are typi
cally rendered as small circles, which are filled or highlighted when selected.
... they are
called radio buttons because they look and operate in a similar manner to the push buttons on old-fashioned radios, such as the one shown below.
...once a radio group is established, selecting any radio button in that group automati
cally deselects any currently-selected radio button in the same group.
...this is because only one radio button in a group can ever be selected at once, and the user agent automati
cally deselects others each time a new one is marked as checked.
<input type="search"> - HTML: Hypertext Markup Language
it is not as semanti
cally useful as other ways to explain your form, and can cause unexpected technical issues with your content.
... using search inputs <input> elements of type search are very similar to those of type text, except that they are specifi
cally intended for handling search terms.
... they are basi
cally equivalent in behavior, but user agents may choose to style them differently by default (and, of course, sites may use stylesheets to apply custom styles to them).
...the following screenshot comes from chrome: in addition, modern browsers also tend to automati
cally store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain.
<input type="submit"> - HTML: Hypertext Markup Language
when the click event occurs (typi
cally because the user clicked the button), the user agent attempts to submit the form to the server.
...this is typi
cally a new tab in the same window as the current document, but may differ depending on the configuration of the user agent.
...this is especially true since the modifiers are typi
cally non-standard to avoid conflicts.
...there's a reason this kind of control is sometimes
called a "simple button." specifications specification status comments html living standardthe definition of '<input type="submit">' in that specification.
<input type="tel"> - HTML: Hypertext Markup Language
unlike <input type="email"> and <input type="url"> , the input value is not automati
cally validated to a particular format before the form can be submitted, because formats for telephone numbers vary so much around the world.
...it is not as semanti
cally useful as other ways to explain your form, and can cause unexpected technical issues with your content.
...label> <input id="telno" name="telno" type="tel" list="defaulttels"> <datalist id="defaulttels"> <option value="111-1111-1111"> <option value="122-2222-2222"> <option value="333-3333-3333"> <option value="344-4444-4444"> </datalist> with the <datalist> element and its <option>s in place, the browser will offer the specified values as potential values for the email address; this is typi
cally presented as a popup or drop-down menu containing the suggestions.
... while the specific user experience may vary from one browser to another, typi
cally clicking in the edit box presents a drop-down of the suggested email addresses.
itemprop - HTML: Hypertext Markup Language
each name-value pair is
called a property, and a group of one or more properties forms an item.
... three properties with values that are strings <div itemscope> <p>my name is <span itemprop="name">neil</span>.</p> <p>my band is
called <span itemprop="band">four parts water</span>.</p> <p>i am <span itemprop="nationality">british</span>.</p> </div> one property, "image", whose value is a url <div itemscope> <img itemprop="image" src="google-logo.png" alt="google"> </div> when a string value can't be easily read and understood by a person (e.g., a long string of numbers and letters), it can be displayed using the...
...items that are not part of others are
called top-level microdata items.
...an item is
called a typed item if it is a url.
Connection management in HTTP/1.x - HTTP
alternatively this may be
called a keep-alive connection.
...theoreti
cally, performance could also be improved if two http requests were to be packed into the same tcp message.
...most http/2 implementations use a technique
called connection coalescing to revert eventual domain sharding.
...this technique is
called domain sharding.
Index - HTTP
it allows web developers to have more control over the data stored lo
cally by a browser for their origins.
...when this policy is enabled,
calls to getcurrentposition() and watchposition() will cause those functions'
callbacks to be invoked with a positionerror code of permission_denied.
...(you could informally
call it accept-transfer-encoding, which would be more intuitive).
... 107 trailer http, reference, header the trailer response header allows the sender to include additional fields at the end of chunked messages in order to supply metadata that might be dynami
cally generated while the message body is sent, such as a message integrity check, digital signature, or post-processing status.
Strict-Transport-Security - HTTP
the http strict transport security header informs the browser that it should never load a site using http and should automati
cally convert all attempts to access the site using http to https requests instead.
... strict transport security resolves this problem; as long as you've accessed your bank's web site once using https, and the bank's web site uses strict transport security, your browser will know to automati
cally use only https, which prevents hackers from performing this sort of man-in-the-middle attack.
... how the browser handles it the first time your site is accessed using https and it returns the strict-transport-security header, the browser records this information, so that future attempts to load the site using http will automati
cally use https instead.
... when the expiration time specified by the strict-transport-security header elapses, the next attempt to load the site via http will proceed as normal instead of automati
cally using https.
About JavaScript - JavaScript
objects are created programmati
cally in javascript, by attaching methods and properties to otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like c++ and java.
... the chakra engine used in internet explorer (although the language it implements is formally
called "jscript" in order to avoid trademark issues).
...web browsers typi
cally use the public api to create host objects responsible for reflecting the dom into javascript.
...a javascript web server would expose host objects representing a http request and response objects, which could then be manipulated by a javascript program to dynami
cally generate web pages.
Control flow and error handling - JavaScript
« previousnext » javascript supports a compact set of statements, specifi
cally control flow statements, that you can use to incorporate a great deal of interactivity in your application.
...while it is common to throw numbers or strings as errors, it is frequently more effective to use one of the exception types specifi
cally created for this purpose: ecmascript exceptions domexception and domerror throw statement use the throw statement to throw an exception.
...if any statement within the try block (or in a function
called from within the try block) throws an exception, control immediately shifts to the catch block.
...the example
calls a function that retrieves a month name from an array based on the value passed to the function.
Meta programming - JavaScript
invariants semantics that remain unchanged when implementing custom operations are
called invariants.
... handler.apply() proxy(..args) function.prototype.apply() and function.prototype.
call() reflect.apply() there are no invariants for the handler.apply method.
... with reflect.has() for example, you get the in operator as a function: reflect.has(object, 'assign') // true a better apply function in es5, you typi
cally use the function.prototype.apply() method to
call a function with a given this value and arguments provided as an array (or an array-like object).
... function.prototype.apply.
call(math.floor, undefined, [1.75]) with reflect.apply this becomes less verbose and easier to understand: reflect.apply(math.floor, undefined, [1.75]) // 1 reflect.apply(string.fromcharcode, undefined, [104, 101, 108, 108, 111]) // "hello" reflect.apply(regexp.prototype.exec, /ab/, ['confabulation']).index // 4 reflect.apply(''.charat, 'ponies', [3]) // "i" checking if property definition has been successful with object.defineproperty, which returns an object if successful, or throws a typeerror otherwise, you would use a try...catch block to catch any error that occurred while defining a property.
Numbers and dates - JavaScript
calling date without the new keyword returns a string representing the current date and time.
...there is a getday method that returns the day of the week, but no corresponding setday method, because the day of the week is set automati
cally.
...' p.m.' : ' a.m.'; return temp; } the jsclock function first creates a new date object
called time; since no arguments are given, time is created with the current date and time.
... then
calls to the gethours, getminutes, and getseconds methods assign the value of the current hour, minute, and second to hour, minute, and second.
Array.prototype.unshift() - JavaScript
return value the new length property of the object upon which the method was
called.
...this method can be
called or applied to objects resembling arrays.
...hence,
calling unshift with n arguments once, or
calling it n times with 1 argument (with a loop, for example), don't yield the same results.
... 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-262)the definition of 'array.prototype.unshift' in that specif...
BigInt64Array() constructor - JavaScript
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
BigUint64Array() constructor - JavaScript
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
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.
... because parse() is a static method of date, it is
called as date.parse() rather than as a method of a date instance.
... examples using date.parse() the following
calls all return 1546300800000.
... the first according to es5 will imply utc time, and the others are specifying utc timezone via the iso date specification (z and +00:00) date.parse("2019-01-01") date.parse("2019-01-01t00:00:00.000z") date.parse("2019-01-01t00:00:00.000+00:00") the following
call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system.
Error() constructor - JavaScript
defaults to the name of the file containing the code that
called the error() constructor.
... 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 x = error('i was created using a function
call!') // ...has the same functionality as this.
Float32Array() constructor - JavaScript
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
Float64Array() constructor - JavaScript
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
Object.create() - JavaScript
custom and null objects a new object created from a completely custom object (especially one created from the null object, which is basi
cally a custom object with no members) can behave in unexpected ways.
... note that such a different order may arise stati
cally via disparate fixed codings such as here, but also dynami
cally via whatever the order any such property-adding code-branches actually get executed at runtime as depends on inputs and/or random-variables.
... // shape - superclass function shape() { this.x = 0; this.y = 0; } // superclass method shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info('shape moved.'); }; // rectangle - subclass function rectangle() { shape.
call(this); //
call super constructor.
... function myclass() { superclass.
call(this); othersuperclass.
call(this); } // inherit one class myclass.prototype = object.create(superclass.prototype); // mixin another object.assign(myclass.prototype, othersuperclass.prototype); // re-assign constructor myclass.prototype.constructor = myclass; myclass.prototype.mymethod = function() { // do something }; object.assign() copies properties from the othersuperclass prototype to...
Promise.prototype.finally() - JavaScript
when the promise is settled, i.e either fulfilled or rejected, the specified
callback function is executed.
... syntax p.finally(onfinally); p.finally(function() { // settled (fulfilled or rejected) }); parameters onfinally a function
called when the promise is settled.
... the finally() method is very similar to
calling .then(onfinally, onfinally) however there are a couple of differences: when creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it a finally
callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected.
... note: a throw (or returning a rejected promise) in the finally
callback will reject the new promise with the rejection reason specified when
calling throw.
Promise.resolve() - JavaScript
examples using the static promise.resolve method promise.resolve('success').then(function(value) { console.log(value); // "success" }, function(value) { // not
called }); resolving an array var p = promise.resolve([1,2,3]); p.then(function(v) { console.log(v[0]); // 1 }); resolving another promise var original = promise.resolve(33); var cast = promise.resolve(original); cast.then(function(value) { console.log('value: ' + value); }); console.log('original === cast ?
...true // value: 33 the inverted order of the logs is due to the fact that the then handlers are
called asynchronously.
... resolving thenables and throwing errors // resolving a thenable object var p1 = promise.resolve({ then: function(onfulfill, onreject) { onfulfill('fulfilled!'); } }); console.log(p1 instanceof promise) // true, object casted to a promise p1.then(function(v) { console.log(v); // "fulfilled!" }, function(e) { // not
called }); // thenable throws before
callback // promise rejects var thenable = { then: function(resolve) { throw new typeerror('throwing'); resolve('resolving'); }}; var p2 = promise.resolve(thenable); p2.then(function(v) { // not
called }, function(e) { console.error(e); // typeerror: throwing }); // thenable throws after
callback // promise resolves var thenable = { then: function(resolve) { resolve('resolving'); throw new ty...
...peerror('throwing'); }}; var p3 = promise.resolve(thenable); p3.then(function(v) { console.log(v); // "resolving" }, function(e) { // not
called }); specifications specification ecmascript (ecma-262)the definition of 'promise.resolve' in that specification.
Reflect.construct() - JavaScript
it is equivalent to
calling new target(...args).
... syntax reflect.construct(target, argumentslist[, newtarget]) parameters target the target function to
call.
... argumentslist an array-like object specifying the arguments with which target should be
called.
... function oneclass() { this.name = 'one' } function otherclass() { this.name = 'other' } //
calling this: let obj1 = reflect.construct(oneclass, args, otherclass) // ...has the same result as this: let obj2 = object.create(otherclass.prototype) oneclass.apply(obj2, args) console.log(obj1.name) // 'one' console.log(obj2.name) // 'one' console.log(obj1 instanceof oneclass) // false console.log(obj2 instanceof oneclass) // false console.log(obj1 instanceof otherclass) // true console.l...
String.prototype.toUpperCase() - JavaScript
the touppercase() method returns the
calling string value converted to uppercase (the value will be converted to a string if it isn't one).
... syntax str.touppercase() return value a new string representing the
calling string converted to upper case.
... exceptions typeerror when
called on null or undefined, for example, string.prototype.touppercase.
call(undefined).
... examples basic usage console.log('alphabet'.touppercase()); // 'alphabet' conversion of non-string this values to strings this method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = string.prototype.touppercase.
call({ tostring: function tostring() { return 'abcdef'; } }); const b = string.prototype.touppercase.
call(true); // prints out 'abcdef true'.
TypedArray.prototype.sort() - JavaScript
the sort() method sorts the elements of a typed array numeri
cally in place and returns the typed array.
... this method has the same algorithm as array.prototype.sort(), except that sorts the values numeri
cally instead of as strings.
... 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 numeri
cally.
... // regular arrays require a compare function to sort numeri
cally: numbers = [40, 1, 5, 200]; numbers.sort(); // [1, 200, 40, 5] numbers.sort((a, b) => a - b); // compare numbers // [ 1, 5, 40, 200 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.sort' in that specification.
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
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.
... object when
called with an object argument, a new typed array is created as if by the typedarray.from() method.
... buffer, byteoffset, length when
called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer.
WeakRef - JavaScript
description a weakref object contains a weak reference to an object, which is
called its target or referent.
...if an application or library depends on gc cleaning up a weakref or
calling a finalizer [cleanup
callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all.
...the result of
calling deref on one of them will match the result of
calling deref on another of them (in the same job), you won't get the target object from one of them but undefined from another.
... if the target of a weakref is also in a finalizationregistry, the weakref's target is cleared at the same time or before any cleanup
callback associated with the registry is
called; if your cleanup
callback
calls deref on a weakref for the object, it will receive undefined.
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 objects.
...n a string is still typeof string typeof (typeof 1) === 'string'; // typeof always returns a string typeof string(1) === 'string'; // string converts anything into a string, safer than tostring // booleans typeof true === 'boolean'; typeof false === 'boolean'; typeof boolean(1) === 'boolean'; // boolean() will convert values based on if they're truthy or falsy typeof !!(1) === 'boolean'; // two
calls of the !
...(logical not) operator are equivalent to boolean() // symbols typeof symbol() === 'symbol' 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.
...let idata = 99; typeof idata + ' wisen'; // 'number wisen' typeof (idata + ' wisen'); // 'string' regular expressions
callable regular expressions were a non-standard addition in some browsers.
for await...of - JavaScript
in such case for await...of throws when consuming rejected promise and doesn't
call finally blocks within that generator.
... function* generatorwithrejectedpromises() { try { yield 0; yield 1; yield promise.resolve(2); yield promise.reject(3); yield 4; throw 5; } finally { console.log('
called finally') } } (async function() { try { for await (let num of generatorwithrejectedpromises()) { console.log(num); } } catch (e) { console.log('catched', e) } })(); // 0 // 1 // 2 // catched 3 // compare with for-of loop: try { for (let numorpromise of generatorwithrejectedpromises()) { console.log(numorpromise); } } catch (e) { console.log('catched', e) } // 0 // 1 // promise { 2 } // promise { <rejected> 3 } // 4 // catched 5 //
called finally to make finally bloc...
...ks of a sync generator to be always
called use appropriate form of the loop, for await...of for the async generator and for...of for the sync one and await yielded promises explicitly inside the loop.
... (async function() { try { for (let numorpromise of generatorwithrejectedpromises()) { console.log(await numorpromise); } } catch (e) { console.log('catched', e) } })() // 0 // 1 // 2 // catched 3 //
called finally specifications specification ecmascript (ecma-262)the definition of 'ecmascript language: the for-in, for-of, and for-await-of statements' in that specification.
var - JavaScript
this is
called hoisting, and is discussed further below.
...this behavior is
called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.
... initialization of several variables var x = 0; function f() { var x = y = 1; // declares x lo
cally; declares y globally.
... console.log(x, y, z); // 3 4 5 } a(); // also
calls b.
Template literals (Template strings) - JavaScript
they were
called "template strings" in prior editions of the es2015 specification.
...if there is an expression preceding the template literal (tag here), this is
called a tagged template.
... in that case, the tag expression (usually a function) gets
called with the template literal, which you can then manipulate before outputting.
... let person = 'mike'; let age = 28; function mytag(strings, personexp, ageexp) { let str0 = strings[0]; // "that " let str1 = strings[1]; // " is a " // there is techni
cally a string after // the final expression (in our example), // but it is empty (""), so disregard.
Web Performance
by minimizing the number of dom nodes, making sure the best order and attributes are used for including content such as styles, scripts, media, and third-party scripts, you can drasti
cally improve the user experience.
... other documentation developer tools performance features this section provides information on how to use and understand the performance features in your developer tools, including waterfall,
call tree, and flame charts.
... the role of tls in performance tls—or https as we tend to
call it—is crucial in creating secure and safe user experiences.
...knowing how to read waterfall charts,
call trees, traces, flame charts , and allocations in your browser developer tools will help you understand waterfall and flame charts in other performance tools.
Same-origin policy - Web security
any
call to document.domain, including document.domain = document.domain, causes the port number to be overwritten with null.
...these interactions are typi
cally placed into three categories: cross-origin writes are typi
cally allowed.
... cross-origin embedding is typi
cally allowed.
... (examples are listed below.) cross-origin reads are typi
cally disallowed, but read access is often leaked by embedding.
Using templates and slots - Web Components
we'll
call it <my-paragraph>: customelements.define('my-paragraph', class extends htmlelement { constructor() { super(); let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(templatecontent.clonenode(true)); } } ); the key point to note here is that we a...
...e> and some javascript to: create a <element-details> element with named slots in its shadow root design the <element-details> element in such a way that, when used in documents, it is rendered from composing the element’s content together with content from its shadow root—that is, pieces of the element’s content are used to fill in named slots in its shadow root note that it is techni
cally possible to use <slot> element without a <template> element, e.g., within say a regular <div> element, and still take advantage of the place-holder features of <slot> for shadow dom content, and doing so may indeed avoid the small trouble of needing to first access the template element's content property (and clone it).
... in addition, even if it is not already rendered, the purpose of the container as a template should be more semanti
cally clear when using the <template>.
... for both <element-details> elements, an attributes heading gets automati
cally added from the shadow root before the position of the "attributes" named slot.
Caching compiled WebAssembly modules - WebAssembly
it is ideal for persisting assets lo
cally for the saved state of an application, including text, blobs, and any other type of cloneable object.
...any subsequent
call to instantiatecachedurl() will then clear out the entire cache, allowing you to avoid using out-of-date modules.
...(fetch(url)).then(results => { storeindatabase(db, results.module); return results.instance; }); }) }, note: it is for this kind of usage that webassembly.instantiate() returns both a module and an instance: the module represents the compiled code and can be stored/retrieved in idb or shared between workers via postmessage(); the instance is stateful and contains the
callable javascript functions, therefore it cannot be stored/shared.
... errmsg => { console.log(errmsg); return webassembly.instantiatestreaming(fetch(url)).then(results => { return results.instance }); }); } caching a wasm module with the above library function defined, getting a wasm module instance and using its exported features (while handling caching in the background) is as simple as
calling it with the following parameters: a cache version, which — as we explained above — you need to update when any wasm module is updated or moved to a different url.
Module structure of the SDK - Archive of obsolete content
commonjs defines: an object
called exports which contains all the objects which a commonjs module wants to make available to other modules a function
called require which a module can use to import the exports object of another module.
... low-level modules like heritage and namespace provide more powerful functionality, and are typi
cally less stable and more complex.
...just
call the following: const { require } = cu.import("resource://gre/modules/commonjs/toolkit/require.js", {}) this will import require() into your scope.
Porting the Library Detector - Archive of obsolete content
each test object contains a function
called test(): if the function finds the library, it defines various additional properties for the test object, such as a version property containing the library version.
... the content script, which we'll
call library-detector.js, will keep most of the logic of the test functions intact.
... main.js will create an array of icons corresponding to the array of library names, and use that to build the widget's html content dynami
cally: function buildwidgetviewcontent(librarylist) { widgetcontent = htmlcontentpreamble; librarylist.foreach(function(library) { widgetcontent += buildiconhtml(icons[library.name], library.name + "<br>version: " + library.version); }); widgetcontent += htmlcontentpostamble; return widgetcontent; } function updatewidgetview(tab) { var widgetview = widget.getview(tab.
Two Types of Scripts - Archive of obsolete content
this enables you to
call functions like: window.alert("hello there"); in an add-on's main scripts you can't do that, because the add-on code does not execute in the context of a page, and the dom is therefore not available.
...in the sdk documentation we
call one sort "add-on code" and the other sort "content scripts".
... minimally you'll have a single module implemented by a script
called "main.js", but you can include additional modules in lib, and import them using the require() function.
XUL Migration Guide - Archive of obsolete content
user interface components xul-based add-ons typi
cally implement a user interface using a combination of two techniques: xul overlays and xul windows.
... you can keep the "chrome.manifest" file in your add-on's root directory and create a directory there
called "chrome".
...because we expect to keep these apis compatible as new versions of firefox are released, we
call them the "supported" apis.
simple-storage - Archive of obsolete content
usage the simple storage module exports an object
called storage that is persistent and scoped to your add-on.
... accessing storage from the console in the add-on debugger, you can access your add-on's simple-storage programmati
cally from the console using the following: loader.modules['resource://gre/modules/commonjs/sdk/simple-storage.js'].exports.storage clarification from mozilla needed: writing the above line in add-on debugger console results in "referenceerror: loader is not defined".
...it will be
called when your storage goes over quota.
event/core - Archive of obsolete content
this will
call all registered listeners for the given type on the given event target in the same order they were registered.
...all listeners of the specific type can be easily removed (only two argument must be passed): off(target, 'message'); also, removing all registered listeners is possible (only one argument must be passed): off(target); globals functions on(target, type, listener) registers an event listener that is
called every time events of the specified type is emitted on the given event target.
... once(target, type, listener) registers an event listener that is
called only once: the next time an event of the specified type is emitted on the given event target.
event/target - Archive of obsolete content
such listeners are
called only once next time event of the specified type is emitted: target.once('ready', function onready() { // do the thing once ready!
... on(type, listener) registers an event listener that is
called every time events of specified type are emitted.
... returns eventtarget : returns the eventtarget instance once(type, listener) registers an event listener that is
called only once: the next time an event of the specified type is emitted.
places/favicon - Archive of obsolete content
globals functions getfavicon(object,
callback) takes an object that represents a page's url and returns a promise that resolves with the favicon url for that page.
...ring example getfavicon("http://mozilla.org").then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); // tab example require("sdk/tabs").open({ url: "http://mozilla.org", onready: function (tab) { getfavicon(tab).then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); } }); // an optional
callback can be provided to handle // the promise's resolve and reject states getfavicon("http://mozilla.org", function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); parameters object : string|tab a value that represents the url of the page to get the favicon url from.
...
callback : function an optional
callback function that will be used in both resolve and reject cases.
Displaying annotations - Archive of obsolete content
} 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); updatematchers(); } annotat...
... 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.
Getting Started (jpm) - Archive of obsolete content
the current tool is
called jpm, and is based on node.js.
... 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.
... note that firefox by default requires add-ons, even lo
cally developed ones, to be signed.
Logging - Archive of obsolete content
it is automati
cally made available to you.
...the following add-on logs the html content of every tab the user loads, by
calling console.log() inside a content script: require("sdk/tabs").on("ready", function(tab) { tab.attach({ contentscript: "console.log(document.body.innerhtml);" }); }); console output if you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used.
... but note that by default,
calls to console.log() will not result in any output in the error console for any installed add-ons: this includes add-ons installed using the add-on builder or using tools like the extension auto-installer.
Bookmarks - Archive of obsolete content
var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var newbkmkid = bmsvc.insertbookmark(newfolderid, uri, bmsvc.default_index, ""); this example instantiates the nsiioservice and uses it to create an nsiuri referring to the google web site, then
calls nsinavbookmarksservice.insertbookmark() to create a new bookmark to google, placing it at the end of the bookmarks folder referenced by newbkmkid.
... the item uri similarly, you can obtain the uri corresponding to a given bookmark item by
calling the nsinavbookmarksservice.getbookmarkuri() method.
...anged: function(abookmarkid, aproperty, aisannotationproperty, avalue) { myextension.dosomething(); }, onitemvisited: function(abookmarkid, avisitid, time) {}, onitemmoved: function(aitemid, aoldparent, aoldindex, anewparent, anewindex) {}, queryinterface: xpcomutils.generateqi([components.interfaces.nsinavbookmarkobserver]) }; // an extension var myextension = { // this function is
called when my add-on is loaded onload: function() { bmsvc.addobserver(myext_bookmarklistener, false); }, // this function is
called when my add-on is unloaded onunload: function() { bmsvc.removeobserver(myext_bookmarklistener); }, dosomething: function() { alert("did something."); } }; see also nsinavbookmarksservice nsinavbookmarkobserver places using xpcom without ...
Downloading Files - Archive of obsolete content
downloading files to download a file, create an instance of nsiwebbrowserpersist and
call its nsiwebbrowserpersist.saveuri() method, passing it a url to download and an nsifile instance representing the local file name/path.
...lprogress, amaxtotalprogress) { var percentcomplete = math.round((acurtotalprogress / amaxtotalprogress) * 100); progresselement.textcontent = percentcomplete +"%"; }, onstatechange: function(awebprogress, arequest, astateflags, astatus) { // do something } } persist.saveuri(obj_uri, null, null, null, "", targetfile, privacy); downloading files that require credentials before
calling nsiwebbrowserpersist.saveuri(), you need to set the progresslistener property of the nsiwebbrowserpersist instance to an object that implements nsiauthprompt.
...if you want to open a login prompt, you can use the default prompt by
calling the window watcher's getnewauthprompter() method.
Finding window handles - Archive of obsolete content
typi
cally the top level browser window hwnd has no children, although if there are windowed plugins (such as flash) visible in the window, they will have hwnds whose parent is the top level browser window hwnd.
...once you have a docshell, queryinterface it into nsibasewindow,
call getmainwidget on result, and then
call getnativedata(ns_native_window).
... re
call that nsibasewindow -> nativehandle returns the following in the different operating 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 = ser...
HTML in XUL for rich tooltips - Archive of obsolete content
specifi
cally, we create a rich tooltip that uses html instead of plain text.
...that tooltip is empty now, but we will use the mouseover event to dynami
cally populate the tooltip (which is about to be shown) with a different message for each menuitem.
... this is done by
calling the onmousetooltip function, which will take the tooltiphtml attribute of the element that is being hovered over and safely convert that into dom and inject it into the tooltip that will soon be shown.
Sidebar - Archive of obsolete content
to open a page in the "viewwebpanelssidebar" from chrome code (browser/addon/extension) such as from menuitem, it can
call: openwebpanel(atitle, auri); accessing the sidebar from a browser.xul script the sidebar content is always in a document separate from the main browser document (the sidebar is actually implemented as a xul browser element).
...for example the code below
calls a function defined in the sidebar's context: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; // verify that our sidebar is open at this moment: if (sidebarwindow.location.href == "chrome://yourextension/content/whatever.xul") { //
call "yournotificationfunction" in the sidebar's context: sidebarwindow.yournotificationfunction(anyarguments); } testing which sidebar is open the sidebar content may contain different panels (bookmarks, history, webpanel,...
... resizing the sidebar programmati
cally 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) .get...
Delayed Execution - Archive of obsolete content
queuing a task in the main event loop when a task needs to be only briefly delayed, such that it runs after the current
call chain returns, it can be added directly to the main thread's event queue rather than scheduled as a timeout: function executesoon(func) { services.tm.mainthread.dispatch(func, ci.nsithread.dispatch_normal); } using nsitimers to schedule tasks in instances where settimeout() and setinterval() are unavailable, or insufficient, tasks can be scheduled with delays using nsitimer instances.
... note: if an nsitimer is garbage collected, it will be deactivated and its
callbacks will not fire.
... some example usages include: const timer = components.constructor("@mozilla.org/timer;1", "nsitimer", "initwith
callback"); function delay(timeout, func) { let timer = new timer(function () { // remove the reference so that it can be reaped.
Code snippets - Archive of obsolete content
xml file i/o code used to read, write and process files drag & drop code used to setup and handle drag and drop events dialogs code used to display and process dialog boxes alerts and notifications modal and non-modal ways to notify users preferences code used to read, write, and modify preferences js xpcom code used to define and
call xpcom components in javascript running applications code used to run other applications <canvas> related what wg canvas-related code signing a xpi how to sign an xpi with pki delayed execution performing background operations.
...ugger service code used to interact with the javascript debugger service svg general general information and utilities svg animation animate svg using javascript and smil svg interacting with script using javascript and dom events to create interactive svg embedding svg in html and xul using svg to enhance html or xul based markup xul widgets html in xul for rich tooltips dynami
cally embed html into a xul element to attain markup in a tooltip label and description special uses and line breaking examples tree setup and manipulation of trees using xul and js scrollbar changing style of scrollbars.
... autocomplete code used to enable form autocomplete in a browser boxes tips and tricks when using boxes as containers tabbox removing and manipulating tabs in a tabbox windows-specific finding window handles (hwnd) (firefox) how to use windows api
calls to find various kinds of mozilla window handles.
Extension Etiquette - Archive of obsolete content
if possible, create a menu item in the menu where it is most applicable; for instance, a bookmark sharing extension should be
called from the bookmarks menu.
...
call .noconflict(true) where applicable many common libraries which create global variables provide a method
called noconflict, or similar, which revert any global variables they've declared, and return the object itself.
... for instance,
calling jquery.noconflict(true) will remove the window.jquery and window.$ variables, and return the jquery object itself, for future use by the
caller.
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
many add-ons need to dynami
cally generate dom content, either xul or html, from their scripts.
...parse element namespace prefix (if none exists, default to defaultnamespace), and create element var elemns = namespace(elemnameorarray); var elem = doc.createelementns(elemns.namespace || jsontodom.defaultnamespace, elemns.shortname); // set element's attributes and/or
callback functions (eg.
...under no circumstances should code resembling '
callback("' + str + '")' appear anywhere in your add-on.
Observer Notifications - Archive of obsolete content
you could do that by
calling all those functions directly, but xpcom offers you a better and cleaner way to achieve that using observers and the observer service.
... createinstance(components.interfaces.nsisupportsstring); // assign some text to data attribute subject.data = "this is a test."; // notify all registered observers observerservice.notifyobservers( subject, "xulschoolhello-test-topic", "hello"); } in the notifytest method, the notifyobservers
call is used to notify all registered observers about the notification topic "xulschoolhello-test-topic".
... when the notifytest method is
called, all observers registered with xulschoolhello-test-topic will get notified and display two alerts.
Setting Up a Development Environment - Archive of obsolete content
the install process requires using an environment variable
called ostype, which is not exported.
... to compile an idl file to xpt, you need a command line tool
called xpidl.
... you should also set up your environment so that xpidl.exe (or just xpidl on other systems) is in the default executable path, and also add a variable
called gecko_sdk, that points to your sdk build: export gecko_sdk=/path/to/your/sdk our build system should pick it up from there.
Security best practices in extensions - Archive of obsolete content
for pages coming from the server, you need to take steps to ensure that the content can not
call back into the web browser and run malicious code.
...give the element a type="content" attribute, which essentially sandboxes the code there and blocks
callback rights into chrome.
...the usefulness of it and power of how it works is best illustrated by the popular greasemonkey extension, which works on the premise of scripts being downloaded and stored lo
cally, to be injected into the web content context via the sandbox.
Signing an XPI - Archive of obsolete content
the 7-zip tool doesn't work when creating mozilla xpi signed archives because it sorts the directory entries alphabeti
cally, and mozilla requires the first entry to be meta-inf/zigbert.rsa.
... install the certificate into mozilla firefox (which goes with the private key created earlier), and copy/paste the displayed certificate text into a new file
called c:\projects\codesigning\certum code signing.cer.
...id" but i want it to be
called "code signing (certum)".
CSS3 - Archive of obsolete content
in order to accelerate the standardization of non-problematic features, the css working group of the w3c, in a decision referred as the beijing doctrine, divided css in smaller components
called modules .
... the w3 consortium periodi
cally publishes such snapshots, like in 2007, 2010, 2015, 2017, and 2018.
... working draft css grid layout unknown css line grid module level 1 working draft css positioned layout module level 3 working draft css regions module level 1 working draft defines a new mechanism allowing content to flow across, eventually non-contiguous, multiple areas
called regions.
Using content preferences - Archive of obsolete content
this permits code running within chrome (in other words: extensions and the browser itself, not web sites) to lo
cally save preferences on a per-site basis.
... browser.upload.lastdir path of a filesystem directory this preference is stored and retrieved automati
cally by file upload controls.
...starting in gecko 9.0, when in private browsing mode, the content preference service stores preferences in memory instead of on disk, and automati
cally forgets them when leaving private browsing mode.
Autodial for Windows NT - Archive of obsolete content
if you turn on the autodial feature, windows will automati
cally dial whenever any application tries to access a network address that can't be reached.
... techni
cally, this control panel applet (internet options) is part of internet explorer.
...if you are using a system with just a modem, the best approach is to configure the remote access auto connection service to automati
cally start.
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
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.
... xmlhttprequest will retrieve the document located at the given url and
call the updatetinderboxstatus() function when it is done.
...this is because we need to reference it in the updatetinderboxstatus() function as well as the current function, and we can't pass the object from one function to the other because the one doesn't
call the other directly.
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
start out by creating a directory
called tinderstatus-installer.
...ess"] { list-style-image: url("chrome://tinderstatus/content/tb-success.png"); } statusbarpanel#tinderbox-status[status="testfailed"] { list-style-image: url("chrome://tinderstatus/content/tb-testfailed.png"); } statusbarpanel#tinderbox-status[status="busted"] { list-style-image: url("chrome://tinderstatus/content/tb-busted.png"); } then we need to create two files in the directory, one
called contents.rdf which contains information for the chrome registry about the component being installed and one
called install.js that contains the code to install the component.
...ir = getfolder("chrome","tinderstatus"); setpackagefolder(installdir); adddirectory("tinderstatus"); registerchrome( content | delayed_chrome, getfolder(installdir, "content")); var result = performinstall(); if ( result != success ) cancelinstall(result); once all the files are in place, use your zip utility from within the tinderstatus-installer directory to create a zip archive
called tinderstatus.xpi with install.js and the entire contents of the tinderstatus/ directory.
Getting Started - Archive of obsolete content
copy everything in \mozilla\chrome\classic\skin\classic to a directory
called \myskin.
...place it in \myskin and
call it preview.png (if it's a jpg or gif
call it preview.jpg or preview.gif).
...change the blue part to whatever you want your theme
called and then its version number.
Drag and Drop Example - Archive of obsolete content
"button" elem="button" ondraggesture="nsdraganddrop.startdrag(event, listobserver)"/> <button label="check box" elem="checkbox" ondraggesture="nsdraganddrop.startdrag(event, listobserver)"/> <button label="text box" elem="textbox" ondraggesture="nsdraganddrop.startdrag(event, listobserver)"/> </vbox> the nsdraganddrop object will be
called to do most of the work.
...var listobserver = { ondragstart: function (event, transferdata, action) { var txt = event.target.getattribute("elem"); transferdata.data = new transferdata(); transferdata.data.adddataforflavour("text/unicode", txt); } } one function has been defined, ondragstart, which will be
called by the nsdraganddrop object when necessary.
...next, appendchild is
called to add the new element to the stack, which is the target of the event.
Enabling Experimental Jetpack Features - Archive of obsolete content
in python, you can
call from __future__ import foo which adds the functionality that foo yields to the script.
... in jetpack, we propse adding a new function to the base namespace
called importfromfuture.
...jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import()
call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration).
Enabling - Archive of obsolete content
in python, you can
call from __future__ import foo which adds the functionality that foo yields to the script.
... in jetpack, we propse adding a new function to the base namespace
called importfromfuture.
...jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import()
call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration).
Enabling Experimental Jetpack Features - Archive of obsolete content
in python, you can
call from __future__ import foo which adds the functionality that foo yields to the script.
... in jetpack, we propse adding a new function to the base namespace
called importfromfuture.
...jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import()
call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration).
Safely loading URIs - Archive of obsolete content
to solve this problem, gecko provides methods that allow the
caller to check whether it's safe to load a particular uri.
... these methods are exposed on the nsiscriptsecuritymanager interface and are
called checkloaduri, checkloaduriwithprincipal, and checkloaduristr.
...by passing the string to something that loads it in a <browser> or <iframe>), you must
call checkloaduristr to be secure.
Supporting private browsing mode - Archive of obsolete content
it will simply always report that private browsing is off, and will never
call any registered watcher functions.
...} in addition, you can install watcher functions to be
called when private browsing turns on and off, as shown in the following example.
... for example, the fire.fm extension has a preference
called "disable station history and scrobble when firefox is in private mode", and disabling publishing of that information inside the private browsing mode by default.
Running Tamarin acceptance tests - Archive of obsolete content
notes on using acceptance runtests.py threading in order to speed up the execution time of the acceptance testsuite, the runtests script automati
cally detects the number of cores on the machine and sets an equivalent number of threads.
...adb automati
cally connects to a phone if connected by usb.
...running with 2 or more phones uses threads to run tests in parallel and reduces running times dramati
cally.
URIs and URLs - Archive of obsolete content
overview handling network and lo
cally retrievable resources is a central part of necko.
...gateways, proxies, caches, and name resolution services might be used to access some resources, independent of the protocol of their origin, and the resolution of some url may require the use of more than one protocol (e.g., both dns and http are typi
cally used to access an "http" url's resource when it can't be found in a local cache).
...this authority component is typi
cally defined by an internet-based server or a scheme-specific registry of naming authorities.
Anonymous Content - Archive of obsolete content
for example, on the html file upload control, the anonymous textfield can be set up to automati
cally inherit the value attribute from the bound element.
...the location at which a children tag occurs is
called an insertion point.
... [editor's note: should there be an api for retrieving insertion points, for dynami
cally creating new insertion points, or for removing insertion points?
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 binding content children implementation constructor destructor field property getter setter method parameter body handlers handler resources stylesheet image binding attachment and detachment attachment using css attachment using element.style property <constructor>
call <destructor>
call binding documents dom interfaces the nsidomdocumentxbl interface anonymous content introduction scoping and access using the dom content generation rules for generation attribute forwarding insertion points <children> handling dom changes event flow and targeting flow and targeting across scopes focus and blur events mouseove...
... this example is targeted to demonstrate the xbl usage rather than to be a practi
cally useful application.
Install script template - Archive of obsolete content
= -4712; var invalidrootkeyerror = -4713; var registrykeynotwritableerror = -4714; //initinstall block //the installation is initialized here -- if we fail here, cancel the installation // initinstall is quite an overloaded method, but i have invoked it here with three strings // which are globally defined err = initinstall(software_name, plid, version); if (err != 0) { //
call initinstall again in case illegal characters in plid err = initinstall(software_name, software_name, version); if (err != 0) cancelinstall(err); } //addfiles to current browser block var pluginsfolder = getfolder("plugins"); //verify disk space if(verifydiskspace(pluginsfolder, plugin_size+component_size)) { // start installing plugin shared library reseterror(); // install the p...
... if(errblock2 == success) { // now take care of writing plids to the win32 registry err = writeplidsolution(); if(err!=success) { logcomment("could not write win32 keys as specified: " + err); } else { logcomment("plid entries are present in the win32 registry"); } } reseterror(); err = performinstall(); if (err == success) refreshplugins(true); //
call refreshplugins(true) if you'd like the web page which invoked the plugin to // reload.
... you can also simply
call refreshplugins() } else cancelinstall(errblock1); // plid solution -- write keys to the registry /** * function for secondary installation of plugin (firstinstall).
execute - Archive of obsolete content
your code must
call the performinstall method to actually execute the file.
...file.execute() executes an installed file (such as a browser) after it has been installed, and is typi
cally placed at the end of an install script and outside of the main install block.
... this means that in order to pass three command-line arguments (-c, -d, and -s) to the executable, you should format the args string as follows: err = file.execute(myfile, '"-c""-d""-s"', true); //techni
cally, given the rules above, you could also pass the same //arguments with the following line, but the result is much less //readable: err = file.execute(myfile, "\"-c\"\"-d\"\"-s\"", true); also see the note about binaries on the macintosh platform in addfile.
getLastError - Archive of obsolete content
description use getlasterror method to obtain the most recent nonzero error code since initinstall or reseterror were
called.
... this method allows you to defer checking for error codes each time you
call addfile or adddirectory until the last addfile or adddirectory
call.
...example the following example
calls getlasterror after a series of addfile
calls: addfile("npplug", ...); addfile("/ms/shared/ctl3d.dll", ...); addfile("/nethelp/royalplug/royalhelp.html",...); err = getlasterror(); ...
WinReg Object - Archive of obsolete content
instead, you construct an instance of this object by
calling the getwinregistry method of the install object.
...typi
cally values in the windows registry are strings.
...however, writing to the registry is delayed until performinstall is
called.
findbar - Archive of obsolete content
onfindagaincommand( findprevious ) return type: no return value
call this method to handle your application's "find next" and "find previous" commands.
... you should specify true as the input parameter to perform a "find previous" operation, or false to perform a "find next." startfind( mode ) return type: no return value
call this method to handle your application's "find" command.
... the first time this is
called for a given findbar, the findbar will flash to draw attention to itself.
startFind - Archive of obsolete content
« xul reference home startfind( mode ) return type: no return value
call this method to handle your application's "find" command.
... the first time this is
called for a given findbar, the findbar will flash to draw attention to itself.
... example typi
cally, you'll simply bind this method to your "find" command, like this: <command name="cmd_find" oncommand="gfindbar.startfind(gfindbar.find_normal);"/> ...
Extensions - Archive of obsolete content
function init() { var contextmenu = document.getelementbyid("contentareacontextmenu"); if (contextmenu) contextmenu.addeventlistener("popupshowing", thumbnailsshowhideitems, false); } function thumbnailsshowhideitems(event) { var show = document.getelementbyid("thumbnail-show"); show.hidden = (document.popupnode.localname != "img"); } the init function should be
called within the handler for the load event so that the popupshowing event handler is hooked up before it would be opened by the user.
... in this example, the thumbnailsshowhideitems function will be
called when the popup is about to be shown.
...specifi
cally, this object is initialized with a set of properties that indiciate the type of object that was the target of the context menu.
Positioning - Archive of obsolete content
tooltips will always appear near the current mouse position, offset verti
cally by a small amount.
...equivalent to topleft topleft after_pointer the popup appears verti
cally offset a few pixels from the mouse pointer (after_pointer is not currently implemented with respect to the mouse pointer.
... it currently offsets 21 pixels verti
cally from the anchor, see bug 619887).
Tooltips - Archive of obsolete content
elements that use the tooltiptext attribute display the tooltip in a default tooltip element, which typi
cally looks like a small yellow box large enough to fit the text inside it.
... this default tooltip is created automati
cally, so you don't normally need to use a tooltip element.
...however, the tree will automati
cally display tooltips for a cell when the value is cropped.
Popup Guide - Archive of obsolete content
specifi
cally, the first two types in the list below are menus.
...when the mouse is moved away from the control, the tooltip automati
cally disappears.
... opening a menu or popup most menus and popups are opened automati
cally when they are associated with an element.
Building Trees - Archive of obsolete content
but moreover, it uses a subtype of the main builder
called the tree builder.
...there may be situations that
call for this, typi
cally when handling smaller amounts of data.
... specifi
cally, the action body should be a single treeitem with its rows and cells.
Introduction - Archive of obsolete content
some other systems
call this databinding.
...typi
cally, the value will be a uri that identifies the location of the data.
...sometimes, you will want to specify the datasource to be used later, possibly determined dynami
cally by a script.
Template Logging - Archive of obsolete content
« previous debugging problems with a template can be difficult as many problems are logic errors that are often not possible to determine automati
cally.
...however,
calling getelementbyid using this id will retrieve the generated content for that result if you want to further study the content that was generated.
...naturally, semantic errors in the data in the datasource can't be easily detected automati
cally.
Box Objects - Archive of obsolete content
re
call that all xul elements are types of boxes, that is the box is the base of all displayed xul elements.
...however, xul provides some helper objects,
called box objects, which can provide some layout related information.
...re
call that dom properties such as childnodes, firstchild, and nextsibling may be used to navigate the document tree.
Content Panels - Archive of obsolete content
instead, you must use a script and
call the loaduri function.
...the tabbrowser sets the content type automati
cally on all tabbed browsers that it creates.
...the tabbrowser automati
cally sets the type attribute of whichever browser is currently visible to content-primary, which means that you will always be able to access the currently visible content in this way.
Introduction to XBL - Archive of obsolete content
the template has two bindings, one
called binding1 and the other
called binding2.
...they can be
called from a script.
...however, to summarize, it causes two buttons to be added automati
cally inside the box, one an ok button and the other a cancel button.
Localization - Archive of obsolete content
typi
cally, you will have one dtd file for each xul file, usually with the same filename except with a .dtd extension.
... so, for the find files dialog, we will need a file
called findfile.dtd.
...this line is typi
cally placed just before the window element.
More Tree Features - Archive of obsolete content
when the user expands and collapses the parent, the view's toggleopenstate function will be
called to toggle the item between open and closed.
...as can be seen in the image, a small plus or minus sign (often
called a twisty) has appeared next to the first row, indicating that it contains child rows.
...thus, once the user has decided on a column layout they like, it will automati
cally be saved for next time.
Popup Menus - Archive of obsolete content
popup menus are typi
cally displayed when the user presses the right mouse button.
...typi
cally, this will be a specific button or a box.
...it currently offsets 21 pixels verti
cally from the anchor, see bug 619887).
Styling a Tree - Archive of obsolete content
we'll use a property
called 'makeitblue'.
...the following properties are automati
cally set as needed: checked this property is set cells whose column is type="checkbox" focus this property is set if the tree currently has the focus.
...you can
call appendelement() again to add additional properties.
Templates - Archive of obsolete content
<button class="rdf:http://www.example.com/rdf#class" uri="rdf:*" label="rdf:http://www.example.com/rdf#name" crop="rdf:http://www.example.com/rdf#crop"/> as you can see, you can dynami
cally generate lists of elements with the attributes provided by a separate datasource.
...when this attribute is present, an object
called a builder is added to the element which is responsible for building the content from the template.
... in javascript you can access the builder object with the builder property, although usually you would only need to do this to have the builder regenerate the content in situations where it is not done automati
cally.
Toolbars - Archive of obsolete content
toolbars may be placed on any side of the window, either horizontally or verti
cally.
...typi
cally however, a set of toolbars would appear along the top of a window.
... when more than one toolbar is placed next to each other, they are typi
cally grouped together in something
called a 'toolbox'.
Using Remote XUL - Archive of obsolete content
xul loaded and rendered in this way is
called remote xul and can be used for basic functions like web site navigation as well as to build sophisticated web-based applications.
... in case you're wondering, the reason the buttons and menu items had style before we added the stylesheet reference is that some xul elements are defined in mozilla using another xml-based language
called xbl which provides building blocks for creating ui widgets.
...we add an id attribute to the iframe element so we can reference it from our function, and we add an oncommand event listener to the menubar element that
calls the function every time the user clicks a button or selects a menu item.
Using the standard theme - Archive of obsolete content
you can either provide a complete custom styling, but most of the time you also want to be able to reuse the standard theme (also
called the "global skin") of the base application for non-custom elements, transparently with regard to which theme the user has currently chosen.
... applying the standard theme in order to use the theme currently chosen by the user of the base application (the so
called "global skin"), you have to add the following line to your xul file: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> this imports the styles found in the <tt>global/skin</tt> chrome directory and will make the standard xul widgets of your application use the selected chosen theme.
...tt> chains first, import the global skin in your custom style sheet using the css <tt>@import</tt> rule: @import url("chrome://global/skin/"); you then have to associate your xul file with your custom style sheet only: <?xml-stylesheet href="chrome://myextension/skin/custom.css" type="text/css"?> applying different custom style sheets depending on the selected theme mozilla is able to automati
cally pick your custom style sheet depending on the theme currently chosen by the user.
XML - Archive of obsolete content
it does not describe the way in which this data is to be presented, like its semanti
cally-challenged cousin html does, and it doesn't have much to say about the data itself.
... when we say language, we mean that developers create a set of terms, orlexicon, and a relationship between these terms, or what some people
call agrammar.
...in fact, let's create a new xml-based language right now
called "memoml".
editor - Archive of obsolete content
call the makeeditable method to make the document loaded in the editor editable.
...properties accessibletype, commandmanager, contentdocument, contentwindow, docshell, editingsession, editortype, webbrowserfind, webnavigation methods geteditor, gethtmleditor, makeeditable examples this example shows how to made the editor editable by setting the designmode property of the loaded html document: <script language="javascript"> function initeditor(){ // this function is
called to set up the editor var editor = document.getelementbyid("myeditor"); editor.contentdocument.designmode = 'on'; } </script> <editor id="myeditor" editortype="html" src="about:blank" flex="1" type="content-primary"/> once editable, the document can have special formatting and other html pieces added to it using the document.execcommand method: var editor = document.getelementbyid("myed...
...most of its methods are
callable directly on the element itself, such as goback and goforward.
image - Archive of obsolete content
image.onload type: script code this event handler will be
called on the image element when the image has finished loading.
...this typi
cally looks like an exclamation mark.
...this will typi
cally be a red "x" icon.
menupopup - Archive of obsolete content
example: <menupopup id="top" onpopuphidden="console.log('the onpopuphidden method of id=top was
called.');"> <menuitem label="item 1"/> <menuitem label="item 2"/> <menu id="submenu1" label="submenu 1"> <menupopup id="submenu1-popup"> <menuitem label="submenu1 item 1"/> <menuitem label="submenu1 item 2"/> </menupopup> </menu> <menu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="subme...
...this handler is usually used to dynami
cally set the contents when the user requests to display it.
... if both x and y have the value -1 the
call will realign the popup with its anchor node.
promptBox - Archive of obsolete content
method overview nsidomelement appendprompt(args, onclose
callback); void removeprompt(nsidomelement aprompt); nodelist listprompts(nsidomelement aprompt); methods appendprompt() creates a new prompt, adding it to the tab.
... nsidomelement appendprompt( args, onclose
callback ); parameters args arguments for the prompt.
... onclose
callback the
callback routine to be
called when the prompt is closed.
toolbar - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a container which typi
cally contains a row of buttons.
...the value is updated automati
cally by the toolbar customization dialog.
...be careful, as setting this property doesn't automati
cally update the currentset attribute.
tree - Archive of obsolete content
however, the content view will automati
cally update the tree if treeitems are changed.
...the tree view's nsitreeview.getcelltext() method is
called to obtain the cell contents.
...if the shouldaccept parameter is true, the cell's label is changed to the edited value (the tree view's nsitreeview.setcelltext() method is
called to change the cell contents).
wizard - Archive of obsolete content
ssamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata « xul reference home advance( pageid ) return type: no return value
call this method to go to the next page.
... cancel() return type: no return value
call this method to cancel and close the wizard.
... rewind() return type: no return value
call this method to go back a page.
Dialogs in XULRunner - Archive of obsolete content
e dialog"/> <groupbox flex="1"> <caption label="select favorite fruit"/> <radiogroup> <radio id="1" label="oranges because they are fruity"/> <radio id="2" selected="true" label="strawberries because of color"/> <radio id="3" label="bananna because it pre packaged"/> </radiogroup> </groupbox> </dialog> xul window elements have a special method to open dialogs,
called window.opendialog().
...in an effort to make things easier for developers and more consistent for users, xul has a mechanism to automati
cally create and position the core dialog buttons ("ok," "cancel," and "help" for example).
... the developer just declares the need for the button, the button's caption, and the access key for the button, as well as the javascript function to
call if the button is pressed.
MacFAQ - Archive of obsolete content
for command-line work, you would
call on: /applications/(vendor)/(name).app/contents/macos/xulrunner ui notes menus to enable your application quit command to work with the application menu (the one to the right of the blue apple), you need to give your quit menu item an id of "menu_filequititem".
...the toolkit will automati
cally enable this behavior if you add class="chromeclass-toolbar" to your <toolbar> element.
... 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"?>...
2006-12-01 - Archive of obsolete content
basic feature that i think is a must in any web broswer a discussion revolving around the idea of having firefox automati
cally convert mistaken non-english characters to english so that web addresses will be completed.
... windows dde shell integration removal a
call for responses or concerns regarding the removal of the dde shell integration.
... question regarding how to access the functionality that arises when window.blur() is
called.
JS-Engine FAQ - Archive of obsolete content
how to determine rhino version programati
cally?
... you can
call getimplementationversion() on a context instance and it gives you a string, e.g.
... non-js-engine questions can i
call functions in mozilla extensions from web page?
NPN_GetURL - Archive of obsolete content
if target is null, the application creates a new stream and delivers the data to the plug-in instance, through
calls to npp_newstream(), npp_writeready() and npp_write(), and npp_destroystream().
...it is typi
cally asynchronous but this is not guaranteed.
... the plug-in could
call npn_geturl() and receive data from the url right away, but more often the data arrives later.
NPN_Invoke - Archive of obsolete content
syntax #include <npruntime.h> bool npn_invoke(npp npp, npobject *npobj, npidentifier methodname, const npvariant *args, uint32_t argcount, npvariant *result); parameters the function has the following parameters: npp the npp indicating which plugin wants to
call the method on the object.
...when the
caller no longer needs the result, it must
call npn_releasevariantvalue() to release it.
...note: early on in the development of the scriptability api this method used to be
called npn_
call() but was renamed for consistency.
NPN_ReleaseVariantValue - Archive of obsolete content
this must always be
called on result variants and such in this api, i.e.
... any npvariant whose value comes from a
call that passes back an npvariant must be released using this function.
...npn_releasevariantvalue() will
call npn_releaseobject() on npvariants of type npvarianttype_object, and npn_memfree() on npvariants of type npvarianttype_string.
NPP_URLNotify - Archive of obsolete content
notifydata plug-in-private value for associating a previous npn_geturlnotify() or npn_posturlnotify() request with a subsequent npp_urlnotify()
call.
... description the browser
calls npp_urlnotify() after the completion of a npn_geturlnotify() or npn_posturlnotify() request to inform the plug-in that the request was completed and supply a reason code for the completion.
... the parameter notifydata is the plug-in-private value passed as an argument by a previous npn_geturlnotify() or npn_posturlnotify()
call, and can be used as an identifier for the request.
NP_Initialize - Archive of obsolete content
description the browser
calls this function only once: when a plug-in is loaded, before the first instance is created.
... this is the first function that the browser
calls.
... after the last instance of a plug-in has been deleted, the browser
calls np_shutdown, where you can release allocated memory or resources.
The First Install Problem - Archive of obsolete content
this uri nomenclature is
called a plugin identifier (plid) and is described on a separate page.
...example: a piece of software
called myapplication might create hkey_local_machine\software\mozillaplugins\@mycompany.com/myapplication,version=5.0.1/ where the plid is something the corporation that makes myapplication (mycompany inc.) determines.
... the example registry key shows the suggested "key creation" at work for an example application
called scobe scrubobat (which doesn't really exist!).
What is RSS - Archive of obsolete content
techni
cally speaking, userland's rss 0.91 is a subset of netscape's rss 0.91.
... <link>http://joe-blow.example.net/log/19</link> </item> <item> <title>black cat spotted</title> <guid>http://joe-blow.example.net/log/18</guid> <pubdate>fri, 13 may 2005 13:13:13 -0500</pubdate> <link>http://joe-blow.example.net/log/18</link> </item> </channel> </rss> note: broadcasting of internet radio is sometimes
call podcasting, ipradio, and audio blogging.
...and were designed to give you an idea about what rss basi
cally looks like.
Proposal - Archive of obsolete content
those labeled with "draft exists" can be implemented, but be warned that they could radi
cally change.
...the transform must already exist on the machine running newsgator; stylesheets will not be downloaded or installed automati
cally.
...draft exists source guid when an rss item is posted in response to a previous item (
called the source item) rss 2.0 offers the source element which allows the item to refer to the rss feed which contains the source item.
SSL and TLS - Archive of obsolete content
an ssl/tls session always begins with an exchange of messages
called the ssl handshake, initial communication between the server and client.
...this cipher suite is no longer fips-compliant because it is too weak cryptographi
cally.
...ecc creates cryptographi
cally-stronger keys with shorter key lengths than rsa, which makes it faster and more efficient to implement.
Array.observe() - Archive of obsolete content
syntax array.observe(arr,
callback) parameters arr the array to be observed.
...
callback the function
called each time changes are made, with the following argument: changes an array of objects each representing a change.
... description the
callback function is
called each time a change is made to arr, with an array of all changes in the order in which they occurred.
Archived JavaScript Reference - Archive of obsolete content
obsolete javascript features and unmaintained docs arguments.
callerthe obsolete arguments.
caller property used to provide the function that invoked the currently executing function.
...information about javascript's version history and implementation status for mozilla/spidermonkey-based javascript applications, such as firefox.number.tointeger()the number.tointeger() method used to evaluate the passed value and convert it to an integer, but its implementation has been removed.object.getnotifier()the object.getnotifer() method was used to create an object that allows to syntheti
cally trigger a change, but has been deprecated and removed in browsers.object.observe()the object.observe() method was used for asynchronously observing the changes to an object.
...you can use the more general proxy object instead.object.prototype.__count__the __count__ property used to store the count of enumerable properties on the object, but it has been removed.object.prototype.__nosuchmethod__the __nosuchmethod__ property used to reference a function to be executed when a non-existent method is
called on an object, but this function is no longer available.object.prototype.__parent__the __parent__ property used to point to an object's context, but it has been removed.object.prototype.eval()the object.eval() method used to evaluate a string of javascript code in the context of an object, however, this method has been removed.object.prototype.unwatch()the unwatch() method removes a watchpoint s...
LiveConnect - Archive of obsolete content
liveconnect provides javascript with the ability to
call methods of java classes and vice-versa using the existing java infrastructure.
... liveconnect use by applets is enabled via the use of the "mayscript" attribute in applet tags on an html page, following which the applet may refer to classes in the netscape.javascript package to access javascript objects, and scripts may directly
call applet methods (using the syntax document.applets.name.methodname()).
... note: liveconnect blocked under some conditions liveconnect
calls from javascript to java api are blocked when the java control panel security slider is set to very high level, or when the slider is at the default high level and the jre has either expired or is below the security baseline.
Implementation Status - Archive of obsolete content
ncedocument() supported 4.8.2 rebuild() supported 4.8.3 recalculate() supported 4.8.4 revalidate() supported 4.8.5 refresh() supported 4.9 feature string for the hasfeature method
call supported 5.
...e when @at evaluates to nan 303198; 10.5 setindex supported 10.6 toggle supported 10.7 setfocus supported 10.8 dispatch supported 10.9 rebuild partial is dispatching events instead of
calling directly 332231; 10.10 recalculate partial is dispatching events instead of
calling directly.
... 332231; 349805; 10.11 revalidate partial is dispatching events instead of
calling directly 332231; 10.12 refresh partial is dispatching events instead of
calling directly 332231; 10.13 reset supported 10.14 load partial no xforms-link-error generated if @src invalid 333782; 10.15 send supported 10.16 message partial output inside message doesn't work correctly 366886; 10.17 conditional execution of xforms actions support...
Describing microformats in JavaScript - Archive of obsolete content
if it's virtual, the virtualgetter() method will be
called to attempt to create the property if it doesn't exist.
... virtualgetter a function that is
called to get a virtual property's value.
... the microformat is registered with the microformat api by
calling microformats.add(), like this: microformats.add("adr", adr_definition); note: to be clear: since the adr microformat is included by default in firefox 3 and later, you don't need to add it yourself if you wish to make use of it.
Archive of obsolete content
if anyone might realisti
cally need the information in a living product, it may not be appropriate to move it here.
... creating a status bar extension many of the concepts introduced here apply to any xul-based application; however, to keep from getting completely overwhelmed, we're going to focus specifi
cally on firefox.
...the new mozilla xpcom architecture allows xpcom components be scriptable via a different mechanism
called xpconnect.
Explaining basic 3D theory - Game development
there are four stages to this processing: the first one involves arranging the objects in the world, and is
called model transformation.
... projection transformation (also
called perspective transformation) then defines the camera settings.
...textures are combined from single texture elements
called texels the same way picture elements are combined from pixels.
Building up a basic demo with Three.js - Game development
the aspect ratio is set to the current width and height of the window so it will be dynami
cally adjusted.
...first, we implement a helper variable,
called t, for counting elapsed time.
... conclusion here's the final code: you can also see it on github and fork the repository, if you want to play with it lo
cally.
Move the ball - Game development
techni
cally, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies.
...the draw() function will be executed within setinterval every 10 miliseconds: function draw() { // drawing code } setinterval(draw, 10); thanks to the infinite nature of setinterval the draw() function will be
called every 10 milliseconds forever, or until we stop it.
...first, instead of a hardcoded position at (50,50) we will define a starting point at the bottom center part of the canvas in variables
called x and y, then use those to define the position the circle is drawn at.
Extra lives - Game development
to make it easier for us to maintain in the future we can create a separate variable that will hold our styling, let's
call it textstyle and place it before the text definitions: textstyle = { font: '18px arial', fill: '#0095dd' }; we can now use this variable when stlying our text labels — update your code so that the multiple instances of the text styling are replaced with the variable: scoretext = game.add.text(5, 5, 'points: 0', textstyle); livestext = game.add.text(game.world.width-5, 5, 'lives: '+lives, te...
...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.
... events you have probably noticed the add() and addonce() method
calls in the above two code blocks and wondered how they differ.
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() { // ...
... rendering the paddle, with physics next up, we will init our paddle by adding the following add.sprite()
call inside the create() function — add it right at the bottom: paddle = game.add.sprite(game.world.width*0.5, game.world.height-5, 'paddle'); we can use the world.width and world.height values to position the paddle exactly where we want it: game.world.width*0.5 will be right in the middle of the screen.
...it's very similar to positioning the paddle — we need to have it placed in the middle of the screen horizontally and at the bottom verti
cally with a little offset from the bottom.
2D maze game with device orientation - Game development
back to game states: the line below is adding a new state
called boot to the game: game.state.add('boot', ball.boot); the first value is the name of the state and the second one is the object we want to assign to it.
...}; ball.boot = function(game) {}; ball.boot.prototype = { preload: function() { this.load.image('preloaderbg', 'img/loading-bg.png'); this.load.image('preloaderbar', 'img/loading-bar.png'); }, create: function() { this.game.scale.scalemode = phaser.scalemanager.show_all; this.game.scale.pagealignhorizontally = true; this.game.scale.pagealignverti
cally = true; this.game.state.start('preloader'); } }; the main ball object is defined and we're adding two variables
called _width and _height that are the width and the height of the game canvas — they will help us position the elements on the screen.
...let’s focus on the keyboard first by adding the following to the create() function : this.keys = this.game.input.keyboard.createcursorkeys(); as you can see there’s a special phaser function
called createcursorkeys(), which will give us an object with event handlers for the four arrow keys to play with: up, down, left and right.
Gecko FAQ - Gecko Redirect 1
basi
cally, a layout engine takes content (such as html, xml, image files, applets, and so on) and formatting information (such as cascading style sheets, presentational html tags, etc.) and displays the formatted content on the screen.
...prefix css 2 - partial support is expected and has already been built into gecko, including support for css2 positioning, but no commitment has been made to achieve a specific level of support dom level 0 level 1 core: full support making entityreferences available through dom1; per a provision of the dom1 spec for xml implementations, entities will be automati
cally expanded inline and therefore not available through dom1; our implementation extrapolates this provision to apply to entityreferences as well for more information, see the dom in mozilla level 1 html dom 2 - most of it has already been implemented in gecko, including support for dom 2 events, the dom 2 style, and the dom2 core.
...as robert o'
callahan notes in bug 25707, "full html4/css1 compliance can't mean '100% bug free'.
Decryption - MDN Web Docs Glossary: Definitions of Web-related terms
decryption is a cryptographic primitive: it transforms a ciphertext message into plaintext using a cryptographic algorithm
called a cipher.
... like encryption, decryption in modern ciphers is performed using a specific algorithm and a secret,
called the key.
... decryption is the reverse of encryption and if the key stays secret, decryption without knowing the specific secret, decryption is mathemati
cally hard to perform.
Encryption - MDN Web Docs Glossary: Definitions of Web-related terms
encryption is a cryptographic primitive: it transforms a plaintext message into a ciphertext using a cryptographic algorithm
called a cipher.
... encryption in modern ciphers is performed using a specific algorithm and a secret,
called the key.
... without knowing the secret, the reverse operation, decryption, is mathemati
cally hard to perform.
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
for example: in a web browser, any code which the script doesn't specifi
cally start up as a background task has a window as its global object.
... scripts running under node.js have an object
called global as their global object.
...we created a global function
called greeting, then invoked it using the window object.
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
hoisting was thought up as a general way of thinking about how execution contexts (specifi
cally the creation and execution phases) work in javascript.
... conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physi
cally moved to the top of your code, but this is not in fact what happens.
...now, let's see what happens when we
call the function before we write it: catname("chloe"); function catname(name) { console.log("my cat's name is " + name); } /* the result of the code above is: "my cat's name is chloe" */ even though we
call the function in our code first, before the function is written, the code still works.
REST - MDN Web Docs Glossary: Definitions of Web-related terms
a system is
called restful when it adhere to those constraints.
...a document, is transferred with its state and relationships via well-defined, standarized operations and formats or services
call themselves restful when they directly modify type of document as opposed to triggering actions somewhere.
...beginners can assume a rest api means an http service that can be
called using standard web libraries and tools.
RGB - MDN Web Docs Glossary: Definitions of Web-related terms
each color is described by a sequence of three numbers (typi
cally between 0.0 and 1.0, or between 0 and 255) that represent the different intensities (or contributions) of red, green, and blue, in determining the final color.
...in opengl, webgl, and glsl the red-green-blue components are fractions (floating-point numbers between 0.0 and 1.0), although in the actual color buffer they are typi
cally stored as 8-bit integers.
... graphi
cally, a color can be represented as a point in a three-dimensional grid or cube, where each dimension (or axis) corresponds to a different channel.
Static method - MDN Web Docs Glossary: Definitions of Web-related terms
in a web api, a static method is one which is defined by an interface but can be
called without instantiating an object of that type first.
... methods
called on object instances are
called instance methods.
... examples in the 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(); ...
Debugging CSS - Learn web development
in the css we have applied: em { color: hotpink; font-weight: bold; } above that in the stylesheet however is a rule with a .special selector: .special { color: orange; } as you will re
call from the lesson on cascade and inheritance where we discussed specificity, class selectors are more specific than element selectors, and so this is the value that applies.
...sometimes the solution magi
cally appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier.
... to create a reduced test case: if your markup is dynami
cally generated — for example via a cms — make a static version of the output that shows the problem.
Fundamental CSS comprehension - Learn web development
call it something really imaginative like style.css.
...re
call from earlier that the content box height should be 30px — this gives you all the numbers you need to calculate the line height.
...re
call from earlier that the content box height should be 30px — this gives you all the numbers you need to calculate the line height.
Combinators - Learn web development
previous overview: building blocks next the final selectors we will look at are
called combinators, because they combine other selectors in a way that gives them a useful relationship to each other and the location of content in the document.
... descendant combinator the descendant combinator — typi
cally represented by a single space ( ) character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first selector.
... selectors that utilize a descendant combinator are
called descendant selectors.
Pseudo-classes and pseudo-elements - Learn web development
examples include: :hover — mentioned above; this only applies if the user moves their pointer over an element, typi
cally a link.
... it acts as if a <span> was magi
cally wrapped around that first formatted line, and updated each time the line length changed.
... ::marker matches the marker box of a list item, which typi
cally contains a bullet or number.
CSS values and units - Learn web development
the terms are basi
cally interchangeable — when you see something in css referred to as a data type, it is really just a fancy way of saying value.
...for example we don't typi
cally use cm (centimeters) on screen.
... a typical position value consists of two values — the first sets the position horizontally, the second verti
cally.
Styling links - Learn web development
this can be specifi
cally styled using the :link pseudo class.
... focus: a link when it has been focused (for example moved to by a keyboard user using the tab key or similar, or programmati
cally focused using htmlelement.focus()) — this is styled using the :focus pseudo class.
...we center the text inside each link, set the line-height to 3 to give the buttons some height (which also has the advantage of centering the text verti
cally), and set the text color to black.
Web fonts - Learn web development
there are only a handful of fonts that you can guarantee to be available across all common systems — the so-
called web-safe fonts.
...if you are importing multiple weights of the same font, you can specify what their weight/style is and then use different values of font-weight/font-style to choose between them, rather than having to
call all the different members of the font family different names.
... 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.
What text editors are available? - Learn web development
save you time by auto-completing recurring structures (for example, automati
cally close html tags, or suggesting valid values for a given css property).
...these functionalities are often helpful: search-and-replace, in one or multiple documents, based on regular expressions or other patterns as needed quickly jump to a given line view two parts of a large document separately view html as it will look in the browser select text in multiple places at once view your project's files and directories format your code automati
cally with code beautifier check spelling auto-indent code based on indentation settings do i want to add extra features to my text editor?
...the best editors provide many plugins, and ideally a way to look for and install new plugins automati
cally.
Test your skills: Other controls - Learn web development
associate it semanti
cally with the provided "comment" label.
... associate it semanti
cally with the provided "comment" label.
...however, this time we want to do things differently: create a basic text input that is semanti
cally associated with the provided label.
What will your website look like? - Learn web development
a website can do basi
cally anything, but, for your first try, you should keep things simple.
...this is sometimes
called a design guide, design system, or brand book, and you can see an example at the firefox photon design system.
...that's
called a hex code (short for hexadecimal), and represents your color.
Debugging HTML - Learn web development
if you look at the listing, you can probably see how println!(hello, world!"); might logi
cally be missing a double quote.
... first, download our debug-example demo and save it lo
cally.
... "end of file seen and there were open elements": this is a bit ambiguous, but basi
cally refers to the fact there are open elements that need to be properly closed.
Document and website structure - Learn web development
scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress
call had made it through.</p> <hr> <p>meanwhile, harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap.
...this is
called information architecture.
...this is very similar to a technique
called card sorting.
HTML text fundamentals - Learn web development
this is done with software
called a screen reader.
...doing it lo
cally will probably be better, as then you'll get to save the work you are doing, whereas if you fill it in to the editable example, it will be lost the next time you open the page.
...use the <u> element when it's semanti
cally appropriate, but consider using css to change the default underline to something more appropriate on the web.
Test your skills: Advanced HTML text - Learn web development
advanced html text 2 in this task we want you to add some semantics to the provided html as follows: turn the second paragraph into a block-level quote, and semanti
cally indicate that the quote is taken from accessibility.
... semanti
cally mark up "html" and "css" as acronyms, providing expansions as tooltips.
... semanti
cally associate machine-readable dates with the dates in the text.
Images in HTML - Learn web development
so for example, if your image is
called dinosaur.jpg, and it sits in the same directory as your html page, you could embed the image like so: <img src="dinosaur.jpg"> if the image was in an images subdirectory, which was inside the same directory as the html page (which google recommends for seo/indexing purposes), then you'd embed it like this: <img src="images/dinosaur.jpg"> and so on.
...this is
called "hotlinking".
...but there is a problem here: there is nothing that semanti
cally links the image to its caption, which can cause problems for screen readers.
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.
...the following subsections detail what you need to do: preparing images using your favourite image editor, create 400px wide and 120px wide versions of: firefox_logo-only_rgb.png firefox-addons.jpg mozilla-dinosaur-head.png
call them something sensible, e.g.
...again,
call them something sensible so you can easily identify them.
HTML table basics - Learn web development
tables are not automati
cally responsive: when you use proper layout containers (such as <header>, <section>, <article>, or <div>), their width defaults to 100% of their parent element.
...update the contents of your table to look like so: <td>hi, i'm your first cell.</td> <td>i'm your second cell.</td> <td>i'm your third cell.</td> <td>i'm your fourth cell.</td> as you will see, the cells are not placed underneath each other, rather they are automati
cally aligned with each other on the same row.
... to recognize the table headers as headers, both visually and semanti
cally, you can use the <th> element ('th' stands for 'table header').
Basic math in JavaScript — numbers and operators - Learn web development
there is an operator
called typeof in javascript that does this.
... 10 / 5 % remainder (sometimes
called modulo) returns the remainder left over after you've divided the left number into a number of integer portions equal to the right number.
...the box is drawn using a browser api
called the canvas api.
Solve common problems in your JavaScript code - Learn web development
one of the most common errors is to declare the function, but not
call it anywhere.
... for example: function myfunction() { alert('this is my function.'); }; this code won't do anything unless you
call it with the following statement: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e.
... how do you run (
call, or invoke) a function?
Test your skills: JSON - Learn web development
the json is loaded into the page as a text string and made available in the catstring parameter of the displaycatinfo() function,
called when the provided promise chain (which starts by fetching the json data) is fulfilled.
...the example won't work lo
cally, or in an environment like codepen or jsfiddle, because of something
called cross-origin security.
... this basi
cally means that you can't request a file from one origin using code on a different origin.
What is web performance? - Learn web development
making the site usable as soon as possible: this basi
cally means loading your web site assets in a sensible order so that the user can start to actually use it really quickly.
... any other assets can continue to load in the background while the user gets on with primary tasks, and sometimes we only load assets when they are actually needed (this is
called lazy loading).
... the measurement of how long it takes the site to get to a usable start after it has started loading is
called time to interactive.
React resources - Learn web development
class components although this tutorial doesn’t mention them, it is possible to build react components using es6 classes – these are
called class components.
...this is
called client-side routing.
... reach router is well-suited to simpler applications, and automati
cally manages focus as the user navigates from page to page.
Using Vue computed properties - Learn web development
previous overview: client-side javascript frameworks next in this article we'll add a counter that displays the number of completed todo items, using a feature of vue
called computed properties.
... in app.vue, add a new method
called updatedonestatus(), below your addtodo() method.
...update your <to-do-item></to-do-item>
call as follows: <to-do-item :label="item.label" :done="item.done" :id="item.id" @checkbox-changed="updatedonestatus(item.id)"> </to-do-item> now if you check a todoitem, you should see the summary update appropriately!
Styling Vue components with CSS - Learn web development
to start with, create a file
called reset.css in the src/assets directory.
... while this tutorial will not be using such tools, it's good to know that when including such code in the assets folder it will be processed automati
cally.
... #f5f5f5; color: #4d4d4d; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; } @media screen and (min-width: 620px) { body { font-size: 1.9rem; line-height: 1.31579; } } /*end resets*/ next, in your src/main.js file, import the reset.css file like so: import './assets/reset.css'; this will cause the file to get picked up during the build step and automati
cally added to our site.
Implementing feature detection - Learn web development
you can look at the different effects these two files have by manually changing the css file referred to by the second <link> element, but let's instead implement some javascript to automati
cally swap them as needed.
...we will fill this in dynami
cally later on.
...generally, such tests are done via one of the following common patterns: summary of javascript feature detection techniques feature detection type explanation example if member in object check whether a certain method or property (typi
cally an entry point into using the api or other feature you are detecting for) exists in its parent object.
Adding a new CSS property
some common mistakes to watch out for when writing custom parsing code (which might go away if we redesign the parser along the lines described in css3-syntax): make sure to
call skipuntil() to look for the matching close parentheses, braces, or brackets whenever you hit an error inside of them.
... make sure to
call ungettoken() if you have
called gettoken() but the result is unexpected.
... 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.
HTTP logging
using the rotate module automati
cally adds timestamps to the log, so it’s always easy to recognize which file keeps the most recent data.
... use 'sync' if your browser crashes or hangs by default, http logging buffers messages and only periodi
cally writes them to disk (this is more efficient and also makes logging less likely to interfere with race conditions, etc).
... there's a handy extension for firefox
called http header live that you can use to capture just the http request and response headers.
Makefiles - Best practices and suggestions
for classes of hardware (unix/windows) place your makefile in a subdirectory, unix/makefile.in always include dependencies when creating a target initial make
call should always be the workhorse: build, generate, deploy, install, etc.
... all subsequent make
calls must become a nop unless sources or dependencies change or have been removed.
... parallel make: add an explicit timestamp dependency (.done) that make can synchronize threaded
calls on to avoid a race condition.
Old Thunderbird build
first, cd into the comm-central subdirectory (created automati
cally by the previous command): cd comm-central then run: python client.py checkout on some types of network connections, "hg clone" might fail because it gets interrupted.
...it is also possible to rebuild specifi
cally.
...those have caused several problems histori
cally and tend to be poorly tested when the build system changes.
Simple Thunderbird build
get the latest mozilla source code from mozilla's mozilla-central mercurial code repository, and check it out into a local directory source/ (or however you want to
call it).
...it is also possible to rebuild specifi
cally.
...those have caused several problems histori
cally and tend to be poorly tested when the build system changes.
Creating Custom Events That Can Pass Data
your modification of this file is basi
cally just two macro
calls.
... 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.
...your event in order for your event to work you must do the following: create a scriptable interface
called nsidom{youreventname} inheriting from nsidomevent.
Process scripts
for example, if you
call the global frame message manager's loadframescript() function, then the script will be loaded separately into all open tabs.
... you can load a process script by accessing a parent process message manager and
calling its loadprocessscript() function.
...if you do, you must
call removedelayedprocessscript() when your extension is disabled or removed the message-passing apis are the same: sendasyncmessage() is available in both directions, while sendsyncmessage() is available from content to chrome only process scripts are system-privileged, and have access to the components object.
Tracking Protection
for example, if your site includes a
callback that runs when content from a tracking site is loaded, then the
callback will not execute.
... for example, you should not use google analytics in the following way: <a href="http://www.example.com" onclick="tracklink('http://www.example.com', event);"> visit example.com </a> <script> function tracklink(url,event) { event.preventdefault(); ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hit
callback': function() { document.location = url; } }); } </script> instead, you should account for the case when google analytics is missing by checking to see if the ga object has initialized: <a href="http://www.example.com" onclick="tracklink('http://www.example.com', event);"> visit example.com </a> <script> function tracklink(url,event) { event.preventdefault(); if (window.ga && ga.loaded) { ga('send', 'event', '...
...outbound', 'click', url, { 'transport': 'beacon', 'hit
callback': function() { document.location = url; } }); } else { document.location = url; } } </script> more information about this technique is available at google analytics, privacy, and event tracking.
HTMLIFrameElement.getMuted()
syntax there are two versions of this method, a
callback version: var request = instanceofhtmliframeelement.getmuted(); and a promise version: instanceofhtmliframeelement.getmuted().then(function(muted) { ...
... }); returns
callback version: a domrequest that represents the get muted request.
... example
callback version: var browser = document.queryselector('iframe'); var request = browser.getmuted(); request.onsuccess = function() { if(request.result) { console.log('the browser is muted.'); } else { console.log('the browser is unmuted.'); } } promise version: var browser = document.queryselector('iframe'); browser.getmuted().then(function(muted) { if(muted) { console.log('the b...
HTMLIFrameElement.getVolume()
syntax there are two versions of this method, a
callback version: var request = instanceofhtmliframeelement.getvolume(); and a promise version: instanceofhtmliframeelement.getvolume().then(function(volume) { ...
... }); returns
callback version: a domrequest that represents the get volume request.
... example
callback version: var browser = document.queryselector('iframe'); var request = browser.getvolume(); request.onsuccess = function() { console.log('the current browser volume is ' + request.result); } promise version: var browser = document.queryselector('iframe'); browser.getvolume().then(function(volume) { console.log('the current browser volume is ' + volume); }); specification not part of any specification.
mozbrowsershowmodalprompt
the mozbrowsershowmodalprompt event is fired when the content of a browser <iframe>
calls the window.alert(), window.confirm(), or window.prompt() methods.
... unblock() a function to be
called when the iframe is unblocked.
... note that if the embedder
calls preventdefault() on this event, the iframe is blocked until unblock() is
called.
mozbrowserusernameandpasswordrequired
the embedder is supposed to retrieve the necessary credentials, usually using a dialog or a database of username/passwords, and then
call authenticate() or cancel() as appropriate.
... authenticate() a function that is
called to enable the authentication to go ahead.
... cancel() a function that is
called to cancel the authentication.
Embedding the editor
editor needs to
call through one or more interfaces when communicating with the ui.
...this interface will be
called nsi????.
...
calling window.trytoclose) appropriately consult each editor for state.
How to get a stacktrace for a bug report
if you file a bug report in bugzilla about a crash you should include a stacktrace (
call stack) in your report.
... the mozilla crash reporter window should automati
cally come up after firefox crashes.
... if you want breakpad to leave the .dump and .extra files on your computer so that you can examine them lo
cally, then set the moz_crashreporter_no_delete_dump environment variable to 1.
Implementing Download Resuming
if the download gets interrupted, necko will
call the stream listener's onstoprequest method with a failure status.
...otherwise,
call resumeat with the desired start position, and the previously stored entity id.
...you may want to use nsisimplestreamlistener to simplify this task; to get progress notifications, you can implement nsiprogresseventsink and set an interface requester as the notification
callbacks of the channel that gives out such an event sink (this needs to be done before
calling asyncopen).
DownloadSummary
methods bindtolist() this method may be
called once to bind this object to a downloadlist.
... note: this method is already
called internally by the downloads.getsummary() function.
...the following methods may be defined: onsummarychanged: optional
called after any property of the summary has changed.
FxAccountsOAuthClient.jsm
oncomplete function gets
called when the firefox accounts oauth flow successfully completes.
...registers a webchannel listener and sets up a
callback if needed.
... parameters none teardown()
call this function to manually release all channels and
callbacks that are in use by this client.
JNI.jsm
if you would like to support versions before that, you can copy and paste the contents of the jsm file int jni stands for java native interface; this library allows
calling java code running in java virtual machines (jvms), etc.
...unlike c from js-ctypes, defining constants is not a manual magic number method in jni, it is declared the same way we define functions, except in jni they are
called fields.
...this is done by
calling .set for each element with the respective value in the avalsarray.
Deferred
note: this function is bound to its associated promise when promise.defer() is
called, and can be
called with any value of this.
... note:
calling this method with a pending promise as the avalue argument, and then
calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution.
... note: this function is bound to its associated promise when promise.defer() is
called, and can be
called with any value of this.
Deferred
note: this function is exactly same as promise constructor's resolve argument, and can be
called with any value of this.
... note:
calling this method with a pending promise as the avalue argument, and then
calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution.
... note: this function is exactly same as promise constructor's reject argument, and can be
called with any value of this.
WebChannel.jsm
method overview listen(function
callback); stoplistening(); send(object message, eventtarget target); attributes id string webchannel id methods listen() registers the
callback for messages on this channel.
... parameters
callback
callback function containing function(id, message, sendercontext) parameters.
... id - webchannel id of the incoming messages message - incoming message object sendercontext - incoming message context - this should be treated as an opaque object and passed to the .send() method stoplistening() resets the
callback for messages on this channel.
openLocationLastURL.jsm
if the user is not in private browsing mode, this automati
cally updates the value of the general.open_location.last_url preference.
... note: this module automati
cally handles private browsing mode for you.
...using the openlocationlasturl object to get or set the value of the open location edit box, simply read the value of, or set the value of, the openlocationlasturl.value field: var url = openlocationlasturl.value; openlocationlasturl.value = "http://www.mozilla.org/"; to reset the value of the edit box to the default (which is an empty string), you can
call the reset() method: method overview reset() methods reset the reset() method resets the saved url to the default, which is an empty string.
Localization content best practices
however, linguisti
cally these are different types of sentences and will be handled differently in other languages.
... don't hardcode characters typi
cally white spaces, commas, or other separators (":", "|").
... late-l10n: it's used by release-drivers to identify bugs, involving new strings, that will land late in the cycle, typi
cally after soft string freeze in firefox os.
Localizing with Pontoon
pontoon will automati
cally open that locale's project for you to get started.
...we
call all of these translation helpers and here's how each of them will help you as you translate strings: history displays previously suggested translations, including from other users.
...actually, it does that for you by automati
cally syncing with repositories on hourly basis.
Localizing without a specialized tool
this will automati
cally create an "x-testing" directory in your current directory (you should be in l10n-mozilla-1.9.2).
...you will use a tool
called compare-locales to do the comparison between your locale's files and the en-us reference.
...(strings in the dtd files are
called "entities".) "manage search engines..." can easily be found in the firefox browser ui by clicking on the drop-down arrow in the search box in the upper-right corner of your browser.
Localization formats
accidentally removes some html like </h1>, that localizer can break everything.) very hard to update automati
cally, if not impossible.
... can be hard to tell what has changed .lang files histori
cally, mozilla has used a gettext-like file to present content for localization.
... <h1><?php echo ___("getting started")?></h1> function ___($str) { return $array[$str]; } advantage to .lang simple work-flow allowing the web developer to place the file in svn and it can appear on the staging server .lang syntax is like simplified .po, which many localizers who are familiar with linux and other projects understand mozilla has a basic tool
called main.lang checker, which can show any untranslated files to the localizer no need to compile to .mo file so a localizer can see his/her changes more quickly creating simple diffs .lang files will be cached which will reduce any slowness effect disadvantage to .lang no plural forms no context for localizers unless you provide good comments no styling by localizers if it is needed may ...
Mozilla Style System
when script dynami
cally 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.
... most
callers who interact with the style system do so using the style structs.
...thus, typical
calling code looks like this: if (aframe->getstyledisplay()->mopacity < 1.0f) return pr_true; or like this: const nsstyleposition *stylepos = aframe->getstyleposition(); if (stylepos->mwidth.getunit() == estyleunit_coord) { nscoord w = stylepos->mwidth.getcoordvalue(); ...
Activity Monitor, Battery Status Menu and top
(apple support documentation specifi
cally recommends it for troubleshooting battery life problems.) unfortunately "energy impact" is not a good measure for either users or software developers and it should be avoided.
... systemstats is a program that runs continuously and periodi
cally measures, among other things, cpu usage and idle wakeups for each running process.
... it will show periodi
cally-updating data like the following.
BloatView
xpcom_mem_bloat_log if set, this causes a bloat log to be printed on program exit, and each time nstracerefcnt::dumpstatistics is
called.
...if they aren't, then you're not using the ns_impl_addref and ns_impl_release (or ns_impl_isupports which
calls them) for xpcom objects, or moz_count_ctor and moz_count_dtor for non-xpcom objects.
... so, the xpcom_mem_log_classes environment variable should be set to the name of the class from the bloatview table: xpcom_mem_log_classes=myclass mach mochitest [options] multiple class names can be specified by setting xpcom_mem_log_classes to a comma-separated list of names: xpcom_mem_log_classes=myclass,myotherclass,deliberatelyleakedclass mach mochitest [options] test harness scripts typi
cally accept a --setenv option for specifying environment variables, which may be more convenient in some cases: mach mochitest --setenv=xpcom_mem_log_classes=myclass [options] for getting allocation stacks in automation, you can add the appropriate --setenv options to the test configurations for the platforms you're interested in.
GC and CC logs
these logs can either be manually or automati
cally generated, and they can be generated in both debug and non-debug builds.
... to find out why an object is being kept alive, the relevant scripts are find_roots.py and parse_cc_graph.py (which is
called by find_roots.py).
...
calling find_roots.py on a cc log with a specific object or kind of object will produce paths from rooting objects to the specified objects.
Measuring performance using the PerfMeasurement.jsm code module
now we want to benchmark a function that is pretty fast (but not fast enough), so we run it several thousand times: for (let i = 0; i < 10000; i++) { set_up_some_state(); monitor.start(); code_to_be_benchmarked(); monitor.stop(); clean_up_afterward(); } we
call the perfmeasurement object's start() method when we want to start recording, and stop() when we want to stop recording.
...since we enable monitoring immediately before
calling code_to_be_benchmarked(), and disable it as soon as it returns, the code in set_up_some_state() and clean_up_afterward() is not measured.
... the monitor object automati
cally accumulates counts over start/stop cycles (that is, it doesn't automati
cally zero the counters each time you start recording).
Profiling with the Gecko Profiler and Local Symbols on Windows
the profiler automati
cally reads symbols from the pdb files that are generated during the build process.
...unfortunately, 32 bit is still the default when building firefox lo
cally.
... if you're building a beta or release channel version, and you want proper c++
callstacks in your profiles, add ac_add_options --enable-profiling to your firefox .mozconfig file.
browser.dom.window.dump.file
browser.dom.window.dump.file redirects the ouput of window.dump()
calls to a file whose address is specified in this preference if browser.dom.window.dump.enabled is set to true.
... type:string default value:none exists by default: no application support: gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) status: active; last updated 2012-03-18 introduction: pushed to nightly on 2009-04-24 bugs: bug 489938 values the value holds the file system path for the file in which the content of the window.dump()
calls get written, e.g.
... the line breaks have to be in the argument of the dump function, else successive dump
calls will get logged into the same line.
McCoy
mozilla
calls mccoy a "simple system" which is a clear sign that something probably is not working, and indeed, is not.
...applications periodi
cally look for and install updates to their add-ons.
...specifi
cally, it focuses on the process of digitally signing update manifests so the applications can verify the integrity of a manifest retrieved over normally insecure channels.
About NSPR
the java-like facilities include monitor reentrancy, implicit and tightly bound notification capabilities with the ability to associate the synchronization objects dynami
cally.
... memory management nspr provides api to perform the basic malloc,
calloc, realloc and free functions.
... depending on the platform, the functions may be implemented almost entirely in the nspr runtime or simply shims that
call immediately into the host operating system's offerings.
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.
...to enable all log module
calls to pr_log, set the variable as follows: set nspr_log_modules=all:5 timestamp including timestamp results in a timestamp of the form "2015-01-15 21:24:26.049906 utc - " prefixing every logged line.
PRThreadScope
syntax #include <prthread.h> typedef enum prthreadscope { pr_local_thread, pr_global_thread pr_global_bound_thread } prthreadscope; enumerators pr_local_thread a local thread, scheduled lo
cally by nspr within the process.
... pr_global_bound_thread a global bound (kernel) thread, scheduled by the host os description an enumerator of type prthreadscope specifies how a thread is scheduled: either lo
cally by nspr within the process (a local thread) or globally by the host (a global thread).
...to find the scope of the thread,
call pr_getthreadscope.
PR_Assert
file the file name of the compilation unit containing this function
call.
... ln the line number within the specified file of this function
call.
... normally an application would not
call this function directly; use pr_assert instead.
PR_CNotifyAll
the
calling thread must be in the monitor at the time pr_cnotifyall is
called.
... returns pr_success indicates that the referenced monitor was located and the
calling thread was in the monitor.
... pr_failure indicates that the referenced monitor could not be located or that the
calling thread was not in the monitor description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cnotifyall notifies all threads waiting for the monitor's state to change.
PR_CWait
pr_failure indicates either that the monitor could not be located in the cache or that the monitor was located and the
calling thread was not the thread that held the monitor's mutex.
...while the thread is waiting, it exits the monitor (just as if it had
called pr_cexitmonitor as many times as it had
called pr_centermonitor).
...when the thread resumes execution, it is the
caller's responsibility to test the state of the monitored data to determine the appropriate action.
PR_Cleanup
if the
calling thread of this function is not the primordial thread, pr_failure.
... description pr_cleanup must be
called by the primordial thread near the end of the main function.
...it does so by blocking the
caller, if and only if it is the primordial thread, until all user threads have terminated.
PR_EnumerateHostEnt
on output, this structure is filled in by the runtime if the result of the
call is greater than 0.
... returns the function returns one of the following values: if successful, the function returns the value you should specify in the enumindex parameter for the next
call of the enumerator.
...you can retrieve the reason for the failure by
calling pr_geterror.
PR_FindSymbolAndLibrary
this location must be pre-allocated by the
caller.
...the location must be pre-allocated by the
caller.
...this function is equivalent to
calling first pr_loadlibrary, then pr_findsymbol.
PR_GMTParameters
note: since this function requires gmt as input, its primary use is as "filler" for cases in which you need a do-nothing
callback.
... description this is a frequently-used time parameter
callback function.
... you don't normally
call it directly; instead, you pass it as a parameter to pr_explodetime() or pr_normalizetime().
PR_GetLibraryName
the constructed path name refers to the actual dynami
cally loaded library.
... it is suitable for use in the pr_loadlibrary
call.
...storage for the result is allocated by the runtime and becomes the responsibility of the
caller.
PR_GetRandomNoise
syntax #include <prrng.h> nspr_api(prsize) pr_getrandomnoise( void *buf, prsize size ); parameters the function has these parameters: buf a pointer to a
caller-supplied buffer to contain the generated random number.
...a return value of zero means that pr_getrandomnoise is not implemented on this platform, or there is no available noise to be returned at the time of the
call.
...this implies that the random value provided may not be, by itself, cryptographi
cally secure.
PR_Initialize
in addition to establishing the sequence of operations, pr_initialize implicitly
calls pr_cleanup on exiting the primordial function.
... description pr_initialize initializes the nspr runtime and places nspr between the
caller and the runtime library.
... pr_initialize does not return to its
caller until all user threads have terminated.
PR_NotifyAll
the monitor object referenced must be one for which the
calling thread currently holds the lock.
... description a
call to pr_notifyall causes all of the threads waiting on the monitor to be scheduled to be promoted to a ready state.
...the expense of scheduling multiple threads increases dramati
cally as the number of threads increases.
PR_NotifyAllCondVar
if unsuccessful (for example, if the
caller has not locked the lock associated with the condition variable), pr_failure.
... description the
calling thread must hold the lock that protects the condition, as well as the invariants that are tightly bound to the condition.
... a
call to pr_notifyallcondvar causes all of the threads waiting on the specified condition variable to be promoted to a ready state.
PR_OpenDir
returns if the directory is successfully opened, a prdir object is dynami
cally allocated and the function returns a pointer to it.
... description pr_opendir opens the directory specified by the pathname name and returns a pointer to a directory stream (a prdir object) that can be passed to subsequent pr_readdir
calls to get the directory entries (files and subdirectories) in the directory.
... the prdir pointer should eventually be closed by a
call to pr_closedir.
PR_Sleep
returns
calling pr_sleep with a parameter equivalent to pr_interval_no_timeout is an error and results in a pr_failure error.
...
calling pr_sleep with the value of ticks set to pr_interval_no_wait simply surrenders the processor to ready threads of the same priority.
... all other values of ticks cause pr_sleep to block the
calling thread for the specified interval.
PR_Wait
the monitor object referenced must be one for which the
calling thread currently holds the lock.
... returns the function returns one of the following values: pr_success means the thread is being resumed from the pr_wait
call either because it was explicitly notified or because the time specified by the parameter ticks has expired.
... description a
call to pr_wait causes the thread to release the monitor's lock, just as if it had
called pr_exitmonitor as many times as it had
called pr_entermonitor.
Threads
it is the
caller's responsibility to ensure that the thread is valid.
... pr_jointhread blocks the
calling thread until a specified thread terminates.
...if the
call is successful, every thread in the same process is capable of associating private data with the new index.
NSS 3.14 release notes
support for application-defined certificate chain validation
callback when using libpkix to better support per-application security policies, a new
callback has been added for applications that use libpkix to verify certificates.
... applications may use this
callback to inform libpkix whether or not candidate certificate chains meet application-specific security policies, allowing libpkix to continue discovering certificate paths until it can find a chain that satisfies the policies.
... the following types have been added in nss 3.14 certchainverify
callback (in certt.h) certchainverify
callbackfunc (in certt.h) cert_pi_chainverify
callback, a new option for certvalparamintype (in certt.h) a new error code: sec_error_application_
callback_error (in secerr.h) new for pkcs #11 pkcs #11 mechanisms: ckm_aes_cts ckm_aes_ctr ckm_aes_gcm (see warnings against using c_encryptupdate/c_decryptupdate above) ckm_sha224_key_derivation ckm_sha256_key_derivation ckm_sha384_key_derivation ckm_sha512_key_derivation changes in nss 3.14 bug 333601 - performance enhancements for intel macs when building for intel macs, nss will now take ...
NSS 3.15.2 release notes
specifi
cally, 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.
... bug 884178 - add pk11_cipherfinal macro bugs fixed in nss 3.15.2 bug 734007 - sizeof() used incorrectly bug 900971 - nssutil_readsecmoddb() leaks memory bug 681839 - allow ssl_handshakenegotiatedextension to be
called before the handshake is finished.
...it is no longer necessary to
call nss_setdomesticpolicy because all cipher suites are now allowed by default.
NSS 3.15 release notes
tls client applications may enable this via a
call to ssl_optionsetdefault(ssl_enable_ocsp_stapling, pr_true); added function secitem_reallocitemv2.
...secitem_reallocitemv2 better matches
caller expectations, in that it updates item->len on allocation.
... applications that use ssl_authcertificatehook to override the default handler should add appropriate
calls to ssl_peerstapledocspresponse and cert_cacheocspresponsefromsidechannel.
NSS 3.24 release notes
ssl_configservercert automati
cally determines the certificate type from the certificate and private key.
... the
caller is no longer required to use sslkeatype explicitly to select a "slot" into which the certificate is configured (which incorrectly identifies a key agreement type rather than a certificate).
...rather than declaring a plarenapool pointer and
calling port_newarena/port_freearena to allocate or free an instance on the heap, declare a portcheaparenapool on the stack and use port_initcheaparena/port_destroycheaparena to initialize and destroy it.
NSS sources building testing
any c function that isn't contained in .def files is strictly for private use within nss, and applications and test tools are not allowed to
call them.
...will be a name dynami
cally derived from your system's architecture.
...on machines that are configured with a hostname that has been registered in your network's dns, this should work automati
cally.
nss tech note2
only display the sequence of pkcs #11
calls.
...display the sequence of pkcs #11
calls, and the parameters given to them.
...the number of
calls to each pkcs #11 function will be counted, and the time spent in each function as well.
nss tech note4
there is a long list of pre-defined oids, and new ones can be added dynami
cally by an application.
... this uses pr_alloc to allocate buffer for the decoded value, the
caller should free up the storage allocated in value->data.
... this uses pr_alloc to allocate buffer for the decoded value, the
caller should free up the storage allocated in value->data.
FC_DecryptDigestUpdate
after
calling both fc_decryptinit and fc_digestinit to set up the operations this function may be
called multiple times.
... the operation is finished by
calls to fc_digestfinal and fc_decryptfinal.
... a user must log into the token (to assume the nss user role) before
calling fc_decryptdigestupdate.
FC_DecryptVerifyUpdate
after
calling both fc_decryptinit and fc_verifyinit to set up the operations this function may be
called multiple times.
... the operation is finished by
calls to fc_decryptfinal and fc_verifyfinal.
... a user must log into the token (to assume the nss user role) before
calling fc_decryptverifyupdate.
FC_DigestEncryptUpdate
after
calling both fc_digestinit and fc_encryptinit to set up the operations this function may be
called multiple times.
... the operation is finished by
calls to fc_digestfinal and fc_encryptfinal in that order.
... a user must log into the token (to assume the nss user role) before
calling fc_digestencryptupdate.
FC_OpenSession
flags [in] papplication notify [in] pointer to a notification
callback function.
...the nss cryptographic module currently doesn't
call the surrender
callback function notify.
... (see pkcs #11 v2.20 section 11.17.1.) a user may
call fc_opensession without logging into the token (to assume the nss user role).
FC_SignEncryptUpdate
after
calling both fc_signinit and fc_encryptinit to set up the operations this function may be
called multiple times.
... the operation is finished by
calls to fc_signfinal and fc_encryptfinal.
... a user must log into the token (to assume the nss user role) before
calling fc_signencryptupdate.
NSC_InitToken
specifi
cally, nsc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs.
... the "reset password" button of the mozilla application suite and seamonkey (in preferences->privacy & security->master passwords)
calls nsc_inittoken().
... the "-t" (token reset) command of certutil
calls nsc_inittoken().
NSS tools : crlutil
-i crl-import-file specify the file which contains the crl to import -f password-file specify a file that will automati
cally supply the password to include in a certificate or to access a certificate database.
... issueraltnames non-critical name-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names * add crl number extension: the crl number is a non-critical crl extension which conveys a monotoni
cally increasing sequence number for a given crl scope and crl issuer.
... for information specifi
cally about nss, the nss project wiki is located at [2]http://www.mozilla.org/projects/security/pki/nss/.
OLD SSL Reference
initialization initializing caches configuration communication functions used by
callbacks cleanup chapter 2 getting started with ssl this chapter describes how to set up your environment, including certificate and key databases, to run the nss sample code.
...nfiguration ssl_importfd ssl_optionset ssl_optionget ssl_cipherprefset ssl_cipherprefget ssl_configsecureserver ssl_seturl ssl_setpkcs11pinarg
callback configuration ssl_authcertificatehook ssl_authcertificate ssl_badcerthook ssl_getclientauthdatahook nss_getclientauthdata ssl_handshake
callback ssl communication functions ...
... ssl_invalidatesession ssl_datapending ssl_securitystatus ssl_getsessionid ssl_setsockpeerid ssl functions used by
callbacks ssl_peercertificate ssl_revealurl ssl_revealpinarg ssl handshake functions ssl_forcehandshake ssl_rehandshake ssl_resethandshake nss shutdown function nss_shutdown deprecated functions ssl_enabledefault ssl_enable ssl_enablecipher ssl_setpolicy ...
gtstd.html
a pkcs #11 module (also
called a cryptographic module) manages cryptographic services such as encryption and decryption via the pkcs #11 interface.
...netscape software uses a file
called secmod.db to keep track of the modules available.
... the communicator certificate db token handles all communication with the certificate and key database files (
called certx.db and keyx.db, respectively, where x is a version number) that store certificates and keys.
ssltyp.html
when you
call cert_destroycertificate, the function decrements the reference count and, if the reference count reaches zero as a result, frees the memory.
...when you
call seckey_destroyprivatekey, the function both frees the memory and sets all the bits to zero.
...to find out why,
call pr_geterror.
NSS Tools certutil
-f password-file specify a file that will automati
cally supply the password to include in a certificate or to access a certificate database.
...unless specified otherwise the default token is an internal slot (specifi
cally, internal slot 2).
...when this argument is used, the default three-month period is automati
cally added to any value given in thevalid-month argument.
NSS tools : crlutil
-i crl-import-file specify the file which contains the crl to import -f password-file specify a file that will automati
cally supply the password to include in a certificate or to access a certificate database.
... issueraltnames non-critical name-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names * add crl number extension: the crl number is a non-critical crl extension which conveys a monotoni
cally increasing sequence number for a given crl scope and crl issuer.
... for information specifi
cally about nss, the nss project wiki is located at [2]http://www.mozilla.org/projects/security/pki/nss/.
Rhino optimization
another benefit of the interpreted mode is that the interpreter performs tail-
call elimination of recursive functions.
...function
call targets are speculatively pre-cached (based on the name used in the source) so that dispatching can be direct, pending runtime confirmation of the actual target.
... note some language features (indirect
calls to eval, use of the arguments property of function objects) were previously not supported in higher optimization levels.
The JavaScript Runtime
string java.lang.charsequence (java.lang.string or org.mozilla.javascript.consstring) object org.mozilla.javascript.scriptable in addition, ecma refers to objects that implement [[
call]] as functions.
... since javascript is a dynami
cally typed language, the static java type of a javascript value is java.lang.object.
...it is the responsibility of the
caller to invoke the appropriate overloaded form.
Rebranding SpiderMonkey (1.8.5)
if you have failed to insert your brand name in any of the previous steps where it is
called for, you must delete this build directory and restart this process from the beginning.
... && chmod 644 $brand.pc "scroll down" a few lines until you see these lines: install:: $(pkg_config_files) @echo pkg_config_file: $(pkg_config_files) those two lines should be modified to read back: install:: $brand.pc @echo pkg_config_file: $brand.pc note: while it is possible to automate the manual editing process, this has been discouraged due to the fact that these files are automati
cally generated and very little constant data can be depended upon.
...you may now perform the build and installation of your custom branded spidermonkey library: make note: depending on your system you may need administrative rights to perform the installation: make install the following information isn't techni
cally needed for using your library but it will help other applications use your library.
Creating JavaScript jstest reftests
jstests has a special requirement: the
call to reportcompare in every jstest is required by the test harness.
...the web has written this kind of if-statement: if (typeof gc === 'function') { var arr = []; arr[10000] = 'item'; gc(); asserteq(arr[10000], 'item', 'gc must not wipe out sparse array elements'); } else { print('test skipped: no gc function'); } reportcompare(0, 0, 'ok'); handling abnormal test terminations some tests can terminate abnormally even though the test has techni
cally passed.
...multiple
calls to expectexitcode will tell the post-processing scripts that the test actually passed if any of the exit codes are found when the test terminates.
GC Rooting Guide
the implementation should trace all the gc things contained in the object by
calling js::traceedge.
...for regular js::nativeobjects, this is normally done by storing them in slots, which are automati
cally traced by the gc.
...the usual way is to define a void trace(jstracer* trc, const char* name) method on the class -- which is already enough be able to create a js::rooted<yourstruct> on the stack -- and then arrange for it to be
called during tracing.
Bytecodes
bytecodes can reference atoms and objects (typi
cally by array index) which are also contained in the jsscript data structure.
...the space for a single javascript value is
called a "slot", so the categories are: argument slots: holds the actual arguments passed to the current frame.
... there are also some slots reserved for dedicated functionality, holding values like this and the
callee / return value.
JS::GetFirstArgumentAsTypeHint
syntax bool js::getfirstargumentastypehint(jscontext* cx,
callargs args, jstype *result); name type description cx jscontext * the context in which to define functions.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
... fs
callargs the arguments of the function
call.
JS::NewFunctionFromSpec
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... behavior handleid the result of a successful
call to propertyspecnametopermanentid(cx, fs->name, &id).
... id is the result of a successful
call to propertyspecnametopermanentid(cx, fs->name, &id).
JS::OrdinaryToPrimitive
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... most users should not
call this -- use js::tonumber, js::toboolean, or js::tostring instead.
... this should only be
called from custom convert hooks.
JSAutoCompartment
this article covers features introduced in spidermonkey 24 raii helper to enter a different compartment on the given context and automati
cally leave it once the jsautocompartment instance gets out of scope.
... syntax jsautocompartment(jscontext *cx, jsobject *target); jsautocompartment(jscontext *cx, jsscript *target); name type description cx jscontext * the context on which a cross-compartment
call is needed.
...jsautocompartment guarantees that by automati
cally entering the given compartment and leaving it upon getting out of scope: void foo(jscontext *cx, jobject *obj) { // in some compartment 'c' { jsautocompartment ac(cx, obj); // constructor enters // in the compartment of 'obj' } // destructor leaves // back in compartment 'c' } see also mxr id search for jsautocompartment bug 86...
JSExtendedClass
}; name type description base jsclass the basic class information and
callbacks for this class.
... description to implement a custom class that uses any of the jsextendedclass
callbacks: create a jsextendedclass and populate both the base fields and the extended fields.
...jsclass and jsextendedclass structs should usually be global, and in this case the compiler automati
cally initializes these fields to null.
JSFunction
as a result, some apis (such as js_
callfunction) that operate on jsfunctions do not work properly with closures.
...instead of using js_
callfunction, for example, it must
call js_
callfunctionvalue.
... function objects created by
calling js_newfunction have two reserved slots for the application's use.
JSHasInstanceOp
on success, the
callback stores the result of the type check in *bp.
... description jshasinstanceop is
called to check whether v is an instance of obj.
... jsclass hooks jsclass offers the following hook: the jsclass.hasinstance
callback implements js_hasinstance and the javascript instanceof keyword.
JSIteratorOp
this article covers features introduced in spidermonkey 1.8
callback for creating iterators.
... description the javascript engine
calls the jsextendedclass.iteratorobject
callback to create an iterator object for a given object.
... the
callback should return an iterator object or null if an error or exception occurred on cx.
JSMarkOp
jsmarkop is the type of the jsclass.mark
callback in spidermonkey 1.7 and earlier.
... description
call js_markgcthing for each gc thing directly reachable from obj.
... jsclass hooks jsclass offers the following hook: the javascript engine
calls the jsclass.mark
callback during the mark phase of garbage collection.
JSObjectOps.getProperty
jsobjectops.getproperty, setproperty, and deleteproperty are high-level
callbacks that implement object property accesses.
... each of these
callbacks is responsible for everything involved with an individual property access operation, including: any locking necessary for thread safety; security checks; finding the property, including walking the prototype chain if needed;
calling the lower-level jsclass hooks;
calling getters or setters; and actually getting, setting, or deleting the property once it is found.
... contrast jsclass.getproperty, jsclass.setproperty, and jsclass.delproperty, which are hooks
called during property accesses and don't have to implement any of that.
JSObjectOps.setProto
the jsobjectops.setproto and setparent
callbacks implement the js_setprototype and js_setparent functions.
... these
callbacks share the same type, jssetobjectslotop.
... slot uint32 the index of the slot being modified: jsslot_proto for the jsobjectops.setproto
callback, and jsslot_parent for the jsobjectops.setparent
callback.
JS_ConstructObject
the preferred alternative is to save a copy of the constructor function for the class, then to
call it using js_new.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
...the
caller does not need to ensure that the array elements are rooted.
JS_ConvertArgumentsVA
syntax bool js_convertargumentsva(jscontext *cx, const js::
callargs &args, const char *format, va_list ap); bool js_convertargumentsva(jscontext *cx, unsigned argc, jsval *argv, const char *format, va_list ap); name type description cx jscontext * pointer to a js context from which to derive runtime information.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
... args const js::
callargs & reference to the arguments to convert.
JS_DefineConstDoubles
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... obsolete from jsapi 35 each property is automati
cally assigned attributes as specified in the flags field of the jsconstdoublespec/jsconstintegerspec structure pointed to by cds/cis.
... if flags is set to 0, the attributes for the property are automati
cally set to jsprop_permanent | jsprop_readonly.
JS_DefineFunctions
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... description js_definefunctions creates zero or more functions and makes them properties (methods) of a specified object, obj, as if by
calling js_definefunction repeatedly.
... 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_DefineObject
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... js_defineobject does not
call clasp->constructor.
... initialization of the new object is up to the
caller.
JS_EncodeCharacters
the
caller is responsible for allocating and freeing this buffer.
...if spidermonkey was built with js_c_strings_are_utf8 defined or js_setcstringsareutf8 was
called, the string is converted to utf-8.
... to calculate the number of bytes needed,
call js_encodecharacters twice, like this: /* determine how many bytes to allocate.
JS_EncodeString
in a js_threadsafe build, the
caller must be in a request on this jscontext..
... the array returned by js_encodestring on success is allocated as though by a
call to js_malloc.
... the
caller may modify it and is responsible for freeing it.
JS_Enumerate
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...this
calls obj's jsclass.enumerate hook.
...but, for example, if an application
calls back into javascript while it is looping over the property ids in the jsidarray, the script could delete properties from obj.
JS_EnumerateDiagnosticMemoryRegions
syntax void js_enumeratediagnosticmemoryregions(jsenumeratediagnosticmemory
callback
callback); name type description
callback jsenumeratediagnosticmemory
callback pointer to the new
callback function to use.
...
callback syntax typedef bool (* jsenumeratediagnosticmemory
callback)(void *ptr, size_t length); name type description ptr void * pointer to the allocated memory.
... see also mxr id search for js_enumeratediagnosticmemoryregions mxr id search for jsenumeratediagnosticmemory
callback bug 662646 ...
JS_GC
when your scripts create many objects, you may want to
call js_gc directly in your code, particularly when a script terminates or when the application has idle time.
... to perform garbage collection only if needed,
call js_maybegc instead.
... use js_setgc
callback to add hooks that are
called during garbage collection.
JS_GetInstancePrivate
syntax void * js_getinstanceprivate(jscontext *cx, js::handle<jsobject*> obj, const jsclass *clasp, js::
callargs *args); // added in jsapi 32 void * js_getinstanceprivate(jscontext *cx, js::handle<jsobject*> obj, const jsclass *clasp, jsval *argv); // obsolete since jsapi 32 name type description cx jscontext * a context.
... args js::
callargs * optional argument, used for error reporting.
...obsolete since jsapi 32 this must be one of the following: an argv pointer created by the javascript engine and passed to a jsnative
callback; js_argv(cx, vp) where vp is a pointer created by the engine and passed to a jsfastnative
callback; or null.
JS_GetParent
it may be a
call, with, or block object representing the function's dynamic scope, or it may be the global object.
...this is often the case for the global object, which is typi
cally the first object created in a new context.
...but if an object's parent is an internal-use-only object (that is, a special
call, with, or block object), js_getparent simply returns it, but obj.__parent__ === null.
JS_IsConstructing_PossiblyWithGivenThisObject
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... vp const jsval * maybethis jsobject ** description in the case of a constructor
called from js_constructobject and js_initclass where the class has the jsclass_construct_prototype flag set, spidermonkey passes the constructor a non-standard this object.
... jsbool foo_native(jscontext *cx, unsigned int argc, jsval *vp) { jsobject *maybethis; if (js_isconstructing_possiblywithgiventhisobject(cx, vp, &maybethis)) { // native
called as a constructor if (maybethis) // native
called as a constructor with maybethis as 'this' } else { // native
called as function, maybethis is still uninitialized } } note: a spidermonkey embedding does not need to use this query unless the embedding uses js_constructobject(), js_initclass() and jsclass_construct_prototype as described above.
JS_IsNativeFunction
syntax bool js_isnativefunction(jsobject *funobj, jsnative
call); name type description funobj jsobject * the function object to examine.
...
call jsnative the native function to compare.
... description js_isnativefunction determines if a specified function object, funobj equals a specified native function,
call.
JS_LookupElement
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... note: in the javascript language, numeric properties (also
called "elements") are just ordinary properties whose names are numeric strings.
...so any
call to js_lookupelement is equivalent to a
call to js_lookupproperty passing a numeric string for the name.
JS_MakeStringImmutable
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...applications must
call js_makestringimmutable before sharing a jsstring among threads by storing it in a c/c++ variable, field, or array element that another thread can read.
... (when an application shares a string by storing it in a javascript object that another thread can read, the javascript engine automati
cally makes the string thread-safe.) after a successful
call to js_makestringimmutable, subsequent
calls to js_getstringcharsz on the same string are guaranteed to succeed, and subsequent
calls to js_getstringchars on the same string are guaranteed to return a null-terminated string.
JS_NewArrayObject
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...otherwise it reports an error as though by
calling js_reportoutofmemory and returns null.
...the new array has the specified length, but it doesn't have any elements.) it is often better to
call js_newarrayobject(cx, 0, null), store the returned object in a gc root, and then populate its elements with js_setelement or js_defineelement.
JS_RemoveExternalStringFinalizer
as with js_addexternalstringfinalizer, there is a threading restriction if you compile the engine js_threadsafe: this function may be
called for a given finalizer pointer on only one thread; different threads may
call to remove distinct finalizers safely.
... you must ensure that all strings with finalizer's type have been collected before
calling this function.
... otherwise, string data will be leaked by the gc, for want of a finalizer to
call.
JS_ResolveStandardClass
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... this api can be
called directly from a global object class's resolve op, to define standard classes lazily.
... the class's enumerate op should
call js_enumeratestandardclasses(cx, obj), to define eagerly during for...in loops any classes not yet resolved lazily.
JS_RestoreExceptionState
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...if any exception was pending when js_saveexceptionstate was
called, the same exception will be set to pend for the current context.
... if no exceptions were pending when
calling js_saveexceptionstate, any pending exception for the context will likewise be cleared.
JS_SaveFrameChain
description these two functions are used to set aside cx's
call stack while that stack is inactive.
... after a
call to js_saveframechain, it looks as if there is no code running on cx.
... before
calling js_restoreframechain, cx's
call stack must be balanced and all nested
calls to js_saveframechain must have had matching js_restoreframechain
calls.
JS_SetExtraGCRoots
callback syntax typedef void jstracedataop (jstracer *trc, void *data); argument meaning trc tracing data, to be passed through to js_
calltracer.
...this is the data value that was passed to js_setextragcroots when this
callback function was installed.
...
callback description generic trace operation that
calls js_
calltracer on additional traceable things.
JS_SetGlobalObject
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...this means that global objects are automati
cally protected from garbage collection, as are any values reachable from their properties.
...applications typi
cally set a context's global object using js_initstandardclasses instead.
JS_SetParent
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...applications that use spidermonkey's security features typi
cally use the parent relation to determine both (a) what security principals are attached to the currently executing script; and (b) what security principals are attached to the object being accessed.
...js_setparent has no way to check that this is the case, but nonetheless, applications must not
call js_setparent on an object that has already been exposed to a script.
JS_ValueToFunction
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...that includes js_
callfunction() and js_getfunctionobject().
... the object's jsobjectops.defaultvalue method is
called with hint=jstype_function.) js_valuetofunction returns a pointer to the converted function.
JS_ValueToObject
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...if v is a native javascript object, this
calls the object's valueof method, if any.
...(implementation note: the object's jsobjectops.defaultvalue method is
called with hint=jstype_object.) the resulting object is subject to garbage collection unless the variable *objp is protected by a local root scope, an object property, or the js_addroot function.
Property attributes
if the inherited property is shared, the setter is
called instead.
...added in spidermonkey 17 mxr id search for jsfun_stub_gsops jsfun_constructor native that can be
called as a constructor.
...added in spidermonkey 38 mxr id search for jsprop_redefine_nonconfigurable jsprop_resolving resolve hooks and enumerate hooks must pass this flag when
calling js_define* apis to reify lazily-defined properties.
SpiderMonkey 1.8.8
many jsapi types, functions, and
callback signatures have changed, though most of them still have the same names and do the same things.
...jsclass
callback changes many of the jsclass
callbacks such as jsresolveop, jsenumerateop and jspropertyop, have a type change on their arguments to jshandleobject, jshandleid, jshandlemutableobject etc.
... atleast for the c api this wraps an extra pointer around these objects, so you would cast the argument to jsobject**, in the
callback function.
SpiderMonkey 17
many jsapi types, functions, and
callback signatures have changed, though most of them still have the same names and do the same things.
...jsclass
callback changes many of the jsclass
callbacks such as jsresolveop, jsenumerateop and jspropertyop, have a type change on their arguments to jshandleobject, jshandleid, jshandlemutableobject etc.
... atleast for the c api this wraps an extra pointer around these objects, so you would cast the argument to jsobject**, in the
callback function.
Exploitable crashes
this is typi
cally located right above the stack trace.
... other tools apple has a tool
called "crashwrangler" that are still being maintained as of 2012.
...microsoft released a debugger extension tool in 2009
called "!exploitable".
Signing Mozilla apps for Mac OS X
the codesign tool apple provides a tool
called codesign; this command-line application is used to add a signature to an application bundle.
...once the application has been signed, the signature of an application bundle can be validated by
calling: codesign -vvvv application.app where application.app is the application bundle you wish to validate.
...if you don't provide one, codesign will automati
cally generate it.
Gecko states
state_invisible the object is programmati
cally hidden.
... for example, menu itmes are programmati
cally hidden until a user activates the menu.
...a speech-based accessibility aid does not announce information when an object with this state has the focus because the object automati
cally announces information.
Manipulating bookmarks using Places
var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var newbkmkid = bmsvc.insertbookmark(newfolderid, uri, bmsvc.default_index, ""); this example instantiates the nsiioservice and uses it to create an nsiuri referring to the google web site, then
calls nsinavbookmarksservice.insertbookmark() to create a new bookmark to google, placing it at the end of the bookmarks folder referenced by newbkmkid.
... the item uri similarly, you can obtain the uri corresponding to a given bookmark item by
calling the nsinavbookmarksservice.getbookmarkuri() method.
...anged: function(abookmarkid, aproperty, aisannotationproperty, avalue) { myextension.dosomething(); }, onitemvisited: function(abookmarkid, avisitid, time) {}, onitemmoved: function(aitemid, aoldparent, aoldindex, anewparent, anewindex) {}, queryinterface: xpcomutils.generateqi([components.interfaces.nsinavbookmarkobserver]) }; // an extension var myextension = { // this function is
called when my add-on is loaded onload: function() { bmsvc.addobserver(myext_bookmarklistener, false); }, // this function is
called when my add-on is unloaded onunload: function() { bmsvc.removeobserver(myext_bookmarklistener); }, dosomething: function() { alert("did something."); } }; see also nsinavbookmarksservice nsinavbookmarkobserver places using xpcom without ...
extIApplication
method overview boolean quit() boolean restart() void getextensions(extiextensions
callback a
callback) attributes the following interfaces are available to all applications: attribute type description id readonly attribute astring the id of the application.
... getextensions(a
callback)
calls a
callback with the list of installed extensions.
... void getextensions(extiextensions
callback a
callback) return value none.
XPCOM glue
this is typi
cally done using gre_getgrepathwithproperties.
... then, the code must
call xpcomgluestartup, which will dynami
cally link against the xpcom runtime.
... embedders using the standalone glue typi
cally also need to avoid linking against nspr as well.
How to build an XPCOM component in JavaScript
xpcom uses a dialect of idl to define interfaces,
called xpidl.
... 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 automati
cally generate the typelib.
...you skipped the sections "defining the interface" and "compiling the typelib" above, you uncommented the "wrappedjsobject" line in the class constructor, and you removed the "[components.interfaces.nsihelloworld]" argument for the
call to xpcomutils.generateqi() in queryinterface, then you can access your component like this: try { var mycomponent = components.classes['@dietrich.ganx4.com/helloworld;1'] .getservice().wrappedjsobject; alert(mycomponent.hello()); } catch (anerror) { dump("error: " + anerror); } for more information about wrappedjsobject, see here.
Receiving startup notifications
the important thing to note is that now instead of registering with the category manager programmati
cally as was done in the past, you add lines to your chrome.manifest to let the application handle it for you.
... registering with the category manager to register with the category manager, simply
call its nsicategorymanager.addcategoryentry() method: categorymanager->addcategoryentry(appstartup_category, "mycomponentname", "contract-id", pr_true, pr_true, getter_copies(previous)); this causes your component to be instantiated using nsicomponentmanager.createi...
...what happens next once you've registered with the category manager, at mozilla startup time (or when the embedding application's ns_initembedding() function is
called), the appstartupnotifier component is instantiated, and its observe() method is
called; this in turn enumerates all components in the app-startup category and sends them the appropriate notifications.
IAccessibleEditableText
1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) this interface is typi
cally used in conjunction with the iaccessibletext interface and complements that interface with the additional capability of clipboard operations.
...if endoffset is lower than startoffset, the result is the same as a
call with the two arguments exchanged.
...this method is equivalent to
calling first deletetext() with the two indices and then
calling inserttext() with the replacement text at the start index.
amIWebInstaller
irefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview boolean installaddonsfromwebpage(in astring amimetype, in nsidomwindow awindow, in nsiuri areferer, [array, size_is(ainstallcount)] in wstring auris, [array, size_is(ainstallcount)] in wstring ahashes, [array, size_is(ainstallcount)] in wstring anames, [array, size_is(ainstallcount)] in wstring aicons, [optional] in amiinstall
callback a
callback, [optional] in pruint32 ainstallcount); boolean isinstallenabled(in astring amimetype, in nsiuri areferer); note: prior to gecko 8.0, all references to nsidomwindow used in this interface were nsidomwindow.
...boolean installaddonsfromwebpage( in astring amimetype, in nsidomwindow awindow, in nsiuri areferer, [array, size_is(ainstallcount)] in wstring auris, [array, size_is(ainstallcount)] in wstring ahashes, [array, size_is(ainstallcount)] in wstring anames, [array, size_is(ainstallcount)] in wstring aicons, in amiinstall
callback a
callback, optional in pruint32 ainstallcount optional ); parameters amimetype the mimetype for the add-ons.
... a
callback optional an optional
callback to notify about installation success and failure.
imgILoader
this means that
callers of loadimage should make sure to cancel() the resulting request before the observer goes away.
...this means that
callers of loadimagewithchannel should make sure to cancel() the resulting request before the observer goes away.
...this must already be opened before this method is
called, and there must have been no ondataavailable
calls for it yet.
jsdIStackFrame
scripts typi
cally select this with the "language" attribute.
...method overview boolean eval(in astring bytes, in autf8string filename, in unsigned long line, out jsdivalue result); attributes attribute type description
callee jsdivalue function object running in this stack frame.
...
callingframe jsdistackframe link to the
caller's stack frame.
mozIStorageProgressHandler
the mozistorageprogresshandler interface lets storage consumers receive
callbacks during the execution of sqlite requests.
... last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports method overview boolean onprogress(in mozistorageconnection aconnection); methods onprogress() the onprogress() method is
called periodi
cally while an sqlite operation is ongoing.
... boolean onprogress( in mozistorageconnection aconnection ); parameters <tt>aconnection</tt> a mozistorageconnection connection indicating the connection for which the
callback was invoked.
nsIAbCard
complex properties are expected to be accessed through a
call to getproperty.
...we allow the
caller to cache the pref value, so we don't have to go to prefs every time.
...if cached by the
caller and supplied to this function, then performance will be improved over many
calls.
nsIAccessibleStates
state_invisible 0x00008000 the object is programmati
cally hidden.
... for example, menu items are programmati
cally hidden until a user activates the menu.
...a speech-based accessibility aid does not announce information when an object with this state has the focus because the object automati
cally announces information.
nsIAppStartup
this need be
called only once per application session.
...if there are no windows open and no outstanding
calls to enterlastwindowclosingsurvivalarea() this method will exit immediately.
...this return code indicates that the application should be restarted because quit was
called with the erestart flag.
nsIApplicationCacheService
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) method overview void cacheopportunisti
cally(in nsiapplicationcache cache, in acstring key); nsiapplicationcache chooseapplicationcache(in acstring key); nsiapplicationcache createapplicationcache(in acstring group); void deactivategroup(in acstring group); nsiapplicationcache getactivecache(in acstring group); nsiapplicationcache getapplicationcache(in acstring clientid); void getgroups([optional] out unsigned long count, [array, size_is(count), ...
...retval] out string groupids); methods cacheopportunisti
cally() flags the specified key as one that should be cached opportunisti
cally.
...void cacheopportunisti
cally( in nsiapplicationcache cache, in acstring key ); parameters cache the cache in which the entry is currently cached.
nsIAuthInformation
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the
caller of nsiauthprompt2.promptusernameandpassword() or nsiauthprompt2.promptpasswordasync() provides an object implementing this interface; the prompt implementation can then read the values here to prefill the dialog.
... after the user entered the authentication information, it should set the attributes of this object to indicate to the
caller what was entered by the user.
... 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.
nsIAutoCompleteListener
methods onautocomplete()
called by the autocomplete session when the search is done or over.
... as of gecko 1.9.1, can also be
called with partial results, in a similar manner to the toolkit autocomplete interface.
... onstatus()
called by the autocomplete session during the search.
nsICachingChannel
it will be set automati
cally if the browser is offline.
...this flag is set automati
cally when the application is offline.
... load_only_if_modified 1 << 31 this load flag controls what happens when a document would be loaded from the cache to satisfy a
call to asyncopen.
nsICharsetResolver
requestcharset()
called to resolve the charset that should be used for parsing the document being loaded from achannel.
...if this is done, the
caller of requestcharset is responsible for
calling notifyresolvedcharset() and passing it the final resolved charset and the closure that requestcharset set.
...awantcharset gets set to true if notifyresolvedcharset() should be
called with the given aclosure object.
nsIComponentManager
until gecko 10 you had to
call this method manually from within the add-on's startup() method (with a matching removebootstrappedmanifestlocation()
call in the add-on's shutdown() method).
... if you're targeting gecko 10 or higher there should be no need to
call this method, since the bootstrapped add-on's chrome.manifest is loaded automati
cally now.
...unlike getservice, this returns a new instance each time it is
called.
nsIDialogParamBlock
must be in the range 0..15 unless setnumberstrings was
called.
...this method can only be
called once.
...must be in the range 0..15 unless setnumberstrings was
called.
nsIDirectoryEnumerator
the nextfile attribute is the first element upon the first
call.
...it is safe to
call this function many times.
...exceptions thrown ns_ok if the
call succeeded and the directory was closed.
getFile
« xpcom api reference
called by the directory service to obtain an nsifile object corresponding for a given standard path location.
... xpcom file system aliases apersistent [out] this output parameter indicates to the
caller whether or not the returned location is persistent.
..._win_personal_dir "pers" ns_win_favorites_dir "favs" ns_win_startup_dir "strt" ns_win_recent_dir "rcnt" ns_win_send_to_dir "sndto" ns_win_bitbucket_dir "buckt" ns_win_startmenu_dir "strt" same thing as ns_os_desktop_dir ns_win_desktop_directory "deskp" file sys dir which physi
cally stores objects on desktop ns_win_drives_dir "drivs" ns_win_network_dir "netw" ns_win_nethood_dir "neth" ns_win_fonts_dir "fnts" ns_win_templates_dir "tmpls" ns_win_common_startmenu_dir "cmstrt" ns_win_common_programs_dir "cmprgs" ns_win_common_startup_dir "cmstrt" ...
nsIDragService
methods native code only!dragmoved programmati
cally changes the drag position of the drag session.
...this is
called when an external drag occurs.
...this is
called when an external drag occurs void startdragsession(); parameters none.
nsIEffectiveTLDService
to use this service, use: var etldservice = components.classes["@mozilla.org/network/effective-tld-service;1"] .getservice(components.interfaces.nsieffectivetldservice); the name "effective tld service" is a historical one; today, the items this interface manipulates are
called public suffixes, and the list of them is the public suffix list, or psl.
...therefore, if you
call getpublicsuffix("a.b.c.nonexistent"), you will get back "nonexistent" - this "tld" is not in the public suffix list, but the implicit "*" rule means that it is returned.
...the tld space is currently expanding at a fairly great rate, and the copy of the psl firefox has may not be totally up to date (because it's not dynami
cally updated data).
nsIEventTarget
events may be sent to this target from any thread by
calling the dispatch method.
...this function may be
called from any thread, and it may be
called re-entrantly.
...return value returns true if events dispatched to this event target will run on the current thread (that is, the thread
calling this method).
nsIFeedProcessor
toolkit/components/feeds/public/nsifeedprocessor.idlscriptable this interface parses rss or atom feeds, triggering
callbacks based on their contents during and after the processing.
...the
caller must then
call the processor's nsistreamlistener methods to drive the parsing process.
... you must not
call any of the other parsing methods on the nsifeedprocessor interface during an asynchronous parse.
nsIFileProtocolHandler
should only be
called on files which are not directories.
...should only be
called on files which are directories.
... note:
callers should use geturlspecfromactualfile() if possible, for performance reasons.
nsIHTTPHeaderListener
modules/plugin/base/public/nsihttpheaderlistener.idlscriptable this interface allows plugin authors to access http response headers after issuing an nsipluginhost.geturl or nsipluginhost.posturl
call.
... 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.
nsIHttpUpgradeListener
netwerk/protocol/http/nsihttpchannelinternal.idlscriptable the
callback interface for nsihttpchannelinternal.httpupgrade; this is
called when an http protocol upgrade is finished.
...method overview void ontransportavailable(in nsisockettransport atransport, in nsiasyncinputstream asocketin, in nsiasyncoutputstream asocketout); methods ontransportavailable()
called when an http protocol upgrade attempt is completed, passing in the information needed by the protocol handler to take over the channel that is no longer being used by http.
... note: to begin a protocol upgrade,
call nsihttpchannelinternal.httpupgrade().
nsIMemoryReporter
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) any piece of code that wishes to allow its memory use to be monitored may create an nsimemoryreporter object and then register it by
calling nsimemoryreportermanager.registerreporter().
... note: this attribute was
called memoryused prior to gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4), and its type was long long.
... deprecated since gecko 8.0 kind_nonheap 0 allocated directly by os
calls e.g.
nsIMicrosummaryObserver
ecko 6.0 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) method overview void oncontentloaded(in nsimicrosummary microsummary); void onelementappended(in nsimicrosummary microsummary); void onerror(in nsimicrosummary microsummary); methods oncontentloaded()
called when an observed microsummary updates its content.
... onelementappended()
called when an element is appended to a microsummary set.
... onerror()
called when an observed microsummary encounters an error during an update.
nsIMsgIdentity
autoquote boolean should we automati
cally quote the original message?
... signaturedate long escapedvcard astring dofcc boolean fccfolder astring fccfolderpickermode astring fccreplyfollowsparent boolean draftsfolderpickermode astring tmplfolderpickermode astring bccself boolean note: don't
call bccself, bccothers, and bcclist directly, they are only used for migration and backward compatability.
...this destroys all pref values; do not
call this unless you know what you're doing!
nsIMsgMessageService
nsiuri aurl); void openattachment(in string acontenttype, in string afilename, in string aurl, in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener); void savemessagetodisk(in string amessageuri, in nsifilespec afile, in boolean ageneratedummyenvelope, in nsiurllistener aurllistener, out nsiuri aurl, in boolean canoni
callineending, in nsimsgwindow amsgwindow); void geturlforuri(in string amessageuri, out nsiuri aurl, in nsimsgwindow amsgwindow); void displaymessageforprinting(in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener, out nsiuri aurl); void search(in nsimsgsearchsession asearchsession, in nsimsgwindow amsgwindow, in...
... void savemessagetodisk(in string amessageuri, in nsifilespec afile, in boolean ageneratedummyenvelope, in nsiurllistener aurllistener, out nsiuri aurl, in boolean canoni
callineending, in nsimsgwindow amsgwindow); parameters amessageuri url representing the message to spool out to disk.
... canoni
callineending amsgwindow nsimsgwindow for progress and status feedback return values aurl the new nsiuri of the saved message.
nsIMsgWindowCommands
method overview void selectfolder(in acstring folderuri); void selectmessage(in acstring messageuri); void clearmsgpane(); methods selectfolder() this method is
called by the backend to change the folder displayed in the message window.
... selectmessage() this method is
called by the backend to change the displayed message.
... clearmsgpane() this method is
called by the backend when it wants to clear the message pane, for instance if you select the group header .
nsIMutableArray
xpcom/ds/nsimutablearray.idlscriptable this interface is a subclass of nsiarray that provides arrays that are mutable; that is, they can be altered programmati
cally.
...any of these methods may throw ns_error_out_of_memory when the array must grow to complete the
call, but the allocation fails.
...to remove a specific element, use nsiarray.indexof() to find the index first, then
call removeelementat.
nsINavHistoryContainerResultNode
this is false for bookmark folder nodes unless the setfolderreadonly() method has been
called to specifi
cally make the folder read-only.
...when closed, attempting to
call getchild() or access childcount results in an error.
...the container may be a result_type_remote_container node that has been dynami
cally generated by the remote container api, or a bookmark folder (result_type_folder) for which some service (such as livemarks) has registered to provide certain operations.
nsINavHistoryResult
more specifi
cally, the nsinavhistoryresultviewer interface provides the view component of the pattern, and nsinavhistoryresultviewobserver is the controller.
... aownsweak if false, the result will keep an owning reference to the observer, which must be removed by
calling removeobserver().
... removeobserver() removes an observer that was added by a previous
call to addobserver().
nsIObserverService
(in most cases, you should use false.) enumerateobservers()
called to enumerate all observers registered for a particular topic.
... notifyobservers() this method is
called to notify all observers for a particular topic.
... removeobserver() this method is
called to unregister an observer for a particular topic.
nsIRequestObserver
inherits from: nsisupports last changed in gecko 1.0 method overview void onstartrequest(in nsirequest arequest, in nsisupports acontext); void onstoprequest(in nsirequest arequest, in nsisupports acontext, in nsresult astatuscode); methods onstartrequest()
called to signify the beginning of an asynchronous request.
... onstoprequest()
called to signify the end of an asynchronous request.
... this
call is always preceded by a
call to onstartrequest().
nsIResumableChannel
the request will not start until asyncopen or open is
called.
...
calling resumeat after open or asyncopen has been
called has undefined behaviour.
...in both of these cases, no ondataavailable will be
called, and onstoprequest will immediately follow with the same status code.
nsIScreen
gecko 1.9.2 note starting in gecko 1.9.2, gecko running on microsoft windows reports 24 bits per pixel instead of 32 bits per pixel on 8-bits per color component displays, since this is typi
cally what the
caller is actually looking for.
...each
call to this method must eventually be followed by a corresponding
call to unlockminimumbrightness() with the same value for the brightness parameter.
... unlockminimumbrightness() releases a lock on the minimum brightness of the screen, which was previously established through a corresponding
call to lockminimumbrightness().
nsIScriptableUnicodeConverter
after converting, finish should be
called and its return value appended to this return value.
...should be
called after convertfromunicode() and appended to that function's return value.
...finish does not need to be
called.
nsISeekableStream
exceptions thrown ns_base_stream_closed if
called on a closed stream.
...exceptions thrown ns_base_stream_closed if
called on a closed stream.
...exceptions thrown ns_base_stream_closed if
called on a closed stream.
nsISelection2
avpercent how to align the frame verti
cally.
...a value of 50 centers the frame verti
cally.
... a value of -1 means move the frame the minimum amount necessary in order for the entire frame to be visible verti
cally (if possible).
nsIServerSocketListener
the address of the client can be found by
calling the nsisockettransport.getaddress() method or by inspecting nsisockettransport.gethost(), which returns a string representation of the client's ip address, which may be either an ipv4 or an ipv6 address.
... inherits from: nsisupports last changed in gecko 1.7 method overview void onsocketaccepted(in nsiserversocket aserv, in nsisockettransport atransport); void onstoplistening(in nsiserversocket aserv, in nsresult astatus); methods onsocketaccepted() this method is
called when a client connection is accepted.
... onstoplistening() this method is
called when the listening socket stops for some reason.
nsISocketProvider
methods native code only!addtosocket this function is
called to allow the socket provider to layer a prfiledesc (a file descriptor) on top of another prfiledesc.
...this object typi
cally implements nsitransportsecurityinfo.
...this object typi
cally implements nsitransportsecurityinfo.
nsISocketTransportService
note: this function may only be
called from an event dispatch on the socket thread.
... note: this function can be
called from any thread.
... note: this function may only be
called from an event dispatch on the socket thread.
nsIStreamListener
method overview void ondataavailable(in nsirequest arequest, in nsisupports acontext, in nsiinputstream ainputstream, in unsigned long aoffset, in unsigned long acount); methods ondataavailable() this method is
called when the next chunk of data for the ongoing request may be read without blocking the
calling thread.
...aoffset number of bytes that were sent in previous ondataavailable()
calls for this request.
...you must read all of these bytes before returning to the
caller.
nsIThreadPool
the thread pool takes ownership of the listener and releases it when the shutdown() method is
called.
... you must not
call this method from any thread within the thread pool.
... instead, you should
call it from another thread (typi
cally the one that created the thread pool).
nsITransactionList
the list returned is addref'd so it is up to the
caller to release the transaction when it is done.
...the transaction returned is addref'd so it is up to the
caller to release the transaction when it is done.
...however, you can still access the transactions contained in the batch with a
call to getchildlistforitem().
nsITransferable
this should be
called on all transferable objects.
... to get the appropriate load context in javascript
callers, one needs to get to the document that the transferable corresponds to, and then get the load context from the document like this: var loadcontext = doc.defaultview.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsiloadcontext); in c++
callers, if you have the corresponding document, you can just
call nsidocu...
...the transferable maintains its own copy of the data, so you can safely discard the original after making this
call, if you wish.
nsIUpdateCheckListener
irefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void oncheckcomplete(in nsixmlhttprequest request, [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount); void onerror(in nsixmlhttprequest request, in nsiupdate update); void onprogress(in nsixmlhttprequest request, in unsigned long position, in unsigned long totalsize); methods oncheckcomplete()
called when the update check is completed.
... onerror()
called when an error occurs while loading the remote update service file.
... onprogress()
called every time there is a progress notification loading the update service file.
nsIWebBrowserChrome
chrome_with_size 4096 specifi
cally for use with nsiwindowcreator.
... chrome_with_position 8192 specifi
cally for use with nsiwindowcreator.
...setstatus()
called when the status text in the chrome needs to be updated.
nsIWebSocketChannel
notification
callbacks nsiinterfacerequestor the notification
callbacks for authorization and so forth.
...the socket listener's methods are
called on the thread that
calls asyncopen() and are not
called until after asyncopen() returns.
... if asyncopen() returns successfully, the protocol implementation promises to
call at least onstart and onstop of the listener.
nsIWorkerScope
1.0 66 introduced gecko 1.9.1 inherits from: nsiworkerglobalscope last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview void postmessage(in domstring amessage, [optional] in nsiworkermessageport amessageport); void close(); attributes attribute type description onclose nsidomeventlistener a listener object to be
called when the worker stops running.
... onmessage nsidomeventlistener a listener object to be
called when a message is posted on the port.
...if a listener has been established by setting the value of the onclose attribute, it gets
called.
nsIXULWindow
intrinsi
callysized boolean indicates if this window is instrinsi
cally sized.
...do not
call this unless you know what you are doing!
... in particular,
calling this when this xul window does not yet have a document in its docshell could cause problems.
NS_CStringContainerInit
with ns_cstringcontainerinit, the coder is required to
call ns_cstringcontainerfinish when done with the nscstringcontainer object.
... therefore, it is generally better to use nsembedcstring, to instantiate a nsacstring object, since it automati
cally releases allocated memory when the object goes out of scope.
... //
call this function to release any memory owned by |str| when done.
NS_CStringContainerInit2
the
caller must ensure that the data is valid for the lifetime of the string container.
...the
caller must have allocated the data array using the xpcom memory allocator.
...the ns_cstringcontainerinit function is equivalent to
calling ns_cstringcontainerinit with adata=nsnull and aflags=0.
NS_StringContainerInit
with ns_stringcontainerinit, the coder is required to
call ns_stringcontainerfinish when done with the nsstringcontainer object.
... therefore, it is generally better to use nsembedstring, to instantiate a nsastring object, since it automati
cally releases allocated memory when the object goes out of scope.
... // be sure to
call this function to release any memory owned by |str| when done.
Frequently Asked Questions
call a getter that uses a raw xpcom interface pointer as an `in/out' parameter?
...
call a getter that fills in an nsifoo*& parameter?
...
call a getter that doesn't addref its result?
XPCOM ownership guidelines
such a function is the perfect example of something that creates an object with a longer lifespan that itself, and gives away ownership (by producing a pointer that is already addrefed) --- in this case, to the
caller.
...anytime there is a cycle of ownership, there is a situation that isn't automati
cally handled by destructors.
... special code must be provided and
called to break the cycle before the participants can be individually released.
Test-Info
each task generates one or more json-formatted data files providing detailed information on tests run in continuous integration, typi
cally broken down by bugzilla component.
... data files are typi
cally consumed by dashboards, like www.arewefissionyet.com.
... running test-info lo
cally "test-info" is a mach command and can be run from any source tree.
The Valgrind Test Job
running the valgrind test job lo
cally valgrind works best on linux.
... ac_add_options --enable-valgrind ac_add_options --disable-jemalloc running to run the valgrind test job lo
cally, run the following command.
... when running lo
cally, you may see errors that do not occur on the test machines.
MailNews Filters
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.
...applyfilterstohdr will in turn
call the applyfilterhit method of the passed in nsimsgfilterhitnotify interface ptr.
...the search is executed lo
cally, not on the server, so that criteria like "in address book" still work.
The libmime module
typedef struct foobarclass foobarclass; typedef struct foobar foobar; class declaration theis structure defines the
callback routines and other per-class data of the class defined in this module.
... struct foobarclass { parentclass superclass; ...any
callbacks or class-variables...
... any methods or class variables which this class does not wish to override will be automati
cally inherited from the parent class (by virtue of its class-initialization function having been run first.) each class object will only be initialized once.
Thunderbird Configuration Files
the path examples above refers to the default profile that is automati
cally created when you start thunderbird for the first time.
... userchrome.css this file sets the display rules for various elements in the thunderbird user interface and is located in the sub-folder
called chrome in your profile folder.
... usercontent.css this file sets the display rules for web content and is located in the sub-folder
called chrome in your profile folder.
Building a Thunderbird extension 5: XUL
the status bar is implemented in a xul file
called messenger.xul, which can be found in the chrome/messenger/content/messenger folder which is packaged inside the omni.ja archive.
...therefore it becomes an item owned by the id
called "status-bar".
... 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="my-panel" label="date"/> </statusbar> </overlay> the <statusbar> widget named status-bar specifies the merge point within the applicatio...
Building a Thunderbird extension 6: Adding JavaScript
( 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 automati
cally when thunderbird loads.
... the event listener then
calls our startup function which gets our <statusbarpanel>-element with the id my-panel from the document's dom tree.
...this allows us to
call the startup function repeatedly with an interval of 60000ms (every minute).
Finding the code for a feature
repeating this process, i see that the submenu items all
call a function togglemessagetagmenu.
... looking that up in mxr, its underlying function uses a very strange
call prevhdrfolder[toggler](messages, key) to change the key.
... trying to figure that out from the code, i see that is just a clever way to do the addkeywordstomessages or removekeywordsfrommessages method
call.
libmime content type handlers
a necessary capability of this module is to dynami
cally add the ability to decode and render various content types.
... api's content type handler plugins are dynami
cally loaded and need to access internal pointers, functions that are part of the c based object system.
... /* * this interface is implemented by content type handlers that will be *
called upon by libmime to process various attachments types.
Using Objective-C from js-ctypes
let objc_getclass = lib.declare("objc_getclass", ctypes.default_abi, id, ctypes.char.ptr); let sel_registername = lib.declare("sel_registername", ctypes.default_abi, sel, ctypes.char.ptr);
calling variadic function objc_msgsend is a variadic function, so we should always pass it a cdata instance, other than this first and second argument, to declare each argument type.
... for example, let's take the following function
call: id text = objc_msgsend(tmp2, initwithcstring_encoding, "hello, firefox!", nsutf8stringencoding); [nsstring initwithcstring:encoding:] is defined as: - (instancetype)initwithcstring:(const char *)nullterminatedcstring encoding:(nsstringencoding)encoding and nsstringencoding is defined as: typedef unsigned long nsuinteger; typedef nsuinteger nsstringencoding; so, our function
call can be converted into the following js-ctypes code: let text = objc_msgsend(tmp2, initwithcstring_encoding, ctypes.char.array()("hello, firefox!"), ctypes.unsigned_long(nsutf8stringencoding)); converted js-ctypes code finally, we have our converted code.
...while (objc_msgsend_bool(synth, isspeaking)) {} let release = sel_registername("release"); objc_msgsend(synth, release); objc_msgsend(text, release); lib.close(); creating objective-c blocks objective-c api
calls sometimes require you to pass in a block.
StructType
you can
call the resulting type's define() method to assign it a non-opaque type later.
...this is the result of
calling ctypes.pointertype(the_type).
... structtype cdata method_overview cdata addressoffield(name) methods inherited from cdata cdata address() string tosource() string tostring() structtype cdata methods addressoffield() returns a new cdata object of the appropriate pointer type, whose value points to the specified field of the structure on which the method was
called.
js-ctypes
js-ctypes allows application and extension code to
call back and forth to native code written in c.
... using js-ctypes ctypes.open custom native file standard os libraries finding window handles working with data working with arraybuffers declaring types declaring and
calling functions declaring and using
callbacks type conversion memory management chromeworker js-ctypes reference a reference guide to the js-ctypes api.
... examples add to iphoto a firefox extension that uses js-ctypes to
call carbon and core foundation framework routines on mac os x to implement an "add image to iphoto" feature in firefox.
Structures - Plugins
structure summary npany
callbackstruct contains information required during embedded mode printing.
... npprint
callbackstruct contains information required by the platformprint field of the npembedprint during embedded mode printing.
... npsetwindow
callbackstruct contains information about the plug-in's unix window environment.
Set a breakpoint - Firefox Developer Tools
breakpoints in brief breakpoints are very useful when debugging javascript — you basi
cally set a point in your code where you would like execution of the code to pause.
... the line number is highlighted in blue: in addition, if the line contains multiple function
calls, each one will be given a small blue arrow icon to the left of it.
... these are
called column breakpoints, and allow you to set the breakpoint to happen exactly on any one of the function
calls in the line (or multiple
calls), by clicking on each relevant one.
Set event listener breakpoints - Firefox Developer Tools
starting with firefox 69, debugging an application that includes event handlers is simplified because the debugger now includes the ability to automati
cally break when the code hits an event handler.
...instead, it’d be far more useful if we showed where in our own app code is
calling the jquery that fired the event.
... 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...
Tutorial: Set a breakpoint - Firefox Developer Tools
reportdo.script.setbreakpoint(0, { hit: function (frame) { console.log('hit breakpoint in ' + frame.
callee.name); console.log('what = ' + frame.eval('what').return); } }); console.log('finished setting breakpoint!'); in the scratchpad, ensure that no text is selected, and press the “run” button.
...when control reaches the start of the report function, debugger
calls the breakpoint handler’s hit method, passing a debugger.frame instance.
...the toolbox’s console now looks like this: you can also click on the text that says “or me!”, to see report
called from a different handler.
Basic operations - Firefox Developer Tools
recording
call stacks the memory tool can tell you exactly where in your code you are allocating memory.
... however, recording this information has a run-time cost, so you must ask the tool to record memory
calls before the memory is allocated, if you want to see memory
call sites in the snapshot.
... to do this, check "record
call stacks" (before firefox 49 this was labeled "record allocation stacks"): ...
Examine and edit HTML - Firefox Developer Tools
there are three types of searches that are performed automati
cally depending on what you enter, a full text search, a css selector search, and an xpath search.
... html tree the rest of the pane shows you the page's html as a tree (this ui is also
called the markup view).
... usually this white space seems to have no effect and no visual output, but in fact, when a browser parses html it will automati
cally generate anonymous text nodes for elements not contained in a node.
Use the Inspector API - Firefox Developer Tools
bindable events using on: markuploaded
called when the left panel has been refreshed, after page change.
... ready
called on first markuploaded.
... pseudoclass
called after toggle of a pseudoclass.
Storage Inspector - Firefox Developer Tools
cookies created as a part of response of network
calls are also listed, but only for
calls that happened while the tool is open.
...it's just
called "storage" in the developer toolbox.
...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 automati
cally.
Style Editor - Firefox Developer Tools
once you're satisfied with your changes, you can save a copy lo
cally by clicking the save button on the sheet's entry in the style sheet pane.
... the style editor automati
cally de-minimizes style sheets that it detects, without affecting the original.
... first, set up your preprocessor so it watches the original source and automati
cally regenerates the css when the source changes.
Web Console Helpers - Firefox Developer Tools
equivalent to document.queryselector() or
calls the $ function in the page, if it exists.
...otherwise, json.stringify will be
called on the argument, and the result will be copied to the clipboard.
... let's take a look at the contents of that node by using the $() and inspect() functions: inspect($("#title")) this automati
cally generates rich output for the object, showing you the contents of the dom node that matches the css selector "#title", which is of course the element with id "title".
about:debugging (before Firefox 68) - Firefox Developer Tools
before firefox 48 if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automati
cally, and you'll see them the next time the content script is loaded or the popup is shown.
... firefox 48 onwards from firefox 48 onwards: as before: if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automati
cally, and you'll see them the next time the content script is loaded or the popup is shown.
...however, you can also debug push notifications lo
cally, without needing the server.
AnalyserNode - Web APIs
analysernode.mindecibels is a double value representing the minimum power value in the scaling range for the fft analysis data, for conversion to unsigned byte values — basi
cally, this specifies the minimum value for the range of results when using getbytefrequencydata().
... analysernode.maxdecibels is a double value representing the maximum power value in the scaling range for the fft analysis data, for conversion to unsigned byte values — basi
cally, this specifies the maximum value for the range of results when using getbytefrequencydata().
... analysernode.smoothingtimeconstant is a double value representing the averaging constant with the last analysis frame — basi
cally, it makes the transition between values over time smoother.
Animation.persist() - Web APIs
the persist() method of the web animations api's animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's automati
cally removing filling animations behavior.
...for this reason, modern browsers automati
cally remove overriding forward filling animations.
...this will be active for each animation by default, or persisted if the persist()
call is uncommented.
Animation.replaceState - Web APIs
the value can be one of: active: the initial value of the animation's replace state; when the animation has been removed by the browser's automati
cally removing filling animations behavior.
...for this reason, modern browsers automati
cally remove overriding forward filling animations.
...this will be active for each animation by default, or persisted if the persist()
call is uncommented.
Animation.reverse() - Web APIs
if
called on an unplayed animation, the whole animation is played backwards.
... if
called on a paused animation, the animation will continue in reverse.
...it is done by setting alicechange's animation.playbackrate to -1 like so: var shrinkalice = function() { // play alice's animation in reverse alicechange.playbackrate = -1; alicechange.play(); // play the bottle's animation drinking.play() } but it could also have been done by
calling reverse() on alicechange like so: var shrinkalice = function() { // play alice's animation in reverse alicechange.reverse(); // play the bottle's animation drinking.play() } specifications specification status comment web animationsthe definition of 'reverse()' in that specification.
Animation - Web APIs
animation.persist() explicitly persists an animation, when it would otherwise be removed due to the browser's automati
cally removing filling animations behavior.
... automati
cally removing filling animations it is possible to trigger a large number of animations on the same element.
...for this reason, modern browsers have implemented the part of the web animations spec that automati
cally removes overriding forward filling animations, unless the developer explicitly specifies to keep them.
AudioBufferSourceNode.start() - Web APIs
using this parameter is functionally identical to
calling start(when, offset) and then
calling stop(when+duration).
... invalidstateerror start() has already been
called.
... you can only
call this function once during the lifetime of an audiobuffersourcenode.
AudioContext.close() - Web APIs
this function does not automati
cally release all audiocontext-created objects, unless other references have been released as well; however, it will forcibly release any system audio resources that might prevent additional audiocontexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data.
...this method throws an invalid_state_err exception if
called on an offlineaudiocontext.
... example the following snippet is taken from our audiocontext states demo (see it running live.) when the stop button is clicked, close() is
called.
AudioParam.value - Web APIs
setting value has the same effect as
calling audioparam.setvalueattime with the time returned by the audiocontext's currenttime property..
... if the current time equals or exceeds the time specified by a previous
call to setvalueattime(), the value is changed to the value passed into setvalueattime().
... if any gradiated or ramped value changing methods have been
called and the current time is within the time range over which the graduated change should occur, the value is updated based on the appropriate algorithm.
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.
... 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.
... example this snippet establishes a handler for the addtrack event that
calls a function, addtotracklist(), passing in the audiotrack object representing the newly-added track.
AudioTrackList.onchange - Web APIs
the audiotracklist property onchange is an event handler which is
called when the change event occurs, indicating that one or more of the audiotracks in the audiotracklist have been enabled or disabled.
... syntax audiotracklist.onchange = eventhandler; value set onchange to a function that should be
called whenever tracks are enabled or disabled on the media element.
... example this snippet establishes a handler for the change event that looks at each of the tracks in the list,
calling a function to update the state of a user interface control that indicates the current state of the track.
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.
... onchange an event handler to be
called when the change event occurs.
... onremovetrack an event handler to
call when the removetrack event is sent, indicating that an audio track has been removed from the media element.
AudioWorkletProcessor - Web APIs
the constructor of the deriving class is getting
called with an options object, so you can perform a custom initialization procedures — see constructor page for details.
...however, you must provide a process() method, which is
called in order to process the audio stream.
...this method gets
called for each block of 128 sample-frames and takes input and output arrays and calculated values of custom audioparams (if they are defined) as parameters.
Using the Beacon API - Web APIs
the handler
calls sendbeacon() with the current url.
...//example.com/analytics"; // create the data to send var data = "state=" + event.type + "&location=" + location.href; // send the beacon var status = navigator.sendbeacon(url, data); // log the data and result console.log("sendbeacon: url = ", url, "; data = ", data, "; status = ", status); }; the following example creates a submit handler and when that event is fired, the handler
calls sendbeacon().
... window.onsubmit = function send_analytics() { var data = json.stringify({ location: location.href, time: date() }); navigator.sendbeacon('/analytics', data); }; workernavigator.sendbeacon() the beacon api's workernavigator.sendbeacon() method works identi
cally to the usual method, but is accessible from worker global scope.
CSSStyleSheet.insertRule() - Web APIs
mystyle.insertrule('#blanc { color: white }', 0); function to add a stylesheet rule /** * add a stylesheet rule to the document (it may be better practice * to dynami
cally change classes, so style information can be kept in * genuine stylesheets and avoid adding extra elements to the dom).
... /*else*/ return originalinsertrule.
call( this, // the sheet to be changed selectorandrule.substring(0, openbracketpos), // the selector selectorandrule.substring(closebracketpos), // the rule arguments[3] // the insert index ); } // works by if the char code is a backslash, then isescaped // gets flipped (xor-ed by 1), and if it is not a backslash ...
... // then isescaped gets xored by itself, zeroing it isescaped ^= newcharcode===92?1:isescaped; // 92 = "\\".charcodeat(0) } // else, there is no unescaped bracket return originalinsertrule.
call(this, selectorandrule, "", arguments[2]); }; } })(cssstylesheet.prototype); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.insertrule' in that specification.
CSSUnparsedValue.forEach() - Web APIs
syntax cssunparsedvalue.foreach(function
callback(currentvalue[, index[, array]]) { // your iterator }[, thisarg]); parameters
callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... arrayoptional the cssunparsedvalue that foreach() is being
called on.
... thisarg optional value to use as this (i.e the reference object) when executing
callback.
CSS Painting API - Web APIs
for example: aside { background-image: paint(mypaintedimage); } the api defines paintworklet, a worklet that can be used to programmati
cally generate an image that responds to computed style changes.
... interfaces paintworklet programmati
cally generates an image where a css property expects a file.
... we create our paintworklet
called 'hollowhighlights' using the registerpaint() function: registerpaint('hollowhighlights', class { static get inputproperties() { return ['--boxcolor']; } static get inputarguments() { return ['*','<length>']; } static get contextoptions() { return {alpha: true}; } paint(ctx, size, props, args) { const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; ...
CanvasRenderingContext2D.fillText() - Web APIs
this method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke()
calls will have no effect on it.
... to draw the outlines of the characters in a string,
call the context's stroketext() method.
... with that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then
call filltext() to draw the text "hello world," starting at the coordinates (50, 90).
CanvasRenderingContext2D.shadowOffsetY - Web APIs
the canvasrenderingcontext2d.shadowoffsety property of the canvas 2d api specifies the distance that shadows will be offset verti
cally.
... syntax ctx.shadowoffsety = offset; offset a float specifying the distance that shadows will be offset verti
cally.
... examples moving a shadow verti
cally this example adds a blurred shadow to a rectangle.
Clients.openWindow() - Web APIs
if the
calling script doesn't have permission to show popups, openwindow() will throw an invalidaccesserror.
... in firefox, the method is allowed to show popups only when
called as the result of a notification click event.
...generally this value must be a url from the same origin as the
calling script.
console.count() - Web APIs
the console.count() method logs the number of times that this particular
call to count() has been
called.
...if supplied, count() outputs the number of times it has been
called with that label.
... if omitted, count() behaves as though it was
called with the "default" label.
Console.group() - Web APIs
this indents following console messages by an additional level, until console.groupend() is
called.
...to create a new nested block,
call console.group().
... to exit the current group,
call console.groupend().
Console.timeEnd() - Web APIs
stops a timer that was previously started by
calling console.time().
...once stopped, the elapsed time is automati
cally displayed in the web console along with an indicator that the time has ended.
...in addition, the
call to timeend() has the additional information, "timer ended" to make it obvious that the timer is no longer tracking time.
Content Index API - Web APIs
indexed entries do not automati
cally expire.
... it's good practice to present an interface for clearing out entries, or periodi
cally remove older entries.
...it is not fired when the contentindex.delete method is
called.
CredentialsContainer.get() - Web APIs
this method collects credentials by
calling the "collectfromcredentialstore" method for each credential type allowed by the options argument.
... for example: if options.password exists, then the passwordcredential.[[collectfromcredentialstore]] is
called.
...
calls to it within an <iframe> element will resolve without effect.
CredentialsContainer.preventSilentAccess() - Web APIs
for example, you might
call this, after a user signs out of a website to ensure that he/she isn't automati
cally signed in on the next site visit.
...this method is typi
cally
called after a user signs out of a website, ensuring this user's login information is not automati
cally passed on the next site visit.
... earlier versions of the spec
called this method requireusermediation().
CustomEvent - Web APIs
event.defaultprevented read only indicates whether or not the
call to event.preventdefault() canceled the event.
... this interface inherits methods from its parent, event: event.createevent() creates a new event, which must then be initialized by
calling its initevent() method.
... event.stopimmediatepropagation() for this particular event, prevent all other listeners from being
called.
DOMException - Web APIs
the domexception interface represents an abnormal event (
called an exception) that occurs as a result of
calling a method or accessing a property of a web api.
... this is basi
cally how error conditions are described in web apis.
... note: because histori
cally the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past.
DataTransfer.setDragImage() - Web APIs
this image is created automati
cally, so you do not need to create it yourself.
...the image will typi
cally be an <image> element but it can also be a <canvas> or any other visible element.
... this method must be
called in the dragstart event handler.
DeprecationReportBody - Web APIs
this typi
cally matches the message a browser will display in its devtools console when a deprecated feature is used, if one is available.
...f 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 the reportingobserver() constructor, we can now click the button to display the report details.
... the report details are displayed via the displayreports() fuction, which takes the observer
callback's reports parameter as its parameter: function displayreports(reports) { const outputelem = document.queryselector('.output'); const list = document.createelement('ul'); outputelem.appendchild(list); for(let i = 0; i < reports.length; i++) { let listitem = document.createelement('li'); let textnode = document.createtextnode('report ' + (i + 1) + ', type: ' + reports[i].type); listitem.appendchild(textnode); let innerlist = document.createelement('ul'); listitem.appendchild(innerlist); list.appendchild(listitem); for (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; in...
DirectoryEntrySync - Web APIs
the following creates an empty file
called seekrits.txt in the root directory.
...the following creates a new directory
called superseekrit in the root directory.
...catch these cases with error
callbacks and retry the deletion.
Document.mozSetImageElement() - Web APIs
ar c = 0x00; function clicked() { var canvas = document.createelement("canvas"); canvas.setattribute("width", 100); canvas.setattribute("height", 100); var ctx = canvas.getcontext('2d'); ctx.fillstyle = "#" + c.tostring(16) + "0000"; ctx.fillrect(25, 25, 75, 75); c += 0x11; if (c > 0xff) { c = 0x00; } document.mozsetimageelement("canvasbg", canvas); } the code here is
called each time the user clicks the <div> element.
...each time the function is
called, the square is a different color (its red component is increased each time), so each time the user clicks the element, the background is filled with a brighter and brighter pattern of red tiles.
... 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.
Document.onfullscreenerror - Web APIs
the document.onfullscreenerror property is an event handler for the fullscreenerror event that is sent to the document when it fails to transition into full-screen mode after a prior
call to element.requestfullscreen().
... example this example attempts to
call requestfullscreen() outside of an event handler.
... since requestfullscreen() can only be
called in response to user action, for security reasons, this will fail, causing the fullscreenerror to be sent to the document.
Document.open() - Web APIs
document.open(); document.write("<p>hello world!</p>"); document.write("<p>i am a fish</p>"); document.write("<p>the number is 42</p>"); document.close(); notes an automatic document.open()
call happens when document.write() is
called after the page has loaded.
...as a result, you can no longer
call document.write() into an untrusted document from chrome, even using wrappedjsobject.
... 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.
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
because of this, it establishes what is
called an inline formatting context.
...if an element contains at least one block element, then it instead establishes what is
called a block formatting context.
... </div> </body> we can summarize how the whitespace here is handled as follows (the may be some slight differences in exact behavior between browsers, but this basi
cally works): because we’re inside a block formatting context, everything must be a block, so our 3 text nodes also become blocks, just like the 2 <div>s.
EXT_float_blend - Web APIs
doing so automati
cally enables ext_float_blend as well.
... with this extension enabled,
calling drawarrays() or drawelements() with blending enabled and a draw buffer with 32-bit floating-point components will no longer result in an invalid_operation error.
... usage notes on devices that support the ext_float_blend extension, it is automati
cally, implicitly, enabled when any one or more of ext_color_buffer_float, oes_texture_float, or webgl_color_buffer_float are enabled.
EffectTiming.fill - Web APIs
that css looks like this: #box { width: 200px; height: 200px; left: 50px; top: 50px; border: 1px solid #7788ff; margin: 0; position: relative; background-color: #2233ff; display: flex; justify-content: center; } all this does is specify the size, border, and color information, as well as indicate that the box should be centered both verti
cally and horizontally inside its container.
... document.getelementbyid("animatebutton").addeventlistener("click", event => { document.getelementbyid("box").animate( boxrotationkeyframes, boxrotationtiming ); }, false); the rest of the code is pretty simple: it adds an event listener to the "animate" button so that when it's clicked by the user, the box is animated by
calling element.animate() on it, providing the boxrotationkeyframes and boxrotationtiming objects to describe the animation that should occur.
...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 primarily provided as a means of representing the animation-fill-mode feature of css animations.
Element: click event - Web APIs
his bug: for ie9 only: set background-color: rgba(0,0,0,0) set opacity: 0 and an explicit background-color other than transparent for ie8 and ie9: set filter: alpha(opacity=0); and an explicit background-color other than transparent safari mobile safari mobile 7.0+ (and likely earlier versions too) suffers from a bug where click events aren't fired on elements that aren't typi
cally interactive (e.g.
... use a typi
cally interactive element (e.g., <a>) instead of one that isn't typi
cally interactive (e.g., <div>).
... safari mobile considers the following elements to be typi
cally interactive (and thus they aren't affected by this bug): <a> (but it must have an href) <area> (but it must have an href) <button> <img> <input> <label> (but it must be associated with a form control) <textarea> this list is incomplete; you can help mdn by doing further testing/research and expanding it.
Element.getAttribute() - Web APIs
examples const div1 = document.getelementbyid('div1'); const align = div1.getattribute('align'); alert(align); // shows the value of align for the element with id="div1" description lower casing when
called on an html element in a dom flagged as an html document, getattribute() lower-cases its argument before proceeding.
...consequently, you should use element.hasattribute() to check for an attribute's existence prior to
calling getattribute() if it is possible that the requested attribute does not exist on the specified element.
... retrieving nonce values for security reasons, csp nonces from non-script sources, such as css selectors, and .getattribute("nonce")
calls are hidden.
Element.getElementsByTagName() - Web APIs
the returned list is live, which means it updates itself with the dom tree automati
cally.
... therefore, there is no need to
call element.getelementsbytagname() with the same element and arguments repeatedly if the dom changes in between
calls.
... when
called on an html element in an html document, getelementsbytagname lower-cases the argument before searching for it.
Element.requestFullscreen() - Web APIs
note: this method must be
called while responding to a user interaction or a device orientation change; otherwise it will fail.
... let elem = document.queryselector("video"); if (!document.fullscreenelement) { elem.requestfullscreen().catch(err => { alert(`error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitfullscreen(); } } if the document isn't already in full-screen mode—detected by looking to see if document.fullscreenelement has a value—we
call the video's requestfullscreen() method.
... if, on the other hand, full-screen mode is already in effect, we
call document.exitfullscreen() to disable full-screen mode.
Element.shadowRoot - Web APIs
examples the following snippets are taken from our life-cycle-
callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.
... inside the <custom-square> element's class definition we include some life cycle
callbacks that make a
call to an external function, updatestyle(), which actually applies the size and color to the element.
... connected
callback() { console.log('custom square element added to page.'); updatestyle(this); } attributechanged
callback(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.cancelable - Web APIs
example for example, browser vendors are proposing that the wheel event can only be canceled the first time the listener is
called — any following wheel events cannot be canceled.
... event.preventdefault(); } else { // the event cannot be canceled, so it is not safe // to
call preventdefault() on it.
... to cancel an event,
call the preventdefault() method on the event.
Event.initEvent() - Web APIs
this method must be
called to set the event before it is dispatched, using eventtarget.dispatchevent().
...— 17notes notes before firefox 17, a
call to this method after the dispatching of the event raised an exception instead of doing nothing.ie full support yesopera full support yessafari full support yeswebview android full support yeschrome android ...
...— 17notes notes before firefox 17, a
call to this method after the dispatching of the event raised an exception instead of doing nothing.opera android full support yessafari ios full support yessamsung internet android full support yeslegend full support full supportdeprecated.
Event.stopImmediatePropagation() - Web APIs
the stopimmediatepropagation() method of the event interface prevents other listeners of the same event from being
called.
... if several listeners are attached to the same element for the same event type, they are
called in the order in which they were added.
... if stopimmediatepropagation() is invoked during one such
call, no remaining listeners will be
called.
ExtendableEvent - Web APIs
if waituntil() is
called outside of the extendableevent handler, the browser should throw an invalidstateerror; note also that multiple
calls will stack up, and the resulting promises will be added to the list of extend lifetime promises.
... it is intended to be
called in the install eventhandler for the installing worker and on the activate eventhandler for the active worker.
... examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the code
calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall, delaying treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully.
FileException - Web APIs
basic concepts synchronous apis do not have error
callbacks, which makes it difficult to catch errors.
... not_readable_err 4 the file or directory cannot be read, typi
cally due to permission problems that occur after a reference to a file has been acquired (for example, the file or directory is concurrently locked by another application).
... too many
calls are being made on file resources.
FileSystemEntry.copyTo() - Web APIs
syntax filesystementry.copyto(newparent[, newname][, success
callback][, error
callback]); parameters newparent a filesystemdirectoryentry object specifying the destination directory for the copy operation.
... success
callback optional a function which is
called when the copy operation is succesfully completed.
... error
callback optional an optional
callback which is executed if an error occurs while copying the items.
FileSystemEntry.getParent() - Web APIs
syntax filesystementry.getparent(success
callback[, error
callback]); parameters success
callback a function which is
called when the parent directory entry has been retrieved.
... the
callback receives a single input parameter: a filesystemdirectoryentry object representing the parent directory.
... error
callback optional an optional
callback which is executed if an error occurs.
FileSystemEntry.moveTo() - Web APIs
syntax filesystementry.moveto(newparent[, newname][, success
callback][, error
callback]); parameters newparent a filesystemdirectoryentry object specifying the destination directory for the move operation.
... success
callback optional a function which is
called when the move operation is succesfully completed.
... error
callback optional an optional
callback which is executed if an error occurs while moving the items.
FontFaceSet - Web APIs
events fontfaceset.onloading an eventlistener
called whenever an event of type loading is fired, indicating a font-face set has started loading.
... fontfaceset.onloadingdone an eventlistener
called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading.
... fontfaceset.onloadingerror an eventlistener
called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set.
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 ...
...t) { if (oreq.status == 200) { ooutput.innerhtml = "uploaded!"; } else { ooutput.innerhtml = "error " + oreq.status + " occurred when trying to upload your file.<br \/>"; } }; oreq.send(odata); ev.preventdefault(); }, false); note: if you pass in a reference to the form, the request method specified in the form will be used over the method specified in the open()
call.
... typi
cally this is used as shown in our simple formdata event demo — in the javascript we reference a form: const formelem = document.queryselector('form'); in our submit event handler we use preventdefault to stop the default form submission, then invoke a formdata constructor to trigger the formdata event: formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.pre...
FullscreenOptions.navigationUI - Web APIs
the fullscreenoptions dictionary's navigationui property is used when
calling requestfullscreen() to specify to what extent the user agent should include its standard user interface while the element is presented in full-screen mode.
... example in this example, the entire document is placed into full-screen mode by
calling requestfullscreen() on the document's document.documentelement, which is the document's root <html> element.
... let elem = document.documentelement; elem.requestfullscreen({ navigationui: "show" }).then({}).catch(err => { alert(`an error occurred while trying to switch into full-screen mode: ${err.message} (${err.name})`); }); the promise's resolve handler does nothing, but if the promise is rejected, an error message is displayed by
calling alert().
Geolocation.getCurrentPosition() - Web APIs
syntax navigator.geolocation.getcurrentposition(success[, error[, [options]]) parameters success a
callback function that takes a geolocationposition object as its sole input parameter.
... error optional an optional
callback function that takes a geolocationpositionerror object as its sole input parameter.
... timeout: integer (milliseconds) - amount of time before the error
callback is invoked, if 0 it will never invoke.
GeolocationCoordinates.longitude - Web APIs
currentposition(function(position) { let lat = position.coords.latitude; let long = position.coords.longitude; lattext.innertext = lat.tofixed(2); longtext.innertext = long.tofixed(2); }); }); after setting up variables to more conveniently reference the button element and the two elements into which the latitude and logitude will be drawn, the event listener is established by
calling addeventlistener() on the <button> element.
... upon receiving a click event, we
call getcurrentposition() to request the device's current position.
... this is an asynchronous request, so we provide a
callback which receives as in put a geolocationposition object describing the determined position.
GlobalEventHandlers.onanimationcancel - Web APIs
syntax var animcancelhandler = target.onanimationcancel; target.onanimationcancel = function value a function to be
called when an animationcancel event occurs indicating that a css animation has begun on the target, where the target object is an html element (htmlelement), document (document), or window (window).
... function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.innerhtml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the handlecancelevent() function, which is
called in response to the animationcancel event, as set up in the html above.
...in browsers that support animationcancel, the event is fired and this handler is
called.
GlobalEventHandlers.onpointerdown - Web APIs
if the pointerdown event isn't canceled through a
call to preventdefault(), most user agents will fire a mousedown event, so that sites not using pointer events will work.
... then the event's preventdefault() method is
called to ensure that the mousedown event isn't triggered, potentially causing events to be handled twice if we had a handler for those events in case pointer event support is missing.
... in addition, the event's preventdefault() method is
called to ensure that the mouseup event isn't triggered unnecessarily.
msAudioCategory - Web APIs
yes communications for streaming communication audio such as the following: voip real time chat or other type of phone
calls should not be used in non-real-time or non-communication scenarios, such as audio and/or video playback, as playback startup latency is affected.
... *note that if msaudiocategory is set to communications, msrealtime is automati
cally set to true.
... for hardware audio offload to be automati
cally applied, the audio category must be set to foregroundonlymedia or backgroundcapablemedia.
HTMLCanvasElement.getContext() - Web APIs
later
calls to this method on the same canvas element return the same drawing context instance as was returned the last time the method was invoked with the same contexttype argument.
... to get a different drawing context object you need to pass a different contexttype or
call the method on a different canvas element.
...this will force the use of a software (instead of hardware accelerated) 2d canvas and can save memory when
calling getimagedata() frequently.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
syntax void canvas.mozfetchasstream(
callback, type); parameters
callback an nsiinputstream
callback.
...also uses netutil.jsm 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(); var netutil
callback = function() { return function(result) { if (!components.issuccesscode(result)) { alert('failed to create icon'); } else { alert('succesfully made'); } }; } var mfas
callback = function(iconname) { return function(instream) { var file = fileutils.getfile('desk', [iconname + '.ico']); var outstream = fileutils.openfileoutputst...
...ream(file); cu.import('resource://gre/modules/netutil.jsm'); netutil.asynccopy(instream, outstream, netutil
callback()); } } canvas.mozfetchasstream(mfas
callback('myicon'), 'image/vnd.microsoft.icon'); specifications not part of any specification.
HTMLImageElement.align - Web APIs
bottom the bottom edge of the image is to be aligned verti
cally with the current text baseline.
... middle the center of the object should be aligned verti
cally with the current baseline.
... top the top edge of the object should be aligned verti
cally with the current baseline.
HTMLImageElement - Web APIs
when
called without parameters, new image() is equivalent to
calling document.createelement("img").
...this is used to turn the image into a hyperlink automati
cally.
... errors if an error occurs while trying to load or render the image, and an onerror event handler has been configured to handle the error event, that event handler will get
called.
HTMLInputElement - Web APIs
it cannot be applied if the type attribute is set to hidden (that is, you cannot automati
cally set focus to a hidden control).
... properties that apply only to text/number-containing or elements autocomplete string: returns / sets the element's autocomplete attribute, indicating whether the value of the control can be automati
cally completed by the browser.
... recommendation techni
cally, the tabindex and accesskey properties, as well as the blur(), click(), and focus() methods, are now defined on htmlelement.
HTMLMediaElement.autoplay - Web APIs
the htmlmediaelement.autoplay property reflects the autoplay html attribute, indicating whether playback should automati
cally begin as soon as enough media is available to do so without interruption.
... note: sites which automati
cally play audio (or videos with an audio track) can be an unpleasant experience for users, so it should be avoided when possible.
... if you must offer autoplay functionality, you should make it opt-in (requiring a user to specifi
cally enable it).
HTMLMediaElement: emptied event - Web APIs
the emptied event is fired when the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is
called to reload it.
...did you
call load()?'); }); using the onemptied event handler property: const video = document.queryselector('video'); video.onemptied = (event) => { console.log('uh oh.
...did you
call load()?'); }; specifications specification status html living standardthe definition of 'emptied media event' in that specification.
HTMLMediaElement: pause event - Web APIs
the pause event is sent when a request to pause an activity is handled and the activity has entered its paused state, most commonly after the media has been paused through a
call to the element's pause() method.
...either the ' + 'pause() method was
called or the autoplay attribute was toggled.'); }); using the onpause event handler property: const video = document.queryselector('video'); video.onpause = (event) => { console.log('the boolean paused property is now true.
... either the ' + 'pause() method was
called or the autoplay attribute was toggled.'); }; specifications specification status html living standardthe definition of 'pause media event' in that specification.
History - Web APIs
calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception.
...
calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception.
...
calling go() without parameters or a value of 0 reloads the current page.
IDBDatabase.deleteObjectStore() - Web APIs
as with idbdatabase.createobjectstore, this method can be
called only within a versionchange transaction.
... exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the method was not
called from a versionchange transaction
callback.
... for older webkit browsers, you must
call first.
IDBIndex - Web APIs
an index is a kind of object store for looking up records in another object store,
called the referenced object store.
...the records in an index are automati
cally populated whenever records in the referenced object store are inserted, updated, or deleted.
...when the object store changes, all indexes that refers to the object store are automati
cally updated.
IDBTransaction.commit() - Web APIs
the commit() method of the idbtransaction interface commits the transaction if it is
called on an active transaction.
... note that commit() doesn't normally have to be
called — a transaction will automati
cally commit when all outstanding requests have been satisfied and no new requests have been made.
... if it is
called on a transaction that is not active, it throws an invalidstateerror domexception.
IDBTransaction - Web APIs
transaction failures transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort
callback: abort due to bad requests, e.g.
... an explicit abort()
call from script.
...note that this doesn't normally have to be
called — a transaction will automati
cally commit when all outstanding requests have been satisfied and no new requests have been made.
Checking when a deadline is due - Web APIs
basi
cally, we want to check what the time and date is right now, and then check each stored event to see if any of their deadlines match the current time and date.
...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.
...d; getyear() is deprecated, and returns a weird value that is not much use to anyone!) var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { next we create another indexeddb objectstore, and use the opencursor() method to open a cursor, which is basi
cally a way in indexeddb to iterate through all the items in the store.
IndexedDB API - Web APIs
interfaces to get access to a database,
call open() on the indexeddb attribute of a window object.
... this method returns an idbrequest object; asynchronous operations communicate to the
calling application by firing events on idbrequest objects.
...the way to change the version of the database has since changed (by
calling idbfactory.open without also
calling idbdatabase.setversion), and the interface idbopendbrequest now has the functionality of the removed idbversionchangerequest.
IntersectionObserver.observe() - Web APIs
to stop observing the element,
call intersectionobserver.unobserve().
... when the visibility of the specified element crosses over one of the observer's visibility thresholds (as listed in intersectionobserver.thresholds), the observer's
callback is executed with an array of intersectionobserverentry objects representing the intersection changes which occurred.
... note that this design allows multiple elements' intersection changes to be processed by a single
call to the
callback.
IntersectionObserver.takeRecords() - Web APIs
the intersectionobserver method takerecords() returns an array of intersectionobserverentry objects, one for each targeted element which has experienced an intersection change since the last time the intersections were checked, either explicitly through a
call to this method or implicitly by an automatic
call to the observer's
callback.
... note: if you use the
callback to monitor these changes, you don't need to
call this method.
...
calling this method clears the pending intersection list, so the
callback will not be run.
KeyboardLayoutMap.forEach() - Web APIs
syntax keyboardlayoutmap.foreach(function
callback(currentvalue[, index[, array]]) { //your iterator }[, thisarg]); parameters
callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... array optional the keyboardlayoutmap that foreach() is being
called on.
... thisarg optional value to use as this (i.e the reference object) when executing
callback.
LocalFileSystemSync - Web APIs
calling window.requestfilesystemsync() for creates new storage for your web app.
... example //taking care of the browser-specific prefix window.requestfilesystemsync = window.requestfilesystemsync || window.webkitrequestfilesystemsync; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success
callback // and the last one is the error
callback // for denial of access and other errors.
... var fs = requestfilesystemsync(temporary, 1024*1024 /*1mb*/); because you are using a synchronous api, you don't need success and error
callbacks.
MediaPositionState.position - Web APIs
the mediapositionstate dictionary's position property is used when
calling the mediasession method setpositionstate() to provide the user agent with the current playback position, in seconds, of the currently-playing media.
... example in this example, a player for a non-standard media file format, written in javascript, uses setinterval() to establish a
callback which fires once per second to refresh the position information by
calling setpositionstate().
... if the media is still playing when the interval is fired, setpositionstate() is
called with an object that specifies the duration, playback rate, and position as reported by a mymedia object that describes the track being played.
MediaQueryListListener - Web APIs
the mediaquerylist.addlistener()
callback is now a plain function and
called with the standard mediaquerylistevent object.
... this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodi
cally, if you need to detect changes to the values of media queries on a document.
... a mediaquerylistlistener is a
callback function that gets invoked with a single argument, the mediaquerylist for which the evaluated result changed.
MediaSession.setPositionState() - Web APIs
call this method on the navigator object's mediasession object.
... example in this example, a player for a non-standard media file format, written in javascript, uses setinterval() to establish a
callback which fires once per second to refresh the position information by
calling setpositionstate().
... if the media is still playing when the interval is fired, setpositionstate() is
called with an object that specifies the duration, playback rate, and position as reported by a mymedia object that describes the track being played.
MediaSessionActionDetails.seekOffset - Web APIs
the mediasessionactiondetails dictionary's seekoffset property is an optional value passed into the action handler
callback to provide the number of seconds the seekforward and seekbackward actions should move the playback time by.
...if the offset isn't specified, the user agent will choose an appropriate offset automati
cally.
... this is typi
cally in the range of five to ten seconds.
MediaStreamConstraints.audio - Web APIs
the mediastreamconstraints dictionary's audio property is used to indicate what kind of audio track, if any, should be included in the mediastream returned by a
call to getusermedia().
...raints = true | false | mediatrackconstraints; value the value of the audio property can be specified as either of two types: boolean if a boolean value is specified, it simply indicates whether or not an audio track should be included in the returned stream; if it's true, an audio track is included; if no audio source is available or if permission is not given to use the audio source, the
call to getusermedia() will fail.
...element.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ audio: { samplesize: 8, echocancellation: true } }).then(stream => audioelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which
calls getusermedia(), specifying a set of audio constraints requesting that echo cancellation be enabled and that, if possible, the sample rate be 8 bits per sample instead of the more common 16 bits (possibly as a bandwidth saving measure).
MediaStreamConstraints.video - Web APIs
the mediastreamconstraints dictionary's video property is used to indicate what kind of video track, if any, should be included in the mediastream returned by a
call to getusermedia().
...straints = true | false | mediatrackconstraints; value the value of the video property can be specified as either of two types: boolean if a boolean value is specified, it simply indicates whether or not a video track should be included in the returned stream; if it's true, a video track is included; if no video source is available or if permission is not given to use the video source, the
call to getusermedia() will fail.
... += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: { width: 160, height: 120, framerate: 15 } }).then(stream => videoelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which
calls getusermedia(), specifying a set of video constraints that indicate a preference for a video track whose dimensions are as close as possible to 160x120 pixels, and whose frame rate is as close to 15 frames per second as possible.
MediaStreamTrack.getConstraints() - Web APIs
the getconstraints() method of the mediastreamtrack interface returns a mediatrackconstraints object containing the set of constraints most recently established for the track using a prior
call to applyconstraints().
...the properties in the returned object are listed in the same order as when they were set, and only properties specifi
cally set by the site or app are included.
...to get the currently active settings for all constrainable properties, you should instead
call getsettings().
MediaStreamTrack.onunmute - Web APIs
mediastreamtrack's onunmute event handler is
called when the unmute event is received.
... when the onunmute event handler is
called, the track's muted flag is false.
... syntax track.onunmute = unmutehandler; value unmutehandler is a function which is
called when the mediastreamtrack receives the unmute event.
MediaTrackConstraints.autoGainControl - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.autogaincontrol as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
... automatic gain control is typi
cally a feature provided by microphones, although it can be provided by other input sources as well.
MediaTrackConstraints.displaySurface - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.displaysurface as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
... usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by
calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's displaysurface object.
MediaTrackConstraints.facingMode - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.facingmode as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
... an exact value in this case indicates that the specified facing mode is specifi
cally required; for example: var constraints = { facingmode: { exact: "user" } }; this indicates that only a user-facing camera is acceptable; if there is no user-facing camera, or the user declines permission to use that camera, the media request will fail.
MediaTrackConstraints.logicalSurface - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.logicalsurface as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
... usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by
calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's logicalsurface object.
MediaTrackConstraints.noiseSuppression - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.noisesuppression as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
... noise suppression is typi
cally provided by microphones, although it can be provided by other input sources as well.
MediaTrackSettings.aspectRatio - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.aspectratio property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.aspectratio as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.channelCount - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.channelcount property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.channelcount as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.echoCancellation - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.echocancellation property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.echocancellation as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.facingMode - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.facingmode property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.facingmode as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.frameRate - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.framerate property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.framerate as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.height - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.height property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.height as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.latency - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.latency property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.latency as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.sampleRate - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.samplerate property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplerate as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.sampleSize - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.samplesize property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplesize as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.volume - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.volume property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.volume as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSettings.width - Web APIs
this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.width property you provided when
calling either getusermedia() or mediastreamtrack.applyconstraints().
... if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.width as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackSupportedConstraints.cursor - Web APIs
the supported constraints list is obtained by
calling navigator.mediadevices.getsupportedconstraints().
... example this method sets up the constraints object specifying the options for the
call to getdisplaymedia().
...capturing is then started by
calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
MediaTrackSupportedConstraints.displaySurface - Web APIs
the supported constraints list is obtained by
calling navigator.mediadevices.getsupportedconstraints().
... example this method sets up the constraints object specifying the options for the
call to getdisplaymedia().
...capturing is then started by
calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
MediaTrackSupportedConstraints.logicalSurface - Web APIs
the supported constraints list is obtained by
calling navigator.mediadevices.getsupportedconstraints().
... example this method sets up the constraints object specifying the options for the
call to getdisplaymedia().
...capturing is then started by
calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
MerchantValidationEvent.complete() - Web APIs
all you have to do is
call complete() from your handler for the merchantvalidation event, passing in the data fetched from the validationurl.
... example in this example, we see the client-side code needed to support merchant validation for a payment request
called payrequest: payrequest.onmerchantvalidation = event => { const validationdatapromise = getvalidationdata(event.validationurl); event.complete(validationdatapromise); } function getvalidationdata(url) { /* ...retrieve the validation data from the url...
...the event handler
calls a function, getvalidationdata(), which retrieves the data from the validation url, then passes that data (or a promise to deliver the data) into complete().
MutationObserverInit.attributeFilter - Web APIs
function
callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": switch(mutation.attributename) { case "status": userstatuschanged(mutation.target.username, mutation.target.status); break; case "username": usernamechanged(mutation.oldvalue, mutation.target.username); bre...
...ak; } 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.
... when observe() is
called, the specified options include both attributefilter and subtree, so that we monitor the attribute values for all of the nodes contained within the subtree rooted at the node with the id "userlist".
MutationObserverInit.characterData - Web APIs
syntax var options = { characterdata: true | false } value a boolean value indicating whether or not to
call the observer's
callback function when textual nodes' values change.
... if true, the
callback specified when observe() was used to start observing the node or subtree is
called any time the contents of a text node are changed.
... if you set characterdataoldvalue to true, characterdata is automati
cally assumed to be true, even if you don't expressly set it as such.
MutationObserverInit.childList - Web APIs
if childlist is false (the default), adding or removing new nodes does not trigger mutation
callbacks.
... by setting childlist to true, your
callback will be invoked any time nodes are added to or removed from the dom node or nodes being watched.
... 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..
Web-based protocol handlers - Web APIs
basi
cally, the web application uses registerprotocolhandler() to register itself with the browser as a potential handler for a given protocol.
...therefore, it is a good idea to guard your
call to register the protocol handler with a check to see if it is already registered, such as in the example below.
... example <?php $value = ""; if ( isset ( $_get["value"] ) ) { $value = $_get["value"]; } ?> <!doctype html public "-//w3c//dtd html 4.01//en"> <html lang="en"> <head> <title>web protocol handler sample</title> </head> <body> <h1>web protocol handler sample - handler</h1> <p>this web page is
called when handling a <code>web+burger:</code> protocol action.
Navigator.sendBeacon() - Web APIs
ensuring that data has been sent during the unloading of a document has traditionally been difficult, because user agents typi
cally ignore asynchronous xmlhttprequests made in an unload handler.
... histori
cally, this was addressed with some of the following workarounds to delay the page unload long enough to send data to some url: submitting the data with a blocking synchronous xmlhttprequest
call in unload or beforeunload event handlers.
... window.addeventlistener("unload", function logdata() { navigator.sendbeacon("/log", analyticsdata); }); the beacon sends an http request via the post method, with all relevant cookies available when
called.
Node.removeChild() - Web APIs
in the second syntax form, however, there is no oldchild reference kept, so assuming your code has not kept any other reference to the node elsewhere, it will immediately become unusable and irretrievable, and will usually be automati
cally deleted from memory after a short time.
...this will also happen if child was in fact a child of element at the time of the
call, but was removed by an event handler invoked in the course of trying to remove the element (e.g., blur.) errors thrown the method throws an exception in 2 different ways: if the child was in fact a child of element and so existing on the dom, but was removed the method throws the following exception: uncaught notfounderror: failed to execute 'removechild' on 'node': the node to be removed is not a child of this node.
....getelementbyid("top"); let nested = document.getelementbyid("nested"); // throws uncaught typeerror let garbage = top.removechild(nested); </script> causing a notfounderror <!--sample html code--> <div id="top"> <div id="nested"></div> </div> <script type="text/javascript"> let top = document.getelementbyid("top"); let nested = document.getelementbyid("nested"); // this first
call correctly removes the node let garbage = top.removechild(nested); // throws uncaught notfounderror garbage = top.removechild(nested); </script> specifications specification status comment domthe definition of 'node: removechild' in that specification.
OscillatorNode.type - Web APIs
doing so automati
cally sets the type to custom.
...to set a custom waveform, just
call setperiodicwave().
... doing so automati
cally sets the type for you.
PaintWorklet - Web APIs
the paintworklet interface of the css painting api programmati
cally generates an image where a css property expects a file.
... paintworklet.registerpaint() registers a class programmati
cally generate an image where a css property expects a file.
...note that registerpaint() is
called without a reference to paintworklet.
PaymentDetailsUpdate - Web APIs
this can be done either by
calling the paymentrequestupdateevent.updatewith() method or by using the paymentrequest.show() method's detailspromise parameter to provide a promise that returns a paymentdetailsupdate that updates the payment information before the user interface is even enabled for the first time.
...when
calling updatewith(), including error in the updated data causes the user agent to display the text as a general error message.
...this is not calculated automati
cally.
PaymentRequest.onpaymentmethodchange - Web APIs
}; value an event handler function which is to be
called whenever the paymentmethodchange event is fired at the paymentrequest, indicating that the user has changed payment methods within the same payment handler.
...to make sure you receive the event, you should add event listeners to paymentrequest object after instantiation, but before you
call show().
... examples an example payment method change handler is shown below; this example handles changes made to the payment method when using apple pay, specifi
cally: 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...
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.
...= {}; if (event.methodname === "https://apple.com/apple-pay") { const servicefeeinfo = calculateservicefee(event.methoddetails); object.assign(detailsupdate, servicefeeinfo); } event.updatewith(detailsupdate); }, false); this begins by looking at the event's methodname property; if that indicates that the user is trying to use apple pay, we pass the methoddetails into a function
called calculateservicefee(), which we might create to take the information about the transaction, such as the underlying credit card being used to service the apple pay request, and compute and return an paymentdetailsupdate object that specifies changes to be applied to the paymentrequest in order to add any service fees that the payment method might require.
... before the event handler returns, it
calls the event's paymentmethodchangeevent.updatewith.updatewith() method to integrate the changes into the request.
PaymentResponse.complete() - Web APIs
this method must be
called after the user accepts the payment request and the promise returned by the paymentrequest.show() method is resolved.
... invalidstateerror the payment has already completed, or complete() was
called while a request to retry the payment is pending.
...it
calls complete() with an answer appropriate to the status in the response.
PaymentResponse.onpayerdetailchange - Web APIs
the paymentresponse object's onpayerdetailchange property is an event handler which is
called to handle the payerdetailchange event, which is sent to the paymentresponse when the user makes changes to their personal information while filling out a payment request form.
... syntax paymentresponse.onpayerdetailchange = eventhandlerfunction; value an event handler function which is
called to handle the payerdetailchange event when the user makes changes to their personal information while editing a payment request form.
... response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payername, payeremail, payerphone } = response; // validate each value which changed by
calling a function // that validates each type of data, returning a promise which // resolves if the data is valid.
PerformanceEventTiming - Web APIs
this typi
cally happens when a // page is loaded in a background tab.
... sendtoanalytics({fid}); } } // create a performanceobserver that
calls `onfirstinputentry` for each entry.
...entries that occurred before
calling `observe()` below.
PerformanceMark - Web APIs
entries of this type are created by
calling performance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline.
... performanceentry.name returns the name given to the mark when it was created via a
call to performance.mark().
... performanceentry.starttime returns the domhighrestimestamp when performance.mark() was
called.
Performance API - Web APIs
entries of this type are created by
calling performance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline.
...entries of this type are created by
calling performance.measure() to add a nameddomhighrestimestamp (the measure) between two marks to the browser's performance timeline.
... performance timeline level 2 candidate recommendation adds serializer to the performanceentry interface as well as adding the performanceobserver interface and
callback resource timing level 1 candidate recommendation adds the performanceresourcetiming interface.
Using Performance Timeline - Web APIs
} // print the performanceentry object var json = pe.tojson(); var s = json.stringify(json); log("performanceentry.tojson = " + s); } performance observers the performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's
callback function that was specified at the time, the observer was created.
... when the observer (
callback) is invoked the
callback's parameters include a performance observer entry list that only contains observed performance entries.
...); } function print_perf_entry(pe) { log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } the performance observer entry list interface has the same three getentries*() methods as the performance interface and these methods are used to retrieve observed performance entries within the observer
callback.
PromiseRejectionEvent.promise - Web APIs
examples this example listens for unhandled promises and, if the reason is an object with a code field containing the text "module not ready", it sets up an idle
callback that will retry the task that failed to execute correctly.
... event.preventdefault() is
called to indicate that the promise has now been handled.
... window.onunhandledrejection = function(event) { if (event.reason.code && event.reason.code == "module not ready") { window.requestidle
callback(function(deadline) { loadmodule(event.reason.modulename) .then(performstartup); }); event.preventdefault(); } } specifications specification status comment html living standardthe definition of 'promiserejectionevent.promise' in that specification.
PushManager.unregister() - Web APIs
return a domrequest object to handle the success or failure of the method
call.
... if the method
call is successful, the request's result will be a pushregistration object representing the endpoint that has been unregistered.
... version undefined when unregister.onsuccess is
called.
RTCDTMFSender.toneBuffer - Web APIs
to place tones into the buffer,
call insertdtmf().
...lower-case "a"-"d" automati
cally gets converted to upper-case.
... the pound/hash sign ("#") and the asterisk ("*") these correspond to the similarly-labeled keys which are typi
cally on the bottom row of the telephone keypad.
RTCDataChannel.onbufferedamountlow - Web APIs
the rtcdatachannel.onbufferedamountlow property is an eventhandler which specifies a function the browser
calls when the bufferedamountlow event is sent to the rtcdatachannel.
... syntax rtcdatachannel.onbufferedamountlow = function; value a function which the browser will
call to handle the bufferedamountlow event.
... example this example responds to the bufferedamountlow event by fetching up to 64kb of a file represented by an object source and
calling rtcdatachannel.send() to queue up the retrieved data for sending on the data channel.
RTCDataChannel.onclosing - Web APIs
the rtcdatachannel.onclosing property is an eventhandler which specifies a function to be
called by the browser when the closing event is received by the rtcdatachannel.
...for example, after rtcdatachannel.close() was
called but the underlying data transport might not have been closed yet.
... syntax rtcdatachannel.onclosing = function; value a function which the browser will
call to handle the closing event.
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.
... the event handler can determine the current state by
calling the transport's getselectedcandidatepair() method, which returns a rtcicecandidatepair whose rtcicecandidatepair.local and rtcicecandidatepair.global properties specify rtcicecandidate objects describing the local and remote candidates that are currently being used.
RTCInboundRtpStreamStats - Web APIs
this id is stable across multiple
calls to getstats().
...this id is stable across multiple
calls to getstats().
...this id is stable across multiple
calls to getstats().
RTCPeerConnection.createDataChannel() - Web APIs
negotiated optional by default (false), data channels are negotiated in-band, where one side
calls createdatachannel, and the other side listens to the rtcdatachannelevent event using the ondatachannel eventhandler .
... alternatively (true), they can be negotiated out of-band, where both sides
call createdatachannel with an agreed-upon id.
... operationerror either the specified id is already in use or, if no id was specified, the webrtc layer was unable to automati
cally generate an id because all ids are in use.
RTCPeerConnection.getConfiguration() - Web APIs
the rtcpeerconnection.getconfiguration() method returns an rtcconfiguration object which indicates the current configuration of the rtcpeerconnection on which the method is
called.
... the returned configuration is the last configuration applied via setconfiguration(), or if setconfiguration() hasn't been
called, the configuration the rtcpeerconnection was constructed with.
... 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: iceconnectionstatechange event - Web APIs
usage notes a successful connection attempt will typi
cally involve the state starting at new, then transitioning through checking, then connected, and finally completed.
... in this example, a handler for iceconnectionstatechange is set up to update a
call state indicator by using the value of iceconnectionstate to create a string which corresponds to the name of a css class that we can assign to the status indicator to cause it to reflect the current state of the connection.
... pc.addeventlistener("iceconnectionstatechange", ev => { let stateelem = document.queryselector("#
call-state"); stateelem.classname = `${pc.iceconnectionstate}-state`; }, false); this can also be written as: pc.oniceconnectionstatechange = ev => { let stateelem = document.queryselector("#
call-state"); stateelem.classname = `${pc.iceconnectionstate}-state`; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'iceconnectionstatechange' in that specification.
RTCPeerConnection: icecandidate event - Web APIs
an icecandidate event is sent to an rtcpeerconnection when an rtcicecandidate has been identified and added to the local peer by a
call to rtcpeerconnection.setlocaldescription().
... rtcpeerconnection.onicecandidate = (event) => { if (event.candidate) { sendcandidatetoremotepeer(event.candidate) } else { /* there are no more candidates coming during this negotiation */ } } the remote peer, upon receiving the candidate, will add the candidate to its candidate pool by
calling addicecandidate(), passing in the candidate string you have passed along using the signaling server.
... examples this example creates a simple handler for the icecandidate event that uses a function
called sendmessage() to create and send a reply to the remote peer through the signaling server.
RTCPeerConnection: negotiationneeded event - Web APIs
see signaling transaction flow in signaling and video
calling for a description of the signaling process that begins with a negotiationneeded event.
... pc.addeventlistener("negotiationneeded", ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }, false); after creating the offer, the local end is configured by
calling rtcpeerconnection.setlocaldescription(); then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer.
...er function to the rtcpeerconnection.onnegotiationneeded property: pc.onnegotiationneeded = ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }; for a more detailed example, see starting negotiation in signaling and video
calling.
RTCPeerConnection.onnegotiationneeded - Web APIs
the rtcpeerconnection interface's onnegotiationneeded property is an eventlistener which specifies a function which is
called to handle the negotiationneeded event when it occurs on an rtcpeerconnection instance.
... example this example, derived from the example in signaling and video
calling, establishes a handler for negotiationneeded events to handle creating an offer, configuring the local end of the connection, and sending the offer to the remote peer.
... pc.onnegotiationneeded = function() { pc.createoffer().then(function(offer) { return pc.setlocaldescription(offer); }) .then(function() { // send the offer to the remote peer through the signaling server }); }) .catch(reporterror); } first, it creates the offer by
calling createoffer().
RTCPeerConnection.onsignalingstatechange - Web APIs
the onsignalingstatechange event handler property of the rtcpeerconnection interface specifies a function to be
called when the signalingstatechange event occurs on an rtcpeerconnection interface.
... the function receives as input the event object of type event; this event is sent when the peer connection's signalingstate changes, which may happen either because of a
call to setlocaldescription() or to setremotedescription().
... pc.onsignalingstatechange = function(event) { if (pc.signalingstate === "have-local-pranswer") { // setlocaldescription() has been
called with an answer } }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.onsignalingstatechange' in that specification.
RTCPeerConnection.ontrack - Web APIs
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.
... example this example, taken from the code for the article signaling and video
calling, connects the incoming track to the <video> element which will be used to display the incoming video.
...the second line of code simply enables a "hang up" button, which the user can use to disconnect from the
call.
RTCPeerConnection.setConfiguration() - Web APIs
if, for example, the rtcpeerconnection() constructor was
called with no parameters, you would have to then
call setconfiguration() to add ice servers before ice negotiation could begin.
...in this situation, one might
call setconfiguration() to switch to new regional ice servers, then initiate an ice restart.
...ice negotiation is restarted by
calling createoffer(), specifying true as the value of the icerestart option.
RTCRtpReceiver.getCapabilities() static function - Web APIs
you can, similarly, obtain the capabilities of rtcrtpsenders by
calling the static function rtcrtpsender.getcapabilities().
... description as a static function, this is always
called using the form: capabilities = rtcrtpreceiver.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list.
...
calling rtcrtpreceiver.getcapabilities() doesn't prime the browser in any way to handle media.
RTCRtpSender.getCapabilities() static function - Web APIs
you can, similarly, obtain the capabilities of rtcrtpreceivers by
calling the static function rtcrtpreceiver.getcapabilities().
... description as a static function, this is always
called using the form: capabilities = rtcrtpsender.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list.
...
calling rtcrtpsender.getcapabilities() doesn't prime the browser in any way to handle media.
RTCStatsReport - Web APIs
the rtcstatsreport interface provides a statistics report obtained by
calling one of the rtcpeerconnection.getstats(), rtcrtpreceiver.getstats(), and rtcrtpsender.getstats() methods.
...
calling getstats() on an rtcpeerconnection lets you specify whether you wish to obtain statistics for outbound, inbound, or all streams on the connection.
... the rtcrtpreceiver and rtcrtpsender versions of getstats() specifi
cally only return statistics available to the incoming or outgoing stream on which you
call them.
RTCTrackEvent - Web APIs
this event is sent by the webrtc layer to the web site or application, so you will not typi
cally need to instantiate an rtctrackevent yourself.
...you will probably not need to create new track events yourself, since they're typi
cally created by the webrtc infrastructure and sent to the connection's ontrack event handler.
... note: it may be helpful to keep in mind that you receive the track event when a new inbound track has been added to your connection, and you
call addtrack() to add a track to the far end of the connection, thereby triggering a track event on the remote peer.
ReadableStreamDefaultController - Web APIs
readablestreamdefaultcontroller instances are created automati
cally during readablestream construction.
...a cancel() function is also provided to stop the generation if readablestream.cancel() is
called for any reason.
...it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is
called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'readablestreamdefaultcontroller' in that specification.
Report - Web APIs
via the reports parameter of the
callback function passed into the reportingobserver() constructor upon creation of a new observer instance.
...f 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 the reportingobserver() constructor, we can now click the button to display the report details.
... the report details are displayed via the displayreports() fuction, which takes the observer
callback's reports parameter as its parameter: function displayreports(reports) { const outputelem = document.queryselector('.output'); const list = document.createelement('ul'); outputelem.appendchild(list); for(let i = 0; i < reports.length; i++) { let listitem = document.createelement('li'); let textnode = document.createtextnode('report ' + (i + 1) + ', type: ' + reports[i].type); listitem.appendchild(textnode); let innerlist = document.createelement('ul'); listitem.appendchild(innerlist); list.appendchild(listitem); for (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; in...
ReportingObserver - Web APIs
f 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 the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constraints, success, failure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be gene...
... note: if you look at the complete source code, you'll notice that we actually
call the deprecated getusermedia() method twice.
... after the first time we
call reportingobserver.takerecords(), which returns the first generated report and empties the queue.
Request - Web APIs
note: the body functions can be run only once; subsequent
calls will resolve with empty strings/arraybuffers.
...tor (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 a windoworworkerglobalscope.fetch()
call, for example: fetch(request) .then(response => response.blob()) .then(blob => { image.src = url.createobjecturl(blob); }); in the following snippet, we create a new request using the request() constructor with some initial data and body content for an api request which need a body payload: const request = new request('https://example.com', {method: 'post', body: '{"foo": "bar"}'}); ...
... you could then fetch this api request by passing the request object in as a parameter to a windoworworkerglobalscope.fetch()
call, for example and get the response: fetch(request) .then(response => { if (response.status === 200) { return response.json(); } else { throw new error('something went wrong on api server!'); } }) .then(response => { console.debug(response); // ...
Using the Resource Timing API - Web APIs
performance.setresourcetimingbuffersize() = not supported"); } } the performance interface has a onresourcetimingbufferfull event handler that gets
called (with an event of type event.type of "resourcetimingbufferfull") when the browser's resource performance entry buffer is full.
... the following code example sets a onresourcetimingbufferfull event
callback in the init() function.
...arning: 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' values are returned as zero unless the server's access policy permits these values to be shared.
SVGAngle - Web APIs
setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automati
cally to reflect this setting.
...setting this attribute will cause value and valueasstring to be updated automati
cally to reflect this setting.
...setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automati
cally to reflect this setting.
SVGLength - Web APIs
setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automati
cally to reflect this setting.
...setting this attribute will cause value and valueasstring to be updated automati
cally to reflect this setting.
...setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automati
cally to reflect this setting.
Selection API - Web APIs
document.getselection() is basi
cally an alias of window.getselection().
... globaleventhandlers.onselectstart represents the event handler that is
called when a selectstart event is fired on the current object (i.e.
... globaleventhandlers.onselectionchange represents the event handler that is
called when a selectionchange event is fired on the current object (i.e.
Sensor - Web APIs
event handlers sensor.onerror
called when an error occurs on one of the child interfaces of the sensor interface.
... sensor.onreading
called when a reading is taken on one of the child interfaces of the sensor interface.
... sensor.onactivate
called when one of the sensor interface's becomes active.
Sensor APIs - Web APIs
alternatively, the absoluteorientationsensor interface provides information that is algorithmi
cally agregated from two or more device sensors.
...the latter type of sensor is also
called a fusion sensor (alternatively, virtual or synthetic sensors).
...gyroscope', and 'magnetometer' accelerometer 'accelerometer' ambientlightsensor 'ambient-light-sensor' gyroscope 'gyroscope' linearaccelerationsensor 'accelerometer' magnetometer 'magnetometer' relativeorientationsensor 'accelerometer', and 'gyroscope' readings sensor readings are received through the sensor.onreading
callback which is inherited by all sensor types.
ServiceWorkerGlobalScope - Web APIs
an active service worker is automati
cally restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage.
... fetch occurs when a fetch() is
called.
... sync triggered when a
call to syncmanager.register is made from a service worker client page.
ShadowRoot - Web APIs
examples the following snippets are taken from our life-cycle-
callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.
... inside the <custom-square> element's class definition we include some life cycle
callbacks that make a
call to an external function, updatestyle(), which actually applies the size and color to the element.
... connected
callback() { console.log('custom square element added to page.'); updatestyle(this); } attributechanged
callback(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.
Storage - Web APIs
to manipulate, for instance, the session storage for a domain, a
call to window.sessionstorage is made; whereas for local storage the
call is made to window.localstorage.
... examples here we access a storage object by
calling localstorage.
...if it does, we run a function
called setstyles() that grabs the data items using storage.getitem() and uses those values to update page styles.
StylePropertyMapReadOnly.forEach() - Web APIs
syntax stylepropertymapreadonly.foreach(function
callback(currentvalue[, index[, array]]) { //your code }[, thisarg]); parameters
callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... arrayoptional the stylepropertymapreadonly thatforeach() is being
called on.
... thisarg optional value to use as this (i.e the reference object) when executing
callback.
SubtleCrypto - Web APIs
the difference is that generatekey() will generate a new distinct key value each time you
call it, while derivekey() derives a key from some initial keying material.
... if you provide the same keying material to two separate
calls to derivekey(), you will get two cryptokey objects that have the same underlying value.
... if the key is sensitive you should use wrapkey(), which exports the key and then encrypts it using another key; the api
calls a "key-wrapping key".
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.
... 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.
... example this snippet establishes a handler for the addtrack event that
calls a function, addtotracklist(), passing in the videotrack object representing the newly-added track.
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.
... onchange an event handler to be
called when the change event occurs.
... onremovetrack an event handler to
call when the removetrack event is sent, indicating that a text track has been removed from the media element.
TouchEvent - Web APIs
if you use touch events, you should
call preventdefault() to keep the mouse event from being sent as well.
... the exception to this is chrome, starting with version 56 (desktop, chrome for android, and android webview), where the default value for the passive option for touchstart and touchmove is true and
calls to preventdefault() will have no effect.
... to override this behavior, you need to set the passive option to false, after which
calling preventdefault() will work as specified.
Supporting both TouchEvent and MouseEvent - Web APIs
consequently, if an application does not want mouse events fired on a specific touch target element, the element's touch event handlers should
call preventdefault() and no additional mouse events will be dispatched.
... here is a code snippet of the touchmove event handler
calling preventdefault().
... // touchmove handler function process_touchmove(ev) { //
call preventdefault() to prevent any further handling ev.preventdefault(); } event order although the specific ordering of touch and mouse events is implementation-defined, the standard indicates the following order is typical: for single input: touchstart zero or more touchmove events, depending on movement of the finger(s) touchend mousemove mousedown mouseup click if the touchstart, touchmove or touchend event is canceled during an interaction, no mouse or click events will be fired, and the resulting sequence of events would just be: touchstart zero or more touchmove events, depending on movement of the finger(s) touchend community touch events community group mail list w3c #touchevents irc channel r...
URL.revokeObjectURL() - Web APIs
the url.revokeobjecturl() static method releases an existing object url which was previously created by
calling url.createobjecturl().
...
call this method when you've finished using an object url to let the browser know not to keep the reference to the file any longer.
... syntax url.revokeobjecturl(objecturl) parameters objecturl a domstring representing a object url that was previously created by
calling createobjecturl().
USB - Web APIs
event handlers usb.onconnect an event handler
called whenever a previously paired device is connected.
... usb.ondisconnect an event handler
called whenever a paired device is disconnected.
...
calling this function triggers the user agent's pairing flow.
UserDataHandler - Web APIs
summary when associating user data with a key on a node, node.setuserdata() can also accept, in its third argument, a handler which will be
called when the object is cloned, imported, deleted, renamed, or adopted.
...in both document.importnode() and node.clonenode(), although user data is not copied over, the handler will be
called.
... methods handle (operation, key, data, src, dst) (no return value) this method is a
callback which will be
called if a node is being cloned, imported, renamed and as well, if deleted or adopted.
Using the User Timing API - Web APIs
creating a performance measure a measure is created by
calling performance.measure(measurename, startmarkname, endmarkname) where measurename is the measure's name and startmarkname and endmarkname are the start and end names, respectively, of the marks the measure will be placed between (in the performance timeline).
...if the method is
called with a specific measure name, all measures with that name will be removed from the timeline.
... if the method is
called with no arguments, all performance entries with a type of "measure" will be removed from the timeline.
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.
... 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.
... example this snippet establishes a handler for the addtrack event that
calls a function, addtotracklist(), passing in the videotrack object representing the newly-added track.
VideoTrackList.onchange - Web APIs
the videotracklist property onchange is an event handler which is
called when the change event occurs, indicating that a videotrack in the videotracklist has been made active.
... syntax videotracklist.onchange = eventhandler; value set onchange to a function that should be
called whenever a track is made active.
... example this snippet establishes a handler for the change event that looks at each of the tracks in the list,
calling a function to update the state of a user interface control that indicates the current state of the track.
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.
... onchange an event handler to be
called when the change event occurs — that is, when the value of the selected property for a track has changed, due to the track being made active or inactive.
... onremovetrack an event handler to
call when the removetrack event is sent, indicating that a video track has been removed from the media element.
Clearing with colors - Web APIs
next, we actually do the drawing by
calling the clear() method.
...this is why webgl/opengl is often
called a state machine.
...this is // the function
call that actually does the drawing.
Simple color animation - Web APIs
this time we put the webgl function
calls within a timer event handler.
...the timer and the timer handler function establish the animation loop, a set of drawing commands that are executed at a regular period (typi
cally, every frame; in this case, once per second).
... clearinterval(timer); } //
call stopanimation() once to setup the initial event // handlers for canvas and button.
WebGL constants - Web APIs
link_status 0x8b82 passed to getprogramparameter after
calling linkprogram to determine if a program was linked correctly.
... validate_status 0x8b83 passed to getprogramparameter after
calling validateprogram to determine if it is valid.
... attached_shaders 0x8b85 passed to getprogramparameter after
calling attachshader to determine if the shader was attached correctly.
WebRTC Statistics API - Web APIs
most broadly, you can
call getstats() on an rtcpeerconnection to get statistics for the connection overall.
... in this example, a new rtcpeerconnection is created, and then setinterval() is used to set the function getconnectionstats() to be
called every second.
... this example specifi
cally looks for the report whose type is inbound-rtp and whose kind is video.
Basic concepts behind Web Audio API - Web APIs
this is
called channel notation.
... if you use this
call above, you will get a stereo buffer with 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 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 automati
cally resampled to 44100hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames/44100hz = 1 second.
window.cancelAnimationFrame() - Web APIs
the window.cancelanimationframe() method cancels an animation frame request previously scheduled through a
call to window.requestanimationframe().
... syntax window.cancelanimationframe(requestid); parameters requestid the id value returned by the
call to window.requestanimationframe() that requested the
callback.
... var myreq; function step(timestamp) { var progress = timestamp - start; d.style.left = math.min(progress / 10, 200) + 'px'; if (progress < 2000) { // it's important to update the requestid each time you're
calling requestanimationframe myreq = requestanimationframe(step); } } myreq = requestanimationframe(step); // the cancelation uses the last requestid cancelanimationframe(myreq); specifications specification status comment html living standardthe definition of 'cancelanimationframe()' in that specification.
Window.setImmediate() - Web APIs
this method is used to break up long running operations and run a
callback function immediately after the browser has completed other operations such as events and display updates.
... func is the function you wish to
call.
... the feature can be emulated in a few different ways: postmessage can be used to trigger an immediate but yielding
callback.
Window: unhandledrejection event - Web APIs
the unhandledrejection event is sent to the global scope of a script when a javascript promise that has no rejection handler is rejected; typi
cally, this is the window, but may also be a worker.
...you can prevent this by
calling preventdefault() on the promiserejectionevent; see preventing default handling below for an example.
...you can prevent that from happening by adding a handler for unhandledrejection events that—in addition to any other tasks you wish to perform—
calls preventdefault() to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code.
WindowOrWorkerGlobalScope.clearInterval() - Web APIs
the clearinterval() method of the windoworworkerglobalscope mixin cancels a timed, repeating action which was previously established by a
call to setinterval().
...this id was returned by the corresponding
call to setinterval().
... it's worth noting that the pool of ids used by setinterval() and settimeout() are shared, which means you can techni
cally use clearinterval() and cleartimeout() interchangeably.
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
the cleartimeout() method of the windoworworkerglobalscope mixin cancels a timeout previously established by
calling settimeout().
...this id was returned by the corresponding
call to settimeout().
... it's worth noting that the pool of ids used by settimeout() and setinterval() are shared, which means you can techni
cally use cleartimeout() and clearinterval() interchangeably.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
syntax scope.queuemicrotask(function); parameters function a function to be executed when the browser engine determines it is safe to
call your code.
... { 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 basi
cally a monkey-patch for queuemicrotask() for modern engines.
... if (typeof window.queuemicrotask !== "function") { window.queuemicrotask = function (
callback) { promise.resolve() .then(
callback) .catch(e => settimeout(() => { throw e; })); // report exceptions }; } specifications specification status comment html living standardthe definition of 'self.queuemicrotask()' in that specification.
Worker.onmessage - Web APIs
the onmessage property of the worker interface represents an eventhandler, that is a function to be
called when the message event occurs.
... these events are of type messageevent and will be
called when the worker's parent receives a message (i.e.
...ceived from worker'); } in the worker.js script, an onmessage handler is used to the handle messages from the main script: onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); console.log('posting message back to main script'); postmessage(workerresult); } notice how in the main script, onmessage has to be
called on myworker, whereas inside the worker script you just need onmessage because the worker is effectively the global scope (dedicatedworkerglobalscope).
WorkerGlobalScope.console - Web APIs
so for example you could
call console.log('test'); inside a worker (which would basi
cally be the equivalent of self.console.log('test');, as these are being
called on the worker scope, which can be referenced with workerglobalscope.self), to return a test message out to the browser console.
... if you are
calling console.log() from a dedicatedworkerglobalscope or other worker scope that acts on a single loaded window, that tab's web console will receive the logs.
... however, if you are
calling console.log() from a sharedworkerglobalscope, the global browser console will receive the logs.
XDomainRequest.onprogress - Web APIs
this method is
called periodi
cally as an event handler for progress events on xdomainrequests, so that code can monitor progress while loading content.
... once loading is complete, the xdomainrequest.onload event handler gets
called.
... syntax xdr.onprogress = funcref; parameters funcref a function to
call when progress events occur.
HTML in XMLHttpRequest - Web APIs
usage retrieving an html resource as a dom using xmlhttprequest works just like retrieving an xml resource as a dom using xmlhttprequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responsetype property of the xmlhttprequest object after
calling open() but before
calling send().
...this test file is small and is not well-formed xml: <title>&&<</title> if the file is named detect.html, the following function can be used for detecting html parsing support: function detecthtmlinxhr(
callback) { if (!window.xmlhttprequest) { window.settimeout(function() {
callback(false); }, 0); return; } var done = false; var xhr = new window.xmlhttprequest(); xhr.onreadystatechange = function() { if (this.readystate == 4 && !done) { done = true;
callback(!!(this.responsexml && this.responsexml.title && this.responsexml.title == "&&<")); } } xhr.onabort =...
... xhr.onerror = function() { if (!done) { done = true;
callback(false); } } try { xhr.open("get", "detect.html"); xhr.responsetype = "document"; xhr.send(); } catch (e) { window.settimeout(function() { if (!done) { done = true;
callback(false); } }, 0); } } the argument
callback is a function that will be
called asynchronously with true as the only argument if html parsing is supported and false as the only argument if html parsing is not supported.
XMLHttpRequest.overrideMimeType() - Web APIs
this method must be
called before
calling send().
...you can avoid this by
calling overridemimetype() to specify a different type.
... // 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.response - Web APIs
you may attempt to request the data be provided in a specific format by setting the value of responsetype after
calling open() to initialize the request but before
calling send() to send the request to the server.
...it works by creating an xmlhttprequest object and creating a listener for readystatechange events such that that when readystate changes to done (4), the response is obtained and passed into the
callback function provided to load().
... 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 ...
XMLHttpRequestEventTarget.onload - Web APIs
the xmlhttprequesteventtarget.onload is the function
called when an xmlhttprequest transaction completes successfully.
... syntax xmlhttprequest.onload =
callback; values
callback is the function to be executed when the request completes successfully.
...the context) is the same xmlhttprequest this
callback is related to.
XRInputSourceEvent.frame - Web APIs
usage notes the event frame does not correspond to a visual frame as is delivered to the frame rendering
callback function (see rendering and the webxr frame rendering
callback for details on the
callback).
... however, since the event frame isn't an animation frame, there is no viewer pose available to represent the viewer's current point of view; the results of
calling getviewerpose() will be an xrviewerpose with an empty views list.
... then, if the result isn't null, the target ray pose's transform is passed into a function
called mycheckandhandlehit() to see if the ray was pointing at anything when the select was triggered.
XRPermissionDescriptor.requiredFeatures - Web APIs
the xrpermissiondescriptor dictionary's requiredfeatures property should be set prior to
calling navigator.permissions.query() to a list of webxr features which must be supported for the app to work.
...this is used for environments in which the user can physi
cally move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions.
...otherwise, typi
cally, one of the other reference space types will be used more often.
XRPermissionStatus.granted - Web APIs
the webxr device api's xrpermissionstatus interface's granted property is an array of strings, each identifying one of the webxr features for which permission has been granted as of the time at which the permission api's navigator.permissions.query() method was
called.
...this is used for environments in which the user can physi
cally move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions.
...otherwise, typi
cally, one of the other reference space types will be used more often.
XRPermissionStatus - Web APIs
the xrpermissionstatus interface defines the object returned by
calling navigator.permissions.query() for the xr permission name; it indicates whether or not the app or site has permission to use webxr, an may be monitored over time for changes to that permissions tate.
... granted an array of strings listing the names of the features for which permission has been granted as of the time at which navigator.permissions.query() was
called.
... any feature which was specified in either the optionalfeatures or requiredfeatures when
calling navigator.permissions.query() are listed in granted if and only if permission to use them is granted.
XRPose.transform - Web APIs
the transform read-only attribute of the xrpose interface is a xrrigidtransform object providing the position and orientation of the pose relative to the base xrspace as specified when the pose was obtained by
calling xrframe.getpose().
...it determines the targeted object by passing the event frame's pose into a function
called findtargetusingray(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the xrinputsource property handedness to a value in the variable user.handedness.
... if the source is a controller in the user's primary hand, a function is
called on the targeted object
called primaryaction(); otherwise, it
calls the targeted object's offhandaction() function.
XRReferenceSpaceEventInit - Web APIs
the xrreferencespaceeventinit dictionary is used when
calling the xrreferencespaceevent() constructor to provide the values for its properties.
... usage notes all of this dictionary's properties must have valid values set on them before
calling the xrreferencespaceevent() constructor.
... examples this simple snippet
calls the constructor to create a new reference space event of type reset.
XRReferenceSpaceType - Web APIs
this type is used when
calling the requestreferencespace() method to obtain a reference space for an xrsession.
...this is used for environments in which the user can physi
cally move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions.
...otherwise, typi
cally, one of the other reference space types will be used more often.
XRSession: selectend event - Web APIs
if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is
called with the target ray pose's matrix.
... upon receiving a select event, the mydropobject() function is
called with the target object and the current target ray pose transform as inputs.
... the selectend event results in a mystoptracking() function being
called with the object being dragged and the final target ray pose's transform.
XRSession: selectstart event - Web APIs
if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is
called with the target ray pose's matrix.
... upon receiving a select event, the mydropobject() function is
called with the target object and the current target ray pose transform as inputs.
... the selectend event results in a mystoptracking() function being
called with the object being dragged and the final target ray pose's transform.
XRSession: squeezeend event - Web APIs
if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is
called with the target ray pose's matrix.
... upon receiving a squeeze event, the mydropobject() function is
called with the target object and the current target ray pose transform as inputs.
... the squeezeend event results in a mystoptracking() function being
called with the object being dragged and the final target ray pose's transform.
XRSession: squeezestart event - Web APIs
if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is
called with the target ray pose's matrix.
... upon receiving a squeeze event, the mydropobject() function is
called with the target object and the current target ray pose transform as inputs.
... the squeezeend event results in a mystoptracking() function being
called with the object being dragged and the final target ray pose's transform.
XRSession.visibilityState - Web APIs
the possible values of visibilitystate are: hidden the virtual scene generated by the xrsession is not currently visible to the user, so its requestanimationframe()
callbacks are not being executed until thevisibilitystate changes.
...to that end, the session's requestanimationframe()
callbacks are being processed at the xr device's native refresh rate and input controllers are being processed as normal.
...in order to optimize resource utilization, the user agent may be handling the session's requestanimationframe()
callbacks at a throttled rate.
XRSession - Web APIs
cancelanimationframe() removes a
callback from the animation frame painting
callback from xrsession's set of animation frame rendering
callbacks, given the identifying handle returned by a previous
call to requestanimationframe().
... requestanimationframe() schedules the specified method to be
called the next time the user agent is working on rendering an animation frame for the webxr device.
... returns an integer value which can be used to identify the request for the purposes of canceling the
callback using cancelanimationframe().
XRSystem: isSessionSupported() - Web APIs
if it is, we set up a button to read "enter xr", to
call a method onbuttonclicked(), and enable the button.
... if no session is already underway, we request the vr session and, if successful, set up the session in a method
called onsessionstarted(), not shown.
... if a session is already underway when the button is clicked, we
call the xrsession object's end() method to shut down the webxr session.
XRSystem: requestSession() - Web APIs
examples creating an immersive vr session the following example
calls requestsession() requesting an "immersive-vr" session.
...next, it
calls issessionsupported(), passing it the desired session option before enabling controls for entering xr.
...finally, the onbuttonclicked() method
calls requestsession() using the same session option passed to issessionsupported().
XRSystem - Web APIs
to determine this, we
call issessionsupported(), passing it the desired session option before enabling the button, immersivebutton, which the user can then use to switch to immersive mode only if immersive vr mode is available.
...if there isn't, we use requestsession() to start one and, once the returned promise resolves, we
call a function onsessionstarted() to set up our session for rendering and so forth.
... if, on the other hand, there is already an ongoing xr session, we instead
call end() to end the current session.
XRTargetRayMode - Web APIs
typi
cally a target ray is drawn from the source of the targeting system along the target ray in the direction in which the user is looking or pointing.
... examples this fragment of code shows part of a function to be
called once every frame.
...for tracked pointers, a function myrendertargetrayasbeam() is
called to render a beam from the input controller's virtual position outward in the direction it's pointing.
XRViewerPose - Web APIs
by
calling viewport() on the webgl context, specifying the xrview as input, you can get the viewport to use when rendering in order to draw the frame for that eye into the correct part of the drawing surface.
... the viewer's pose for the animation frame represented by xrframe can be obtained by
calling the frame's getviewerpose() method, specifying the reference space in which the origin's position should be computed.
... examples in this example—part of the code to render an xrframe, getviewerpose() is
called to get an xrviewerpose using the same reference space the code is using as its base reference space.
XRVisibilityState - Web APIs
values hidden the virtual scene generated by the xrsession is not currently visible to the user, so its requestanimationframe()
callbacks are not being executed until thevisibilitystate changes.
...to that end, the session's requestanimationframe()
callbacks are being processed at the xr device's native refresh rate and input controllers are being processed as normal.
...in order to optimize resource utilization, the user agent may be handling the session's requestanimationframe()
callbacks at a throttled rate.
XRWebGLLayer.framebuffer - Web APIs
calling functions such as framebuffertexture2d(), framebufferrenderbuffer(), deleteframebuffer(), or getframebufferattachmentparameter() on an opaque framebuffer results in the webgl error invalid_operation (0x0502).
... opaque framebuffers are considered incomplete and are not available for rendering other than while executing the requestanimationframe()
callback.
...
calling checkframebufferstatus() on the webgl context from outside the animation frame
callback causes the webgl framebuffer_unsupported error (0x8cdd) to be reported.
mssitemodejumplistitemremoved - Web APIs
the mssitemodejumplistitemremoved event occurs when mssitemodeshowjumplist is
called and an item has been removed from a jump list by the user.
... syntax event property object.oncandidatewindowhide = handler; addeventlistener method object.addeventlistener("mssitemodejumplistitemremoved", handler, usecapture) general info synchronous no bubbles no cancelable no note this event is raised once for every item that has been removed since the last time mssitemodeshowjumplist was
called.
... this event is not triggered if mssitemodeclearjumplist has been
called.
Web APIs
web apis are typi
cally used with javascript, although this doesn't always have to be the case.
...s rtcrtcpparameters rtcrtpcapabilities rtcrtpcodeccapability rtcrtpcodecparameters rtcrtpcontributingsource rtcrtpencodingparameters rtcrtpparameters rtcrtpreceiveparameters rtcrtpreceiver rtcrtpsendparameters rtcrtpsender rtcrtpstreamstats rtcrtpsynchronizationsource rtcrtptransceiver rtcrtptransceiverdirection rtcrtptransceiverinit rtcsctptransport rtcsessiondescription rtcsessiondescription
callback rtcstats rtcstatsicecandidatepairstate rtcstatsreport rtcstatstype rtctrackevent rtctrackeventinit radionodelist range readablebytestreamcontroller readablestream readablestreambyobreader readablestreambyobrequest readablestreamdefaultcontroller readablestreamdefaultreader relativeorientationsensor renderingcontext report reportingobserver reportingobserveroptions request reques...
...kerglobalscope workerlocation workernavigator worklet writablestream writablestreamdefaultcontroller writablestreamdefaultwriter x xdomainrequest xmldocument xmlhttprequest xmlhttprequesteventtarget xmlhttprequestresponsetype xmlserializer xpathevaluator xpathexception xpathexpression xpathnsresolver xpathresult xrboundedreferencespace xrenvironmentblendmode xreye xrframe xrframerequest
callback xrhandedness xrinputsource xrinputsourcearray xrinputsourceevent xrinputsourceeventinit xrinputsourceschangeevent xrinputsourceschangeeventinit xrpermissiondescriptor xrpermissionstatus xrpose xrreferencespace xrreferencespaceevent xrreferencespaceeventinit xrreferencespacetype xrrenderstate xrrenderstateinit xrrigidtransform xrsession xrsessionevent xrsessioneventinit xrsessioninit xrses...
Using the aria-orientation attribute - Accessibility
the aria-orientation attribute is used to indicate whether an element is oriented horizontally or verti
cally.
... value vocabulary vertical the element is oriented verti
cally.
... examples example 1: the snippet below shows a simple slider that is oriented verti
cally.
Using the slider role - Accessibility
as the user interacts with the thumb, the application must programmati
cally adjust the slider's aria-valuenow (and possible aria-valuetext) attribute to reflect the current value.
...the application will programmati
cally update the value of aria-valuenow in response to user input.
...-valuemin="1" aria-valuemax="100" aria-valuenow="50" oninput="outputupdate(value)"> <output for="fader" id="volume">50</output> the following code snippet allows you to return the output as it is updated by user input: function outputupdate(vol) { document.queryselector('#volume').value = vol; } example 2: text values sometimes, a slider is used to choose a value that is not, semanti
cally, a number.
ARIA: contentinfo role - Accessibility
this section is commonly
called a footer.
... using the <footer> element will automati
cally communicate a section has a role of contentinfo.
... best practices prefer html when it is an immediate descendant of the <body> element, using the <footer> element will automati
cally communicate a section has a role of contentinfo (save for a known issue in voiceover).
ARIA: Mark role - Accessibility
the mark landmark role semanti
cally denotes html elements containing text that is marked/highlighted for reference purposes.
... this is semanti
cally equivalent to the html <mark> element.
... best practices prefer html using the <mark> element will automati
cally communicate a section has a role of mark.
ARIA: Navigation Role - Accessibility
by classifying and labeling sections of a page, structural information conveyed visually through layout is represented programmati
cally.
... using the <nav> element will automati
cally communicate a section has a role of navigation.
... best practices prefer html using the <nav> element will automati
cally communicate a section has a role of navigation.
ARIA: Region role - Accessibility
by classifying and labeling sections of a page, structural information conveyed visually through layout is represented programmati
cally.
... using the <section> element will automati
cally communicate a section has a role of region if it is given an accessible name.
... best practices prefer html using the <section> element will automati
cally communicate that a section has a role of region if it is given an accessible name.
Alerts - Accessibility
it will
call the addalert function to add the alert with the provided error message.
...most screen readers will pick this one up automati
cally and speak it.
...why don’t you set focus back to the invalid field automati
cally?
An overview of accessible web applications and widgets - Accessibility
since the html4 specification doesn't provide built-in tags that semanti
cally describe these kinds of widgets, developers typi
cally resort to using generic elements such as <div> and <span>.
... aria attributes are interpreted automati
cally by the browser and translated to the operating system's native accessibility apis.
...on windows, the next tab should automati
cally be activated when the user presses the arrow keys.
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 caret can sometimes visually appear at the end of a line, but logi
cally it is on the first character on the next line.
...not only can this save extra
calls, but it will always return the visual line of text when used with the gettext methods and line boundaries.
Operable - Accessibility
2.2.2 pausing, stopping, hiding (a) for moving/blinking content that starts automati
cally, lasts longer than 5 seconds, and is shown alongside other content, controls should be provided to pause, stop, or hide it.
... for auto-updating information that starts automati
cally and is shown alongside other content, controls should be provided to pause, stop, or hide it, or to control the frequency of updates.
... the only exception to this is where a page is one step in a process, so should only logi
cally have links to the previous and next steps.
Understandable - Accessibility
3.1.5 reading level (aaa) if text is provided that requires a higher reading level that lower secondary education level (typi
cally children around 11-14 years old), provide supplementary explainer material to help people who can't read it, or provide an alternative version that is written at lower secondary level.
...a currency converter appearing on every page of a world travel site for example should be exactly the same, semanti
cally and in terms of labels.
...what page to show, when to advance to the next photo in the gallery...) if you need to have something like a carousel on a page, provide an option to stop it automati
cally advancing.
-moz-orient - CSS: Cascading Style Sheets
values inline the element is rendered in the same direction as the axis of the text: horizontally for horizontal writing modes, verti
cally for vertical writing modes.
... block the element is rendered orthogonally to the axis of the text: verti
cally for horizontal writing modes, horizontal for vertical writing modes.
... vertical the element is rendered verti
cally.
::placeholder - CSS: Cascading Style Sheets
syntax ::placeholder accessibility concerns color contrast contrast ratio placeholder text typi
cally has a lighter color treatment to indicate that it is a suggestion for what kind of input will be valid, and is not actual input of any kind.
... an alternate approach to providing placeholder information is to include it outside of the input in close visual proximity, then use aria-describedby to programmati
cally associate the <input> with its hint.
...without a label that has been programmati
cally associated with an input using a combination of the for and id attributes, assistive technology such as screen readers cannot parse <input> elements.
:fullscreen - CSS: Cascading Style Sheets
syntax :fullscreen usage notes the :fullscreen pseudo-class lets you configure your stylesheets to automati
cally adjust the size, style, or layout of content when elements switch back and forth between full-screen and traditional presentations.
...this is done without needing to specifi
cally apply style changes using javascript.
... html the page's html looks like this: <h1>mdn web docs demo: :fullscreen pseudo-class</h1> <p>this demo uses the <code>:fullscreen</code> pseudo-class to automati
cally change the style of a button used to toggle full-screen mode on and off, entirely using css.</p> <button id="fs-toggle">toggle fullscreen</button> the <button> with the id "fs-toggle" will change between pale red and pale green depending on whether or not the document is in full-screen mode.
:scope - CSS: Cascading Style Sheets
when used from a dom api such as queryselector(), queryselectorall(), matches(), or element.closest(), :scope matches the element on which the method was
called.
... syntax :scope examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's
called.
... javascript var context = document.getelementbyid('context'); var selected = context.queryselectorall(':scope > div'); document.getelementbyid('results').innerhtml = array.prototype.map.
call(selected, function (element) { return '#' + element.getattribute('id'); }).join(', '); html <div id="context"> <div id="element-1"> <div id="element-1.1"></div> <div id="element-1.2"></div> </div> <div id="element-2"> <div id="element-2.1"></div> </div> </div> <p> selected elements ids : <span id="results"></span> </p> result specification...
@font-face - CSS: Cascading Style Sheets
the @font-face css at-rule specifies a custom font with which to display text; the font can be loaded from either a remote server or a lo
cally-installed font on the user's own computer.
... by allowing authors to provide their own fonts, @font-face makes it possible to design content without being limited to the so-
called "web-safe" fonts (that is, the fonts which are so common that they're considered to be universally available).
... the ability to specify the name of a lo
cally-installed font to look for and use makes it possible to customize the font beyond the basics while making it possible to do so without relying on an internet connection.
Using multi-column layouts - CSS: Cascading Style Sheets
if column-count is not also set, then the browser will automati
cally make as many columns as fit in the available width.
... in a multi-column block, content is automati
cally flowed from one column into the next as needed.
...excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum </div> css #columns_12 { columns: 12 8em; } result height balancing the css3 column specification requires that the column heights must be balanced: that is, the browser automati
cally sets the maximum column height so that the heights of the content in each column are approximately equal.
Descendant combinator - CSS: Cascading Style Sheets
the descendant combinator — typi
cally represented by a single space ( ) character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first selector.
... selectors that utilize a descendant combinator are
called descendant selectors.
... /* list items that are descendants of the "my-things" list */ ul.my-things li { margin: 2em; } the descendant combinator is techni
cally 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.
Media queries - CSS: Cascading Style Sheets
media queries in html in html, media queries can be applied to various elements: in the <link> element's media attribute, they define the media to which a linked resource (typi
cally css) should be applied.
... you can learn more about programmati
cally using media queries in testing media queries.
... testing media queries programmati
cally describes how to use media queries in your javascript code to determine the state of a device, and to set up listeners that notify your code when the results of media queries change (such as when the user rotates the screen or resizes the browser).
Viewport concepts - CSS: Cascading Style Sheets
to recap, the viewport is basi
cally the part of the document that is currently visible.
...the area that is visible is
called the viewport.
... see also @viewport css at-rule visual viewport api <meta>, specifi
cally <meta name="viewport"> using the viewport meta tag to control layout on mobile browsers ...
box-orient - CSS: Cascading Style Sheets
the box-orient css property sets whether an element lays out its contents horizontally or verti
cally.
... vertical the box lays out its contents verti
cally.
... html <div class="example"> <p>i will be to the left of my sibling.</p> <p>i will be to the right of my sibling.</p> </div> css div.example { display: -moz-box; /* mozilla */ display: -webkit-box; /* webkit */ display: box; /* as specified */ /* children should be oriented verti
cally */ -moz-box-orient: horizontal; /* mozilla */ -webkit-box-orient: horizontal; /* webkit */ box-orient: horizontal; /* as specified */ } result specifications not part of any standard.
<color> - CSS: Cascading Style Sheets
note: the list of accepted keywords has undergone many changes during the evolution of css: css level 1 only included 16 basic colors,
called the vga colors as they were taken from the set of displayable colors on vga graphics cards.
...they are
called the extended color keywords, the x11 colors, or the svg colors.
...techni
cally, transparent is a shortcut for rgba(0,0,0,0).
<easing-function> - CSS: Cascading Style Sheets
the easing functions in the cubic-bezier subset of easing functions are often
called "smooth" easing functions, because they can be used to smooth down the start and end of the animation.
...as these curves are continuous, they are often used to smooth down the start and end of the animation and are therefore sometimes
called easing functions.
... the steps() class of easing functions the steps() functional notation defines a step function dividing the domain of output values in equidistant steps.this subclass of step functions are sometimes also
called staircase functions.
font-family - CSS: Cascading Style Sheets
"brush script mt", "brush script std", "lucida
calligraphy", "lucida handwriting", "apple chancery", cursive.
... emoji fonts that are specifi
cally designed to render emoji.
... working draft adds new generic font families, specifi
cally: system-ui, ui-serif, ui-sans-serif, ui-monospace, ui-rounded, emoji, math, and fangsong.
font-variant-position - CSS: Cascading Style Sheets
these glyphs are typi
cally used in <sub> and <sup> elements.
... /* keyword values */ font-variant-position: normal; font-variant-position: sub; font-variant-position: super; /* global values */ font-variant-position: inherit; font-variant-position: initial; font-variant-position: unset; when the usage of these alternate glyphs is activated, if one character in the run doesn't have such a typographi
cally-enhanced glyph, the whole set of characters of the run is rendered using a fallback method, synthesizing these glyphs.
...they are merely graphi
cally enhanced, and have no effect on the line-height and other box characteristics.
outline-width - CSS: Cascading Style Sheets
typi
cally equivalent to 1px in desktop browsers (including firefox).
...typi
cally equivalent to 3px in desktop browsers (including firefox).
...typi
cally equivalent to 5px in desktop browsers (including firefox).
resize - CSS: Cascading Style Sheets
both the element displays a mechanism for allowing the user to resize it, which may be resized both horizontally and verti
cally.
... block the element displays a mechanism for allowing the user to resize it in the block direction (either horizontally or verti
cally, depending on the writing-mode and direction value).
... inline the element displays a mechanism for allowing the user to resize it in the inline direction (either horizontally or verti
cally, depending on the writing-mode and direction value).
scroll-snap-type-y - CSS: Cascading Style Sheets
/* keyword values */ scroll-snap-type-y: none; scroll-snap-type-y: mandatory; scroll-snap-type-y: proximity; /* global values */ scroll-snap-type-y: inherit; scroll-snap-type-y: initial; scroll-snap-type-y: unset; syntax values none when the visual viewport of this scroll container is scrolled verti
cally, it must ignore snap points.
... mandatory the visual viewport of this scroll container will rest on a snap point if it isn't currently scrolled verti
cally.
... proximity the visual viewport of this scroll container may come to rest on a snap point if it isn't currently scrolled verti
cally considering the user agent's scroll parameters.
Adding captions and subtitles to HTML5 video - Developer guides
they are however implemented in the same way techni
cally, so the material in this article will apply to both.
...this menu is built dynami
cally, so that languages can be added or removed later by simply editing the <track> elements within the video's markup.
...dding:10px; } .subtitles-menu li { padding:0; text-align:center; } .subtitles-menu li button { border:none; background:#000; color:#fff; cursor:pointer; width:90%; padding:2px 5px; border-radius:2px; } styling the displayed subtitles one of the less well known about and supported features of webvtt is the ability to style the individual subtitles (something
called text cues) via css extensions.
Media events - Developer guides
emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is
called to reload it.
... progress sent periodi
cally to inform interested parties of progress downloading the media.
... the listener simply
calls the element's play() method, which starts playback.
A hybrid approach - Developer guides
luckily, we aren’t techni
cally constrained to using client-side techniques here: another option is to use server-side user-agent detection to show the user the proper content.
... using user-agent detection specifi
cally for content and not layout also allows you to have a single url for each piece of content, so that the content can adapt its layout to the user’s browser.
...another downside is that because this approach relies on responsive design, it typi
cally works best on a new project or one that has an existing flexible layout, not as a retrofit.
User input and controls - Developer guides
if you want to use touch events, you need to add event listeners and specify handler functions, which will be
called when the event gets fired: element.addeventlistener("touchstart", handlestart, false);
element.addeventlistener("touchcancel", handlecancel, false);
element.addeventlistener("touchend", handleend, false);
element.addeventlistener("touchmove", handlemove, false); where element is the dom element you want to register the touch events on.
... implement controls pointer lock in some cases, typi
cally game development, you might need to access mouse events even when the cursor goes past the boundary of the browser or screen: the pointer_lock_api gives you full control of the pointing device.
...you can achieve this by
calling element.requestfullscreen() on that element.
Writing forward-compatible websites - Developer guides
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.
... if that happens, then suddenly your function stops being
called.
... to avoid this, fully qualify global variable access using "window.", like so: <script> function localname() { alert('function localname has been
called'); } </script> <div onclick="window.localname()">clicking me should show an alert<div> don't concatenate scripts you don't control the "use strict;" directive in ecmascript, when used on the file level, applies to everything in the file.
Block-level elements - HTML: Hypertext Markup Language
html (hypertext markup language) elements histori
cally were categorized as either "block-level" elements or "inline-level" elements.
... browsers typi
cally display the block-level element with a newline both before and after the element.
... elements the following is a complete list of all html "block-level" elements (although "block-level" is not techni
cally defined for elements that are new in html5).
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
calling any of the following on a tainted canvas will result in an error:
calling getimagedata() on the canvas's context
calling toblob() on the <canvas> element itself
calling todataurl() on the canvas attempting any of these when the canvas is tainted will cause a securityerror to be thrown.
... = 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.todataurl("image/png")); } catch(err) { console.log("error: " + err); } } imagereceived() is
called to handle the "load" event on the htmlimageelement that receives the downloaded image.
... now it's time to actually save the image lo
cally.
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
each <abbr> element you use is independent from all others; providing a title for one does not automati
cally attach the same expansion text to others with the same content text.
... when an abbreviation's presence in the text needs to be semanti
cally noted, the <abbr> element is useful.
... examples marking up an abbreviation semanti
cally to mark up an abbreviation without providing an expansion or description, simply use <abbr> without any attributes, as seen in this example.
<img>: The Image Embed element - HTML: Hypertext Markup Language
image loading errors if an error occurs while loading or rendering an image, and an onerror event handler has been set on the error event, that event handler will get
called.
...specifi
cally, the image would raster at these dimensions and naturalwidth/naturalheight on images would return the values specified in this attribute.
...this is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategi
cally placing images in a page's markup such that a server can track how many images are requested and when.
<input type="datetime-local"> - HTML: Hypertext Markup Language
here is javascript code for programmati
cally setting the value: function setvalue(element, date) { var isostring = date.toisostring() element.value = isostring.substring(0, (isostring.indexof("t")|0) + 6|0); } why worry about the y10k problem if it is going to happen many centuries after your death?
... </div> <div> <span> <label for="hour">hour:</label> <select id="hour" name="hour"> </select> </span> <span> <label for="minute">minute:</label> <select id="minute" name="minute"> </select> </span> </div> </div> </form> the months are hard-coded (as they are always the same), while the day and year values are dynami
cally generated depending on the currently selected month and year, and the current year respectively (see the code comments below for detailed explanations of how these functions work.) we also decided to dynami
cally generate the hours and minutes, as there are so many of them!
...eateelement('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'; fallbacklabel.style.display = 'block'; // populate the days and years dynami
cally // (the months are 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); } // crea...
<input type="number"> - HTML: Hypertext Markup Language
it is not as semanti
cally useful as other ways to explain your form, and can cause unexpected technical issues with your content.
... important: bear in mind that, logi
cally, you should not be able to enter characters inside a number input other than numbers.
... validation we have already mentioned a number of validation features of number inputs, but let's review them now: <input type="number"> elements automati
cally invalidate any entry that isn't a number (or empty, unless required is specified).
<input type="week"> - HTML: Hypertext Markup Language
in non-supporting browsers, the control degrades gracefully to function identi
cally to <input type="text">.
...n> <label for="week">week:</label> <select id="fallbackweek" name="week"> </select> </span> <span> <label for="year">year:</label> <select id="year" name="year"> <option value="2017" selected>2017</option> <option value="2018">2018</option> </select> </span> </div> </div> </form> the week values are dynami
cally generated by the javascript code below.
... 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.display = 'block'; // populate the weeks dynami
cally populateweeks(); } function populateweeks() { // populate the week select with 52 weeks for(var i = 1; i <= 52; i++) { var option = document.createelement('option'); option.textcontent = (i < 10) ?
<table>: The Table element - HTML: Hypertext Markup Language
the attribute is applied both horizontally and verti
cally, to the space between the top of the table and the cells of the first row, the left of the table and the first column, the right of the table and the last column and the bottom of the table and the last row.
...this is typi
cally indicated by the presence of the colspan and rowspan attributes.
... if the table cannot be broken apart, use a combination of the id and headers attributes to programmati
cally associate each table cell with the header(s) the cell is associated with.
Global attributes - HTML: Hypertext Markup Language
autocapitalize controls whether and how text input is automati
cally capitalized as it is entered/edited by the user.
... data-* forms a class of attributes,
called custom data attributes, that allow proprietary information to be exchanged between the html and its dom representation that may be used by scripts.
...such information can typi
cally, but not necessarily, be presented to the user as a tooltip.
Choosing between www and non-www URLs - HTTP
in an http url, the first substring that follows the initial http:// or https:// is
called the domain name.
...the key point is that semanti
cally one domain name represents one single server.
...this official domain is
called the canonical name.
Clear-Site-Data - HTTP
it allows web developers to have more control over the data stored lo
cally by a browser for their origins.
... "cache" indicates that the server wishes to remove lo
cally cached data (i.e.
... examples sign out of web site if a user signs out of your website or service, you might want to remove lo
cally stored data.
HTTP headers - HTTP
custom proprietary headers have histori
cally been used with an x- prefix, but this convention was deprecated in june 2012 because of the inconveniences it caused when nonstandard fields became standard in rfc 6648; others are listed in an iana registry, whose original content was defined in rfc 4229.
... device-memory techni
cally a part of device memory api, this header represents an approximate amount of ram client has.
...it is semanti
cally equivalent to the html <link> element.
Proxy Auto-Configuration (PAC) file - HTTP
the browser will automati
cally retry a previously unresponsive proxy after 30 minutes.
... proxy w3proxy.netscape.com:8080; proxy mozilla.netscape.com:8081; direct same as above, but if both proxies go down, automati
cally start making direct connections.
...if the proxy goes down, connections become direct automati
cally: function findproxyforurl(url, host) { if (isplainhostname(host) || dnsdomainis(host, ".mozilla.org")) { return "direct"; } else { return "proxy w3proxy.mozilla.org:8080; direct"; } } note: this is the simplest and most efficient autoconfig file for cases where there's only one proxy.
Redirections in HTTP - HTTP
http has a special kind of response,
called a http redirect, for this operation.
... special redirections 304 (not modified) redirects a page to the lo
cally cached copy (that was stale), and 300 (multiple choice) is a manual redirection: the body, presented by the browser as a web page, lists the possible redirections and the user clicks on one to select it.
... typi
cally, you don't want your users to resend put, post or delete requests.
Regular expression syntax cheatsheet - JavaScript
in results, matches to capturing groups typi
cally in an array whose members are in the same order as the left parentheses in the capturing group.
...if you don't need the matched substring to be re
called, prefer non-capturing parentheses (see below).
...the matched substring cannot be re
called from the resulting array's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9).
Groups and ranges - JavaScript
in results, matches to capturing groups typi
cally in an array whose members are in the same order as the left parentheses in the capturing group.
...if you don't need the matched substring to be re
called, prefer non-capturing parentheses (see below).
...the matched substring cannot be re
called from the resulting array's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9).
Text formatting - JavaScript
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 automati
cally converts the string literal to a temporary string object,
calls the method, then discards the temporary string object.
... you should use string literals unless you specifi
cally need to use a string object, because string objects can have counterintuitive behavior.
... normalize returns the unicode normalization form of the
calling string value.
Private class fields - JavaScript
the limitation of static variables being
called by only static methods still holds.
... 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.
...in the following example this refers to the derived class (not the base class) when we try to
call derived.publicstaticmethod2(), and thus exhibits the same "provenance restriction" as mentioned above: class base { static #privatestaticmethod() { return 42; } static publicstaticmethod1() { return base.#privatestaticmethod(); } static publicstaticmethod2() { return this.#privatestaticmethod(); } } class derived extends base {} console.log(deriv...
SyntaxError: return not in function - JavaScript
the javascript exception "return (or yield) not in function" occurs when a return or yield statement is
called outside of a function.
... a return or yield statement is
called outside of a function.
...the return and yield statements must be in a function, because they end (or pause and resume) function execution and specify a value to be returned to the function
caller.
SyntaxError: missing formal parameter - JavaScript
declaring functions and
calling functions are two separate steps.
... declarations require identifier as parameters, and only when
calling (invoking) the function, you provide the values the function should use.
...greet("howdy") { return greeting; }; // syntaxerror: missing formal parameter function log({ obj: "value"}) { console.log(arg) }; // syntaxerror: missing formal parameter you will need to use identifiers in function declarations: function square(number) { return number * number; }; function greet(greeting) { return greeting; }; function log(arg) { console.log(arg) }; you can then
call these functions with the arguments you like: square(2); // 4 greet("howdy"); // "howdy" log({obj: "value"}); // object { obj: "value" } ...
SyntaxError: missing ) after argument list - JavaScript
the javascript exception "missing ) after argument list" occurs when there is an error with how a function is
called.
... there is an error with how a function is
called.
... console.log('pi: ' math.pi); // syntaxerror: missing ) after argument list you can correct the log
call by adding the "+" operator: console.log('pi: ' + math.pi); // "pi: 3.141592653589793" unterminated strings console.log('"java" + "script" = \"' + 'java' + 'script\"); // syntaxerror: missing ) after argument list here javascript thinks that you meant to have ); inside the string and ignores it, and it ends up not knowing that you meant the ); to end the function console.log.
TypeError: "x" is not a constructor - JavaScript
you want this type of object to be
called car, and you want it to have properties for make, model, and year.
... to do this, you would write the following function: function car(make, model, year) { this.make = make; this.model = model; this.year = year; } now you can create an object
called mycar as follows: var mycar = new car('eagle', 'talon tsi', 1993); in promises when returning an immediately-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it.
... this is not legal (the promise constructor is not being
called correctly) and will throw a typeerror: this is not a constructor exception: return new promise.resolve(true); instead, use the promise.resolve() or promise.reject() static methods: // this is legal, but unnecessarily long: return new promise((resolve, reject) => { resolve(true); }) // instead, return the static method: return promise.resolve(true); return promise.reject(false); ...
TypeError: 'x' is not iterable - JavaScript
ap.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 functions you
call to produce an iterable object.
... function* generate(a, b) { yield a; yield b; } for (let x of generate) // typeerror: generate is not iterable console.log(x); when they are not
called, the function object corresponding to the generator is
callable, but not iterable.
...
calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator.
getter - JavaScript
the get syntax binds an object property to a function that will be
called when that property is looked up.
... description sometimes it is desirable to allow access to a property that returns a dynami
cally computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method
calls.
...the value is calculated the first time the getter is
called, and is then cached so subsequent accesses return the cached value without recalculating it.
Array.prototype.includes() - JavaScript
note: techni
cally speaking, includes() uses the samevaluezero algorithm to determine whether the given element is found.
... the example below illustrates includes() method
called on the function's arguments object.
... (function() { console.log(array.prototype.includes.
call(arguments, 'a')) // true console.log(array.prototype.includes.
call(arguments, 'd')) // false })('a','b','c') please do not add polyfills on reference articles.
Array.prototype.slice() - JavaScript
olor) this script writes: mycar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, 'cherry condition', 'purchased 1997'] newcar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] mycar[0].color = red newcar[0].color = red the new color of my honda is purple mycar[0].color = purple newcar[0].color = purple array-like objects slice method can also be
called to convert array-like objects/collections to a new array.
... function list() { return array.prototype.slice.
call(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] binding can be done with the
call() method of function.prototype and it can also be reduced using [].slice.
call(arguments) instead of array.prototype.slice.
call.
... let unboundslice = array.prototype.slice let slice = function.prototype.
call.bind(unboundslice) function list() { return slice(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.slice' in that specification.
FinalizationRegistry() constructor - JavaScript
the finalizationregistry constructor creates a finalizationregistry object that uses the given
callback.
... 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 => { // ....
Function() constructor - JavaScript
calling the constructor directly can create functions dynami
cally, but suffers from security and similar (but far less significant) performance issues to eval.
...this is less efficient than declaring a function with a function expression or function statement and
calling it within your code because such functions are parsed with the rest of the code.
... // 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.prototype.toString() - JavaScript
javascript
calls the tostring method automati
cally when a function is to be represented as a text value, e.g.
... the tostring() method will throw a typeerror exception ("function.prototype.tostring
called on incompatible object"), if its this value object is not a function object.
... function.prototype.tostring.
call('foo'); // typeerror if the tostring() method is
called on built-in function objects or a function created by function.prototype.bind, tostring() returns a native function string which looks like "function () {\n [native code]\n}" if the tostring() method is
called on a function created by the function constructor, tostring() returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body.
Intl.DateTimeFormat() constructor - JavaScript
options optional an object with some or all of the following properties: datestyle the date formatting style to use when
calling format().
... possible values include: "full" "long" "medium" "short" timestyle the time formatting style to use when
calling format().
... possible values include: "full" "long" "medium" "short" fractionalseconddigits the number of fractional seconds to apply when
calling format().
JSON.parse() - JavaScript
var k; var v; var value = holder[key]; if (value && typeof value === "object") { for (k in value) { if (object.prototype.hasownproperty.
call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.
call(holder, key, value); } // parsing happens in ...
...specifi
cally, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver.
... then it is
called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments.
Map - JavaScript
for this reason (and because there were no built-in alternatives), objects have been used as maps histori
cally.
... map.prototype.foreach(
callbackfn[, thisarg])
calls
callbackfn once for each key-value pair present in the map object, in insertion order.
... if a thisarg parameter is provided to foreach, it will be used as the this value for each
callback.
Object.prototype.constructor - JavaScript
exp() function type() {},false,/(?:)/ // /(?:)/ function type() {},false, // new string() function string() { [native code] },false,test // 'test' changing the constructor of a function mostly this property is used for defining a function as a function-constructor with further
calling it with new and prototype-inherits chain.
...*/ } parent.prototype.parentmethod = function parentmethod() {} function child() { parent.
call(this) // make sure everything is initialized properly } child.prototype = object.create(parent.prototype) // re-define child prototype to parent prototype child.prototype.constructor = child // return original constructor to child but when do we need to perform the last line here?
...*/ } function createdconstructor() { parent.
call(this) } createdconstructor.prototype = object.create(parent.prototype) createdconstructor.prototype.create = function create() { return new this.constructor() } new createdconstructor().create().create() // typeerror undefined is not a function since constructor === parent in the example above the exception will be shown since the constructor links to parent.
Object.defineProperty() - JavaScript
when the property is accessed, this function is
called without arguments and with this set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance).
...when the property is assigned, this function is
called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned.
...definesetandget() { object.defineproperty(this, 'myproperty', pattern); } var instance = new testdefinesetandget(); instance.myproperty = 'test'; console.log(instance.myproperty); // i always return this string, whatever you have assigned console.log(instance.myname); // this is my name string inheritance of properties if an accessor property is inherited, its get and set methods will be
called when the property is accessed and modified on descendant objects.
Object.prototype.toSource() - JavaScript
you can
call tosource() while debugging to examine the contents of an object.
...a cycli
cally linked list or a tree that can be traversed both ways, tosource() will not recreate the self-reference, as of firefox 24.
... 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.
Proxy.revocable() - JavaScript
proxy a proxy object created with new proxy(target, handler)
call.
... if the revoke() function gets
called, the proxy becomes unusable: any trap to a handler will throw a typeerror.
...
calling revoke() again has no effect.
Reflect - JavaScript
static methods reflect.apply(target, thisargument, argumentslist)
calls a target function with arguments as specified by the argumentslist parameter.
...equivalent to
calling new target(...argumentslist).
...equivalent to
calling delete target[propertykey].
RegExp.prototype[@@match]() - JavaScript
description this method is
called internally in string.prototype.match().
... examples direct
call this method can be used in almost the same way as string.prototype.match(), except the different this and the different arguments order.
... 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
description this method is
called internally in string.prototype.matchall().
... examples direct
call this method can be used in almost the same way as string.prototype.matchall(), except for the different value of this and the different order of arguments.
... 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 speci...
RegExp.prototype[@@search]() - JavaScript
description this method is
called internally in string.prototype.search().
... examples direct
call this method can be used in almost the same way as string.prototype.search(), except the different this and the different arguments order.
... 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
description this method is
called internally in string.prototype.split() if its separator argument is an object that has a @@split method, such as a regexp.
... examples direct
call this method can be used in almost the same way as string.prototype.split(), except the different this and the different order of arguments.
... 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.test() - JavaScript
(this is similar to the string.prototype.match() method.) as with exec() (or in combination with it), test()
called multiple times on the same global regular expression instance will advance past the previous match.
...(regexp.prototype.exec() also advances the lastindex property.) further
calls to test(str) will resume searching str starting from lastindex.
... when test() returns false, the
calling regex's lastindex property will reset to 0.
Set - JavaScript
specifi
cally, for sets, +0 (which is strictly equal to -0) and -0 were different values.
... set.prototype.foreach(
callbackfn[, thisarg])
calls
callbackfn once for each value present in the set object, in insertion order.
... if a thisarg parameter is provided, it will be used as the this value for each invocation of
callbackfn.
String.prototype.charAt() - JavaScript
the index of the first character is 0, and the index of the last character—in a string
called stringname—is stringname.length - 1.
... throw 'low surrogate without preceding high surrogate'; } // we can pass over low surrogates now as the second component // in a pair which we have already processed return false; } in an ecmascript 2016 environment which allows destructured assignment, the following is a more succinct and somewhat more flexible alternative in that it does increment for an incrementing variable automati
cally (if the character warrants it in being a surrogate pair).
... if (0xd800 > prev || prev > 0xdbff) { throw 'low surrogate without preceding high surrogate' } // return the next character instead (and increment) return [str.charat(i + 1), i + 1] } fixing charat() to support non-basic-multilingual-plane (bmp) characters while the previous example may be more useful for programs that must support non-bmp characters (since it does not require the
caller to know where any non-bmp character might appear), in the event that one does wish, in choosing a character by index, to treat the surrogate pairs within a string as the single characters they represent, one can use the following: function fixedcharat(str, idx) { let ret = '' str += '' let end = str.length let surrogatepairs = /[\ud800-\udbff][\udc00-\udfff]/g while ((surrogatepairs...
String.raw() - JavaScript
syntax string.raw(
callsite, ...substitutions) string.raw`templatestring` parameters
callsite well-formed template
call site object, like { raw: ['foo', 'bar', 'baz'] }.
...the first syntax mentioned above is only rarely used, because the javascript engine will
call this with proper arguments for you, (just like with other tag functions).
... // normally you would not
call string.raw() as a function, // but to simulate `foo${2 + 3}bar${'java' + 'script'}baz` you can do: string.raw({ raw: ['foo', 'bar', 'baz'] }, 2 + 3, 'java' + 'script'); // 'foo5barjavascriptbaz' // notice the first argument is an object with a 'raw' property, // whose value is an iterable representing the separated strings // in the template literal.
Symbol.toStringTag - JavaScript
property attributes of symbol.tostringtag writable no enumerable no configurable no examples default tags object.prototype.tostring.
call('foo'); // "[object string]" object.prototype.tostring.
call([1, 2]); // "[object array]" object.prototype.tostring.
call(3); // "[object number]" object.prototype.tostring.
call(true); // "[object boolean]" object.prototype.tostring.
call(undefined); // "[object undefined]" object.prototype.tostring.
call(null); // "[object null]" // ...
... 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.
TypedArray.from() - JavaScript
mapfn optional map function to
call on every element of the typed array.
...this means that the following are equivalent: typedarray.from(obj, mapfn, thisarg) typedarray.from(array.prototype.map.
call(obj, mapfn, thisarg)).
...hence, when working with proxy objects, it
calls handler.set to create new elements rather than handler.defineproperty().
WeakSet - JavaScript
use case: detecting circular references functions that
call themselves recursively need a way of guarding against circular data structures by tracking which objects have already been processed.
... 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!
... execrecursively(obj => console.log(obj), foo); here, a weakset is created on the first run, and passed along with every subsequent function
call (using the internal _refs parameter).
Logical NOT (!) - JavaScript
it is typi
cally used with boolean (logical) values.
... if a value can be converted to true, the value is so-
called truthy.
... if a value can be converted to false, the value is so-
called falsy.
Nullish coalescing operator (??) - JavaScript
function a() { console.log('a was
called'); return undefined;} function b() { console.log('b was
called'); return false;} function c() { console.log('c was
called'); return "foo";} console.log( a() ??
... c() ); // logs "a was
called" then "c was
called" and then "foo" // as a() returned undefined so both expressions are evaluated console.log( b() ??
... c() ); // logs "b was
called" then "false" // as b() returned false (and not null or undefined), the right // hand side expression was not evaluated no chaining with and or or operators it is not possible to combine both the and (&&) and or operators (||) directly with ??.
Pipeline operator (|>) - JavaScript
this allows the creation of chained function
calls in a readable manner.
... the result is syntactic sugar in which a function
call with a single argument can be written like this: let url = "%21" |> decodeuri; the equivalent
call in traditional syntax looks like this: let url = decodeuri("%21"); syntax expression |> function the value of the specified expression is passed into the function as its sole parameter.
... examples chaining function
calls the pipeline operator can improve readability when chaining several functions.
Expressions and operators - JavaScript
super the super keyword
calls the parent constructor.
... ...obj spread syntax allows an expression to be expanded in places where multiple arguments (for function
calls) or multiple elements (for array literals) are expected.
... binary logical operators logical operators are typi
cally used with boolean (logical) values, and when they are, they return a boolean value.
return - JavaScript
the return statement ends function execution and specifies a value to be returned to the function
caller.
...if specified, a given value is returned to the function
caller.
... to avoid this problem (to prevent asi), you could use parentheses: return ( a + b ); examples interrupt a function a function immediately stops at the point where return is
called.
Trailing commas - JavaScript
trailing commas (sometimes
called "final commas") can be useful when adding new elements, parameters, or properties to javascript code.
...an array with holes is
called sparse (a dense array has no holes).
... function f(p) {} function f(p,) {} (p) => {}; (p,) => {}; the trailing comma also works with method definitions for classes or objects: class c { one(a,) {} two(a, b,) {} } var obj = { one(a,) {}, two(a, b,) {}, }; function
calls the following function invocation pairs are legal and equivalent to each other.
JavaScript typed arrays - JavaScript
as you may already know, array objects grow and shrink dynami
cally and can have any javascript value.
... however, typed arrays are not to be confused with normal arrays, as
calling array.isarray() on a typed array returns false.
... let typedarray = new uint8array([1, 2, 3, 4]), normalarray = array.prototype.slice.
call(typedarray); normalarray.length === 4; normalarray.constructor === array; specifications specification ecmascript (ecma-262)the definition of 'typedarray objects' in that specification.
Digital video concepts - Web media technologies
the name "yuv" is generally used today to describe this color system, even though the term was originally used specifi
cally for analog coding of color, while ycbcr was used for digital color.
...these sensors physi
cally occupy the same surface,
called the retina, at the back of the eye.
... yuv data representation because the image is represented using more detail in greyscale than in color, the values of y', u, and v are not typi
cally stored together, one sample per pixel, the way rgb images are stored in memory.
The "codecs" parameter in common media types - Web media technologies
this value defines the function used to map the gamma (delightfully
called the "opto-electrical transfer function" in technical parlance) from the source to the display.
... webm profile numbers profile description 00 only 4:2:0 (chroma subsampled both horizontally and verti
cally).
... 02 only 4:2:0 (chroma subsampled both horizontally and verti
cally).
OpenSearch description format
opensearch description files can be advertised as described in autodiscovery of search plugins, and can be installed programmati
cally as described in adding search engines from web pages.
... supporting automatic updates for opensearch plugins opensearch plugins can automati
cally update.
...the template attribute should be the url of the opensearch document to automati
cally update to.
CSS and JavaScript animation performance - Web Performance
the
callback function of the method is
called by the browser before the next repaint on each frame.
...developers can create an animation by simply changing an element's style each time the loop is
called (or updating the canvas draw, or whatever.) note: like css transitions and animations, requestanimationframe() pauses when the current tab is pushed into the background.
...this can occur because css transitions/animations are simply resampling element styles in the main ui thread before each repaint event happens, which is almost the same as resampling element styles via a requestanimationframe()
callback, also triggered before the next repaint.
Navigation and resource timings - Web Performance
both provide the same read-only properties, but navigation timing measures the main document's timings whereas the resource timing provides the times for all the assets or resources
called in by that main document and the resources' requested resources.
...the navigation timings provide us a way to programmati
cally check transfer sizing and bandwidth savings.
... resource timing whereas navigation timing is for measuring the performance of the main page, generally the html file via which all the other assets are requested, resource timing measures timing for individual resources, the assets
called in by the main page, and any assets that those resources request.
Privacy, permissions, and information security
because of this, browsers typi
cally introduce a small amount of variability to timers in order to make them less useful for identifying the user's system.
...ty to define the extent to which a document's content can be accessed by other devices over the web; used in particular to prevent or mitigate attacks on the server feature policy lets web developers selectively enable, disable, and modify the behavior of certain features and apis both for a document and for subdocuments loaded in <iframe>s <iframe>'s allow attribute techni
cally part of feature policy, the allow attribute on an <iframe> specifies which web features the document in the frame should be allowed to access http public key pinning (hpkp) hpkp is used by servers to instruct a client to associate a specific public key with the server going forward in order to decrease the likelihood of man-in-the-middle attacks http strict transport securit...
...y (hsts) hsts is used by servers to let them protect themselves from protocol downgrade and cookie hijack attacks by letting sites tell clients that they can only use https to communicate with the server http/2 while http/2 techni
cally does not have to use encryption, most browser developers are only supporting it when used with https, so it can be thought of in that regard as being security-related permissions api provides a way to determine the status of permissions for the current browser context transport layer security (tls); formerly known as secure sockets layer (ssl) tls provides security and privacy by encrypting data during transport over the network.
Add to Home screen - Progressive web apps (PWAs)
adding an install button to make our pwa installable on desktop, we first added a button to our document to allow users to do the installation — this isn't made available automati
cally on desktop apps, and the installation needs to be triggered by a user gesture: <button class="add-button">add to home screen</button> we then gave it some simple styling: .add-button { position: absolute; top: 1px; left: 1px; } javascript for handling the install at the bottom of our index.js file, we added some javascript to handle the installation.
...we can then use a handler like the one below to handle the installation: window.addeventlistener('beforeinstallprompt', (e) => { // prevent chrome 67 and earlier from automati
cally showing the prompt e.preventdefault(); // stash the event so it can be triggered later.
... prompt deferredprompt.prompt(); // wait for the user to respond to the prompt deferredprompt.userchoice.then((choiceresult) => { if (choiceresult.outcome === 'accepted') { console.log('user accepted the a2hs prompt'); } else { console.log('user dismissed the a2hs prompt'); } deferredprompt = null; }); }); }); so here we:
call event.preventdefault() to stop chrome 67 and earlier from
calling the install prompt automati
cally (this behavior changed in chrome 68).
Installing and uninstalling web apps - Progressive web apps (PWAs)
to add a web app to the home screen (also known as the launcher or springboard), tap the sharing button () at the bottom of the screen: this
calls up the sharing panel.
... among the options should be the "add to home screen" option, unless it's been specifi
cally removed from the list by the user editing the optons displayed: choosing "add to home screen" here presents the confirmation dialog box, which not only confirms that the user wants to add the app to the home screen, but also lets the user customize its name.
...typi
cally this means you'll see the app's icon along with a short title.
Media - Progressive web apps (PWAs)
these properties dynami
cally change the appearance of content as the user works with the interface.
... example these rules specify styles for a button that changes dynami
cally as the user interacts with it: .green-button { background-color:#cec; color:#black; border:2px outset #cec; padding: 5px 10px; } .green-button[disabled] { background-color:#cdc; color:#777; } .green-button:active, .green-button.active { border-style: inset; } <table> <tbody> <tr> <td><button class="green-button" disabled>click me</button></td> <td><button class=...
...the next page describes how you can change rules dynami
cally by using a programming language: javascript.
local - SVG: Scalable Vector Graphics
the local attribute specifies the unique id for a lo
cally stored color profile as specified by international color consortium.
... if both the xlink:href and the local attribute are specified, then the local file system is searched for the color profile first, and, if not available lo
cally, then the resource identified by the xlink:href attribute is used.
... only one element is using this attribute: <color-profile> usage notes value <string> default value none animatable no <string> this value specifies the unique id for a lo
cally stored color profile as specified by international color consortium.
Getting started - SVG: Scalable Vector Graphics
fine adjustments can be made to the font size and vertical position to ensure the final result is aestheti
cally pleasing.
... the svg file can be referenced with an object element: <object data="image.svg" type="image/svg+xml" /> likewise an iframe element can be used: <iframe src="image.svg"></iframe> an img element can theoreti
cally be used too.
... finally, svg can be created dynami
cally with javascript and injected into the html dom.
Patterns - SVG: Scalable Vector Graphics
since, in this case, we wanted the pattern to repeat 4 times horizontally and verti
cally, the height and width are set to 0.25.
... to make this work in the example above, we had to consider the size of our box (200 pixels) and the fact that we wanted the pattern to repeat itself 4 times horizontally and verti
cally.
...rect x="0" y="0" width=".125" height=".125" fill="url(#gradient2)"/> <circle cx=".125" cy=".125" r=".1" fill="url(#gradient1)" fill-opacity="0.5"/> </pattern> now, because the pattern content is in the same unit system as the pattern, we don't have to offset the box so that the pattern starts in the correct place, and if the object size was changed to a larger one, the pattern would automati
cally scale so that it had the same number of objects and repeats inside it.
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
for files loaded lo
cally, it first looks in a cache of filename extension to media type mappings (stored in a mozilla profile file
called mimetypes.rdf), and if it doesn't find a media type there, it asks the operating system.
...problems in the way mozilla obtains the media type for files loaded lo
cally can occur in two ways.
...make sure the "do this automati
cally for files like this from now on" checkbox is checked.
Web security
newly issued certificates are 'logged' to publicly run, often independent ct logs which maintain an append-only, cryptographi
cally assured record of issued tls certificates.
... mixed content an https page that includes content fetched using cleartext http is
called a mixed content page.
...typi
cally, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example.
XML introduction - XML: Extensible Markup Language
instead, you define your own tags designed specifi
cally for your needs.
...most importantly, since the fundamental format of xml is standardized, if you share or transmit xml across systems or platforms, either lo
cally or over the internet, the recipient can still parse the data due to the standardized xml syntax.
... entities like html, xml offers methods (
called entities) for referring to some special reserved characters (such as a greater than sign which is used for tags).
current - XPath
the following two are symanti
cally equivalent.
...moreover, the latter two are semanti
cally equivalent.
... <xsl:value-of select="current()"/> <xsl:value-of select="foo/bar[current() = x]"/> <xsl:variable name="current" select="current()"/> <xsl:value-of select="foo/bar[$current = x]"/> and the next code is also semanti
cally equivalent to the latter two, since the .
Loading and running WebAssembly code - WebAssembly
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!
...your code might look something like this: webassembly.instantiatestreaming(fetch('mymodule.wasm'), importobject) .then(obj => { //
call an exported function: obj.instance.exports.exported_func(); // or access the buffer contents of an exported memory: var i32 = new uint32array(obj.instance.exports.memory.buffer); // or access the elements of an exported table: var table = obj.instance.exports.table; console.log(table.get(0)()); }) note: for more information on how exporting from a webassembly module works, have a ...
...again, assuming our module is
called simple.wasm: create a new xmlhttprequest() instance, and use its open() method to open a request, setting the request method to get, and declaring the path to the file we want to fetch.
Communicating With Other Scripts - Archive of obsolete content
content scripts that have been loaded into the same document by different methods, or the same method
called more than once, can pass messages directly to each other using the dom postmessage() api or a customevent.
... messaging from content script to page script suppose we have a page
called "listen.html" hosted at "my-domain.org", and we want to send messages from the add-on to a script embedded in that page.
Testing the Add-on SDK - Archive of obsolete content
this suite basi
cally tests cfx xpi's ability to produce the xpi files that we expect it to.
... with travis if you merely make a pull request for the mozilla/addon-sdk then all of the jpm tests mentioned above will be run on travis-ci automati
cally and you will see the pass/fail results with a link to the log in the github pull request.
hotkeys - Archive of obsolete content
usage to define a hotkey combination, create a hotkey object, passing it the combination and a function to be
called when the user presses that combination.
...for example, accel-s is typi
cally used to save a file, but if you use it for something completely different, then it would be extremely confusing for users.
console/traceback - Archive of obsolete content
get() returns json : returns the json representation of the stack at the point that this function is
called.
...if no argument is provided, the stack at the point this function is
called is used.
content/worker - Archive of obsolete content
calling the self.postmessage() function from a content script will asynchronously emit the message event on the corresponding worker.
... detach this event is emitted when the document associated with this worker is unloaded or the worker's destroy() method is
called.
core/namespace - Archive of obsolete content
let sandboxes = ns(); function widget(options) { let { element, contentscript } = options; let widget = object.create(widget.prototype); view.
call(widget, options.element); sandboxes(widget).sandbox = cu.sandbox(element.ownerdocument.defaultview); // ...
... }; widget.prototype.destroy = function destroy() { view.prototype.destroy.
call(this); // ...
frame/hidden-frame - Archive of obsolete content
parameters options : object required options: name type onready function,array functions to
call when the frame is ready to load content.
... you must specify an onready
callback and refrain from using the hidden frame until the
callback gets
called, because hidden frames are not always ready to load content the moment they are added.
places/history - Archive of obsolete content
// we'd compose the query with the following options let lastweek = date.now - (1000*60*60*24*7); search( // first query looks for all entries before last week with 'ruby' [{ query: "ruby", to: lastweek }, // second query searches all entries after last week with 'javascript' { query: "javascript", from: lastweek }], // we want to order chronologi
cally by visit date { sort: "date" } ).on("end", function (results) { // results is an array of objects containing visit data, // sorted by visit date, with all entries from more than a week ago // that contain 'ruby', *in addition to* entries from this last week // that contain 'javascript' }); globals functions search(queries, options) queries can be performed on history entries by pas...
... end the end event is
called when all search results have returned.
remote/child - Archive of obsolete content
methods forevery
calls the
callback for every existing frame and any new frames created in the future.
...listeners are automati
cally removed when this frame is destroyed.
system/events - Archive of obsolete content
listener : function function that will be
called when an event is fired, with a single event object as argument.
... listener : function function that will be
called when an event is fired.
test/assert - Archive of obsolete content
this function is only
called by the unit test framework, and not by unit tests themselves.
... for all other object pairs, including array objects, equivalence is determined by having the same number of owned properties (as verified with object.prototype.hasownproperty.
call), the same set of keys (although not necessarily the same order), equivalent values for every corresponding key, and an identical "prototype" property.
cfx to jpm - Archive of obsolete content
the current tool is
called jpm, and is based on node.js.
... 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.
Add a Context Menu Item - Archive of obsolete content
you don't need to add it: once you have constructed the item, it is automati
cally added in the correct context.
...typi
cally you'd store the image in your add-on's "data" directory, and construct the url using self.data.url(): var self = require("sdk/self"); var contextmenu = require("sdk/context-menu"); var menuitem = contextmenu.item({ label: "log selection", context: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' + ' var text = window.getselection().tostrin...
Adding a Button to the Toolbar - Archive of obsolete content
create a directory
called "data", mkdir data and save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png then open the file
called "index.js" in the root of your addon directory and add the following code to it: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, ...
...if you specify a collection of icons in different sizes the browser will automati
cally choose the best fit for the screen resolution and the place in the browser ui that hosts the button.
Storing annotations - Archive of obsolete content
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 annotati...
... these three files can all go in a new subdirectory of data which we will
call list.
Display a Popup - Archive of obsolete content
function handleclick(state) { text_entry.show(); } // when the panel is displayed it generated an event
called // "show": we will listen for that event and when it happens, // send our own "show" event to the panel's script, so the // script can prepare the panel for display.
... text_entry.on("show", function() { text_entry.port.emit("show"); }); // listen for messages
called "text-entered" coming from // the content script.
Open a Web Page - Archive of obsolete content
to do this, pass a
callback function into open().
... the
callback is assigned to the onready property, and will be passed the tab as an argument: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onready: function onready(tab) { console.log(tab.title); } }); even then, you don't get direct access to any content hosted in the tab.
Alerts and Notifications - Archive of obsolete content
basic modal alert alert('hello'); pop-ups the following code presents a non-modal pop-up, which automati
cally disappears after an appropriate delay.
... var message = 'another pop-up blocked'; var box = gbrowser.getnotificationbox(); var notification = box.getnotificationwithvalue('popup-blocked'); if (notification) { notification.label = message; } else { var buttons = [{ label: 'button', accesskey: 'b', popup: 'blockedpopupoptions',
callback: null }]; let priority = box.priority_warning_medium; box.appendnotification(message, 'popup-blocked', 'chrome://browser/skin/info.png', priority, buttons); } ...
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', 'quadraticcurveto', 'rect', 'restore', 'rotate', 'save', 'scale', 'settransform', 'stroke', 'strokerect', 'stroketext', 'transform', 'translate']; var gettermetho...
... var canvas = document.createelement('canvas'); var ctxt = canvas.getcontext('2d'); function loadimagefile(url,
callback) { var image = new image(); image.src = url; return new promise((accept, reject) => { image.onload = accept; image.onerror = reject; }).then(accept => { canvas.width = this.width; canvas.height = this.height; ctxt.clearrect(0, 0, this.width, this.height); ctxt.drawimage(this, 0, 0); accept(canvas.todataurl()); }); } usage: loadimagefile('myimage.jpg').
Progress Listeners - Archive of obsolete content
the tabbrowser only notifies you of the events for which you provide a
callback.
... onstatechange: function() {}, onprogresschange: function() {}, onstatuschange: function() {}, onsecuritychange: function() {} }; window.addeventlistener("load", function() { myextension.init() }, false); window.addeventlistener("unload", function() { myextension.uninit() }, false); note: if you use the same listener for more than one tab/window, use awebprogress.domwindow in the
callback methods to obtain the tab/window which triggers the state change or event.
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 automati
cally translated from \"" + smimetype + "\" to \"text/ecmascript\".
...let us
call this function createecmasrc() and let us associate it with the c mime types: rosetta_c.js: a c compiler /* c compiler for rosetta */ (function () { if (!window.rosetta) { return; } /* this function takes as argument a plain text (in this case, a code written in c) and returns another plain text written in ecmascript */ function createecmasrc (scsrc) { /* this is just an empty exam...
Windows - Archive of obsolete content
re-using and focusing named windows while specifying the name parameter to window.open or window.opendialog will prevent multiple windows of that name from opening, each
call will actually re-initialize the window and thus lose whatever state the user has put it in.
... similarly, you can get the current inner window id using the nsidomwindowutils attribute currentinnerwindowid: var util = win.queryinterface(components.interfaces.nsiinterfacerequestor).getinterface(components.interfaces.nsidomwindowutils); var windowid = util.currentinnerwindowid; programati
cally modifying html when attempting to modify html elements, it is important to specify the namespace.
Extension Packaging - Archive of obsolete content
the extension will be found automati
cally by the extension manager the next time the application is launched.
...a special kind of extension xpi,
called the multiple item package, explains how to create this kind of package.
Adding Events and Commands - Archive of obsolete content
all nodes observing it will automati
cally have those attribute values set or removed as well.
...--> <menuitem id="xulschoolhello-hello-menu-item" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.helloitem.accesskey;" command="xulschoolhello-hello-command" /> commands allow you to keep your javascript
calls in a single place, avoiding code repetition and possible bugs.
Adding sidebars - Archive of obsolete content
one common use for a stack is to have an image background that stretches horizontally and verti
cally depending on the size of the foreground object: <stack> <hbox flex="1"> <image src="chrome://xulschoolhello/skin/stack-bg.png" flex="1" /> </hbox> <hbox> <!-- some content here.
... adding style to a tree can also be challenging, which is why there's a guide specifi
cally covering how to style a tree.
Introduction - Archive of obsolete content
it is only one part of the development landscape, but given that it's practi
cally exclusive to mozilla, it tends to be used to identify all mozilla-related development.
...even this project,
called xul school, covers several other technologies such as javascript, css, xbl and xpcom.
User Notifications and Alerts - Archive of obsolete content
etnotificationbox(); 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(); }; // similarly for decline button.
...for mac os x, support was added on firefox 3, and only through a third-party tool
called growl.
Session store API - Archive of obsolete content
in order to properly restore your extension's state when a tab is restored, it needs to use the session store api's settabvalue() method to save any data it will need in order to restore its state, and then
call gettabvalue() to retrieve the previous setting when the tab is restored.
... the tab's persistent xul attributes (those saved due to
calls to persisttabattribute()) and permissions are restored.
Add-ons - Archive of obsolete content
here we
call the event myextensionevent.
... legacy add-ons this section contains links to documentation for legacy technology for add-on development, including: legacy extensions for firefox for android add-ons that work with desktop firefox do not automati
cally work in firefox for android: overlay extensions this page contains links to documentation for the approach to developing extensions for gecko-based applications which uses: performance best practices in extensions one of firefox's great advantages is its extreme extensibility.
Underscores in class and ID Names - Archive of obsolete content
for example, a function whose job is to "get the length of a string" might be
called get_string_length, and a variable representing the number of people who voted republican might be voted_republican.
...although underscores are, as of this writing, techni
cally permitted in class and id names, there are many historical and practical reasons why they should be avoided.
XUL user interfaces - Archive of obsolete content
copy and paste the content from here, making sure that you scroll to get all of it: // xul demonstration var 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(thedate) } // internal function setday(adate) { if (currentday) currentday.setattribute("disabled", "true") if (adate == null) currentday = null else { var d = adate.getday() currentday = daybox.firstchild while (d-- > 0) currentday = currentday.nextsibling currentday.removeattribute("disabled") } datebox.focus(); } function showstatus(adate) { if (adate == null) { status.removeattribute("warning") status.setattri...
Creating a status bar extension - Archive of obsolete content
many of the concepts introduced here apply to any xul-based application; however, to keep from getting completely overwhelmed, we're going to focus specifi
cally on firefox.
...we do this by embedding inside the statusbar named "status-bar" -- which is the firefox browser window's status bar -- a new statusbarpanel object we
call "status-bar-sample-1".
List of Mozilla-Based Applications - Archive of obsolete content
frizione javascript development, testing and deployment environment uses mozilla rhino geckofx embeddable gecko gjs javascript bindings for gnome globalmojo browser that raises money for your favorite causes gluescript a javascript engine which can be used as a general purpose language uses mozilla spidermonkey and formerly
called wxjavascript gnome operating system gnome 3 will use spidermonkey through gjs google adwords editor editor google gadgets for linux google’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-...
...r wysiwyg html editor unofficial bug-fix release of nvu kylo video browser uses gecko biofortis labmatrix web-accessible software application used for information management and integration of patient clinical, specimen, genetic and molecular assay data based on xul liaison groupware client for novell’s email and collaboration server previously
called mozngw linbox kiosk browser (fr) web browser dedicated browser for french prefecture and town hall litl internet computer for home uses spidermonkey and gecko lizilayers gis application 3liz also creates some gis firefox add-ons logitech harmony remote software software for remote control device uses gre or xulrunner longman d...
Localizing an extension - Archive of obsolete content
string = stringsbundle.getstring('changestring') + " "; var openstring = stringsbundle.getstring('openstring') + " "; var lowstring = stringsbundle.getstring('lowstring') + " "; var highstring = stringsbundle.getstring('highstring') + " "; var volumestring = stringsbundle.getstring('volumestring') + " "; this code gets a reference to the string bundle element we added to stockwatcher2.xul by
calling document.getelementbyid(), specifying the id "string-bundle".
... then it fetches all the strings we need from the bundle, one by one, by
calling the string bundle's getstring() method, passing the appropriate key for each string.
Images, Tables, and Mysterious Gaps - Archive of obsolete content
of course, documents authored in xhtml strict or html strict will trigger the "standards" rendering mode, so we're going to go through two basic ways to address the problem in strict documents, and a number of ways to
call on these "fixes." setting images to be blocks the first choice, and one that will work for most graphi
cally-intense designs, is to convert the image from being an inline element to a block-level element.
... any image in a table cell with other images should be verti
cally aligned with the bottom of the line box.
Source Navigator - Archive of obsolete content
with it, you can edit your source code, display relationships between classes and functions and members, and display
call trees.
... you can also build your projects, either with your own makefile, or by using source-navigator's build system to automati
cally generate a makefile.
Using XML Data Islands in Mozilla - Archive of obsolete content
html5 has a more general feature
called "data blocks" that can carry almost any textual data, including xml.
...for this demo, you must create an external document
called purchase_order.xml: <!doctype html> <html> <head> <title>xml data block demo</title> <script> function rundemo() { var doc = document.getelementbyid("purchase-order").contentdocument; var lineitems = doc.getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "lineitem"); var firstprice = lineitems[0].getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "price...
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 ...
...if you have trouble getting the moz-byteshift.pl script to work lo
cally, there is also an online version available.
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
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").
...make sure the mimetypes of your html embed tags match the mimetype specified in your nprt.rc file and the top of your npp_gate.cpp file version issues if vc++ compiler throws you error c2664 on 'drawtext' function
call, you may replace it by 'drawtexta'.
Finding the file to modify - Archive of obsolete content
xul, which is short for xml-based user interface language (and is pronounced like "zool"), is an xml-based language specifi
cally designed for describing application interfaces.
... each window and dialog box in mozilla is defined by a single xul file (in some cases other xul files
called overlays contribute portions of another window's structure).
Documentation for BiDi Mozilla - Archive of obsolete content
in a bidi-enabled document, the following things happen: during a reflow, nsbidipresutils::resolve is
called.
...where the system is capable of tasks such as reversing and shaping text, symmetric swapping, numeric translation, etc., no special text rendering is needed, though there may be a
call to a native api to set the base text direction (for example settextalign on windows).
Downloading Nightly or Trunk Builds - Archive of obsolete content
so to figure out how to download a cutting edge or bleeding edge or 'beta' version of firefox, you need to look for a "build" (which is developer-speak for the packaged files you can download) of 1.9.1 (the number of the underlying 'platform'
called 'gecko' or 'mozilla' that firefox uses).
... if you need to download builds often, most builds can be downloaded semi-automati
cally and saved with a convenient name using mozdownload.
Syncing custom preferences - Archive of obsolete content
for example, if your add-on had a pref
called extension.frobnaz.foobar, to have it synced, create a bool preference
called services.sync.prefs.sync.extension.frobnaz.foobar and set it to true.
... the most convenient place for this would be your add-on's default preferences, though if you want to give the user a choice to opt-in, you can also do it programmati
cally.
Helper Apps (and a bit of Save As) - Archive of obsolete content
calls show() on the nsihelperapplauncherdialog, which asynchronously puts up the helper app dialog.
... helper app dialog this is our implementation of nsihelperapplauncherdialog it
calls back to the nsexternalapphandler to let it know what the user picked saving to disk if a user decides to "save to disk", we just move/copy the temporary file over to the chosen location once the download completes.
First run - Archive of obsolete content
you can also register a
callback that will be
called after installation.
... </p> </> }; in this example, the page at http://example.com/myjetpack becomes the first-run page: var manifest = { firstrunpage: "http://example.com/myjetpack" }; first-run
callback you can register a
callback that will be
called after your jetpack has been successfully installed.
First Run - Archive of obsolete content
you can also register a
callback that will be
called after installation.
... </p> </> }; in this example, the page at [http://example.com/myjetpack] becomes the first-run page: var manifest = { firstrunpage: "http://example.com/myjetpack" }; first-run
callback you can register a
callback that will be
called after your jetpack has been successfully installed.
Settings - Archive of obsolete content
jetpack will automati
cally generate a user interface based on the specification.
...jetpack will automati
cally generate a user interface from this specification that users of your jetpack may use to customize the settings.
Jetpack Snippets - Archive of obsolete content
> <script><![cdata[ //firebug lite bookmarklet code: var firebug=document.createelement('script'); firebug.setattribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); document.body.appendchild(firebug); (function(){if(window.firebug.version){firebug.init();}else{settimeout(arguments.
callee);}})();void(firebug); ]]></script> </body></html>, width: 800, //wide enough to use firebug onselect: function(slide) { slide.slide(800, true); }});
calling into a slidebar from the global jetpack scope jetpack.slidebar.append({ onready: function (slide) { //
call out to a global function, passing the slidebar object exinitslidebar(slide); },...
... ...});function exinitslidebar(aslidebar) { // this variable will now be global slider = aslidebar;} // then, accessing the slidebar htmlvar tl = slider.contentdocument.getelementbyid("thumblist"); // or
calling slidebar api methods or accessing propertiesslider.notify(); ...
Settings - Archive of obsolete content
jetpack will automati
cally generate a user interface based on the specification.
...jetpack will automati
cally generate a user interface from this specification that users of your jetpack may use to customize the settings.
Mozilla Crypto FAQ - Archive of obsolete content
as a mirror of the mozilla ftp site you will automati
cally be distributing open source encryption code as well.
...("usc" stands for "united states code.") the eaa was passed as temporary legislation; however the president of the united states has periodi
cally issued orders to continue the eaa and ear, exercising authority under the international emergency economic powers act, also known as 50 usc 1701-1706.
Plugin Architecture - Archive of obsolete content
sequence of events in content a content node for a plugin dom element gets created in bindtotree (usually) or another function, it
calls loadobject loadobject either notices directly that it is dealing with a plugin, or it starts a network request and notices this in onstartrequest when it realizes that, it tries to create a frame, if anotify is true and no frame exists yet if a frame exists now, it is asked to instantiate the plugin that was the normal case.
...(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 ...
Extensions - Archive of obsolete content
extensions typi
cally overlay the host application's ui to add toolbar buttons, menus and other features.
...to support prism specifi
cally, you'll need to add prism to the list of target applications in the extension's install.rdf file.
Installer - Archive of obsolete content
this means that when you double-click or launch a *.webapp file, prism is launched and automati
cally opens the web application.
... current windows and mac installs automati
cally associate *.webapp with prism.
PyDOM - Archive of obsolete content
note that you can stick arbitrary values on any dom object - this is what js
calls 'expandos'.
...using python ideally, you just tell mozilla you are using python, and magi
cally you can use python instead of javascript.
Same origin policy for XBL - Archive of obsolete content
for the nsidomdocumentxbl interface's nsidomdocumentxbl.addbinding() and nsidomdocumentxbl.loadbindingdocument() methods, the originating principal is the one of the script making the
call, or the principal of the document the
call is made on if there isn't a script.
...a
call to checloaduriwithprincipal() is done to make sure the principal is able to link to the given uri in the first place.
SpiderMonkey coding conventions - Archive of obsolete content
macros are generally all_caps and underscored, to
call out potential side effects, multiple uses of a formal argument, etc.
... linkage dll entry points have their return type expanded within a js_public_api() macro
call, to get the right windows secret type qualifiers in the right places for all build variants.
File object - Archive of obsolete content
pipelines are implemented with the popen() system
call.
... 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.
Merging TraceMonkey Repo - Archive of obsolete content
histori
cally, auto-merge doesn't mess up much.
...you can't really back out a merge easily, so rambo-ing a fix or figuring out how to back out an offending changeset is the only way it has been resolved histori
cally.
Abc Assembler Tests - Archive of obsolete content
* * ***** end license block ***** */ function main() { getlocal0 pushscope findproperty start pushstring "instructions that start with the letter l"
callpropvoid start 1 newfunction .function_id(runtest) getlocal0
call 0 findproperty end
callpropvoid end 0 returnvoid } function runtest() { // test null <= null == true findproperty compare_stricteq pushstring "null lessequals null" // testname pushtrue // expected pushnull pushnull lessequals // actual
callpropvoid compare_stricteq 3 // ...
...use .try / .catch to catch typeerror // convert_o null .try { pushnull convert_o pop findproperty fail pushstring "convert_o null" pushstring "exception should have been thrown: typeerror: error #1009: cannot access a property or method of a null object reference." getlocal1
callpropvoid fail 3 jump finished_convert_o_null } .catch { getlocal0 pushscope setlocal2 // save typeerror findproperty compare_typeerror pushstring "convert_o null" // test name pushstring "typeerror: error #1009" // expected getlocal2 // actual
callpropvoid compare_typeerror 3 } finished_convert_o_null: } ...
Actionscript Acceptance Tests - Archive of obsolete content
(see bug 587093 for details.) specifying multiple .abcs: if you desire to run a test with multiple .abc files (e.g: avmshell a.abc b.abc testname.abc) there is a special avm_args directive
called multiabc that is specified surrounded by two pipe (|) symbols: |multiabc| $dir/testname_support/a.abc $dir/testname_support/b.abc the extra abc files will usually be placed in a _support dir (see additional files below).
... the underscore is necessary otherwise the buildbot system will delete the .abc before starting up a testrun (not an issue when running lo
cally, but makes it easy to differentiate between binary-only abc files and generated abcs.
Tamarin build documentation - Archive of obsolete content
example
call to build on an x86_64 machine with the 10.5 sdk: $ ../configure.py --mac-sdk=105 --target=x86_64-darwin if asc is not set, you will need to add asc.jar to the utils directory in tamarin-redux (bug 631641).
... tryserver etiquette the sandbox is not a good substitute for running the regression tests lo
cally to catch obvious problems.
Tamarin Build System Documentation - Archive of obsolete content
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 lo
cally?
... the list of smoke tests are located in the tamarin-repository, test/run-smokes.txt, assume the start directory is test format is cd testdir; command to run test above the test should be a # comment describing why the test in the smokes, when test failed, possibly a bugzilla bug the tests can be run by following the above instructions for running buildbot scripts lo
cally and executing the all/run-smoke-tests.sh as a rule any test failure should be immediately added to the top of the smoke test list so the list is prioritized how to exclude tests from acceptance or mark them as known failures?
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
what is a hardship is that addresses of dynamic variables, those allocated on the
call stack, in a function's local frame, are not valid across thread boundaries.
...what is probably more likely to cause problems is passing addresses of automati
cally allocated variables to a function that wends its way though arbitrary amounts of convoluted logic, and finds its way into an object that is shared.
Venkman Internals - Archive of obsolete content
it will mark these with a "tick" as you
call it.
...in order to set a breakpoint in a particular function, you'll want to
call scriptwrapper.setbreakpoint(pc[, parentbp]); where |pc| is the program counter location to set the breakpoint, and |parentbp| is an optional "future breakpoint" object to use as the parent for this breakpoint.
Writing textual data - Archive of obsolete content
var chunk = converter.convertfromunicode(your_string); os.write(chunk, chunk.length); // repeat as needed for further strings at the end, you need to
call finish and write its data to the stream.
... note that not many character encodings need it, but for those that do
calling this is important for proper output.
DOM Interfaces - Archive of obsolete content
typi
cally used with an (arbitrary) anonid attribute to retrieve a specific anonymous child in an xbl binding.
...the binding document can then be modified programmati
cally using the dom.
XBL - Archive of obsolete content
xml binding language (xbl, sometimes also
called extensible bindings language) is a language for describing bindings that can be attached to elements in other documents.
... the element that the binding is attached to,
called the bound element, acquires the new behavior specified by the binding.
XML in Mozilla - Archive of obsolete content
to fully implement xlink, we need something
called a link manager.
...we'd really like to get tests that can be run automati
cally (this would require knowledge of web development; document.load() and/or xml extras might be needed), but probably most of the bugs we get have just been found by normal people trying to do something that works in some other browser and does not work in mozilla.
toString - Archive of obsolete content
method of installversion object syntax string version = installversion.tostring ( initobj ); parameters the tostring method has the following parameter: initobj initobj is an installversion object whose init method has been
called.
...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(); ...
addFile - Archive of obsolete content
typi
cally, absolute pathnames are only used for shared components, or components that come from another vendor, such as /microsoft/shared/msvcrt40.dll.typi
cally, relative pathnames are relative to the main pathname specified in the initinstall method.
...to move this and all other files to their final location,
call the performinstall method after you've successfully added all files.
confirm - Archive of obsolete content
this string is typi
cally in the form of a prompt for the user (e.g., "are you sure you want to delete the selected file(s)?").
...the following examples show the result of
calling confirm() with three buttons 0='a', 1='b' and 2='c'.
getWinProfile - Archive of obsolete content
once you have this object, you can
call its methods to retrieve strings from the file or to add strings to the file.
...example to edit the win.ini file, you would create a winprofile object with this
call: var mywinprofileobj = getwinprofile (getfolder("windows"), "win.ini"); ...
patch - Archive of obsolete content
typi
cally, absolute pathnames are only used for shared components, or components that come from another vendor, such as /microsoft/shared/msvcrt40.dll.
... typi
cally, relative pathnames are relative to the main pathname specified in the initinstall method.
setPackageFolder - Archive of obsolete content
you should only
call this method once, and you should always
call it immediately after you
call initinstall.
... if you
call setpackagefolder multiple times, the last folder set is the folder that is saved in the client version registry and used as the default for other installations.
Install Object - Archive of obsolete content
the following two lines, for example, are equivalent: f = getfolder("program"); f = install.getfolder("program"); an installation script is composed of
calls to the install object, and generally takes the following form: initialize the installation
call initinstall with the name of the installation and the necessary registry and version information.
... add the files to the installation add files to the installation by
calling getfolder to get file objects and passing those object refs to addfile as many times as necessary.
Return Codes - Archive of obsolete content
pi package cannot be read invalid_arguments -208 bad parameters to a function illegal_relative_path -209 illegal relative path user_cancelled -210 user clicked cancel on install dialog install_not_started -211 a problem occurred with the parameters to initinstall, or initinstall was not
called first silent_mode_denied -212 the silent installation privilege has not been granted.
... download_error -228 problem with download script_error -229 error in the script already_exists -230 file already exists lo
cally is_file -231 expected target directoy and got file source_does_not_exist -232 source file/dir not found source_is_directory -233 expected source file and got directory source_is_file -234 expected source directory and got file insufficient_disk_space -235 no...
writeString - Archive of obsolete content
values are not actually written until performinstall is
called.
... 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"); ...
panel.fade - Archive of obsolete content
« xul reference homefadetype: one of the values belowthe fade attribute, which may only be used with arrow panels, lets you set up a panel that will automati
cally fade away after a short time.
... nonethe panels doesn't automati
cally fade away.slowthe panels slowly fades away after a short time.fastthe panels quickly fades away after a short time.
state - Archive of obsolete content
this attribute will be updated automati
cally as the splitter is moved, and is generally used in a stylesheet to apply a different appearance for each state.
... dragging the user is current adjusting the position of the splitter, typi
cally by dragging it with the mouse.
Working With Directories - Archive of obsolete content
each
call to nsifile.append() navigates to a further subdirectory.
...for each item, nsifile.isfile() is
called to check if an item is a file and lastmodifiedtime (nsifile.attributes) attribute is compared with the time of the lastmod reference.
How to implement a custom XUL query processor component - Archive of obsolete content
from the beginning of the name var name = avar.tostring().slice(1); return this._data[name]; }, // return an object instead of a string for convenient comparison purposes // or null to say just use string value getbindingobjectfor: function(avar) { return null; }, //
called when a rule matches this item.
..., abuilder, ashoulddelaybuilding) { // todo: parse the adatasources variable // for now, ignore everything and let's just signal that we have data return this._data; }, initializeforbuilding: function(adatasource, abuilder, arootnode) { // perform any initialization that can be delayed until the content builder // is ready for us to start }, done: function() { //
called when the builder is destroyed to clean up state }, compilequery: function(abuilder, aquery, arefvariable, amembervariable) { // outputs a query object.
onFindAgainCommand - Archive of obsolete content
« xul reference home onfindagaincommand( findprevious ) return type: no return value
call this method to handle your application's "find next" and "find previous" commands.
... you should specify true as the input parameter to perform a "find previous" operation, or false to perform a "find next." example typi
cally, you'll simply bind this method to your "find next" and "find previous" commands, like this: <command name="cmd_find_previous" oncommand="gfindbar.onfindagaincommand(true);"/> <command name="cmd_find_next" oncommand="gfindbar.onfindagaincommand(false);"/> ...
advance - Archive of obsolete content
« xul reference home advance( pageid ) return type: no return value
call this method to go to the next page.
...the code in the onwizardnext attribute is
called before the page is changed.
cancel - Archive of obsolete content
« xul reference home cancel() return type: no return value
call this method to cancel and close the wizard.
... the code in the onwizardcancel attribute is
called before the wizard is cancelled.
extra1 - Archive of obsolete content
« xul reference home extra1() return type: no return value
call this method to simulate clicking the extra1 button.
... the code in the onextra1 attribute is
called.
extra2 - Archive of obsolete content
« xul reference home extra2() return type: no return value
call this method to simulate clicking the extra2 button.
... the code in the onextra2 attribute is
called.
rewind - Archive of obsolete content
« xul reference home rewind() return type: no return value
call this method to go back a page.
...the code in the onwizardback attribute is
called before the page is changed.
Namespaces - Archive of obsolete content
an xml namespace is identified by an unique name (
called a uri, not a url, even though it can look like a url).
... <foo/> the answer is that it's in no namespace, or alternately, it's in the namespace denoted by the empty string: <foo xmlns=""/> this second example is semanti
cally equivalent to the first.
Providing Command-Line Options - Archive of obsolete content
myapphandler", // changeme: generate a unique id classid: components.id('{2991c315-b871-42cd-b33f-bfee4fcbf682}'), // changeme: change the type in the contractid to be unique to your application contractid: "@mozilla.org/commandlinehandler/general-startup;1?type=myapp", _xpcom_categories: [{ category: "command-line-handler", // changeme: // category names are sorted alphabeti
cally.
...r("incorrect parameter passed to -viewapp on the command line."); } // changeme: change "myapp" to your command line flag (no argument) if (cmdline.handleflag("myapp", false)) { openwindow(chrome_uri, null); cmdline.preventdefault = true; } }, // changeme: change the help info as appropriate, but // follow the guidelines in nsicommandlinehandler.idl // specifi
cally, 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" }; ...
Filtering - Archive of obsolete content
whether a triple or member is added or removed, the template must be rebuilt by
calling the rebuild method.
...when a choice is made, the applyfilter function as shown above is
called and the template content gets rebuilt with the desired filter applied.
The Joy of XUL - Archive of obsolete content
it also enables javascript objects to present xpcom compliant interfaces to be
called by xpcom objects.
...the ui for the month and week views was practi
cally rewritten while the application logic remained virtually unchanged.
Things I've tried to do with XUL - Archive of obsolete content
while this works at first, after a number of rows have been added it breaks and stops displaying the first cell (the one specified by the appenditem
call).
... instead, you must build up your own listitem full of listcells, and then add that listitem to the listbox, using generic dom
calls: var row = document.createelement('listitem'); // create and attach 1st cell var cell = document.createelement('listcell'); cell.setattribute('label', label ); cell.setattribute('value', value ); row.appendchild( cell ); // create and attach 2nd cell cell = document.createelement('listcell'); cell.setattribute('label', label2 ); cell.setattribute('value', value2 ); row.appendchild( cell ); // etc // ...
Tree Widget Changes - Archive of obsolete content
the column objects are created automati
cally, so you don't have to write any extra code.
...when the user clicks the cell, the view's setcellvalue method will be
called with either the value true or false.
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
for example, a custom checkbox might have a checked property which needs to be changed when the user clicks the checkbox: <handlers> <handler event="mouseup" action="this.checked=!this.checked"/> </handlers> when the user clicks and releases the mouse button over the check box, the mouseup event is sent to it, and the handler defined here is
called, causing the state of the checked property to be reversed.
... if set, the handler is only
called when the modifier is pressed.
Additional Install Features - Archive of obsolete content
finally, we
call the file.copy function which copies the source file to the destination.
...you can
call this function at any point during the installation script to determine whether an error occured during the last operation.
Anonymous Content - Archive of obsolete content
xbl content xbl can be used to automati
cally add a set of elements inside another element.
...override the bound element the anonymous content is created automati
cally whenever a binding is attached to an element.
Creating Dialogs - Archive of obsolete content
second, you could pass a function or object as one of the arguments when creating the dialog, then
call that function or modify the object in the opened dialog.
...if you try the example above, you will find that the dook() function is
called when the ok button is pressed and the docancel() function is
called when the cancel button is pressed.
Creating a Window - Archive of obsolete content
however, one additional flag,
called 'chrome' is necessary to indicate to the browser that this is a chrome document to open.
...create a file
called findfile.xul and put it in the content directory specified in the findfile.manifest file (we've created in the previous section).
Introduction - Archive of obsolete content
xul is one such language designed specifi
cally for building portable user interfaces.
...this is done using a feature of xul
called an overlay, which allows the ui provided from one source, in this case, the firefox browser, to be merged together with the ui from the extension.
Manipulating Lists - Archive of obsolete content
this interface provides a number of functions specifi
cally for handling multiple selection.
...typi
cally, you will use these properties to iterate over the list and perform some operation for each item.
Modifying the Default Skin - Archive of obsolete content
(although the underlying code for mozilla
calls them skins and the user interface
calls them themes, they're both referring to the same thing).
... customize with userchrome.css if you place a file
called 'userchrome.css' in a directory
called 'chrome' inside your user profile directory, you can override settings without changing the archives themselves.
Persistent Data - Archive of obsolete content
remembering state when building a large application, you will typi
cally want to be able to save some of the state of a window across sessions.
...you will typi
cally want to save toolbar states, window positions and whether certain panels are displayed or not, but you can save almost anything.
Trees and Templates - Archive of obsolete content
note in the image that additional child elements below the top-level elements have been added automati
cally.
...this becomes useful for certain datasources where the data is determined dynami
cally.
Using spell checking in XUL - Archive of obsolete content
checking the spelling of a word to check the spelling of a word, you must first create an interface to the mozispellcheckingengine component and then
call the check() method on the string you wish to test.
... .getservice(components.interfaces.mozipersonaldictionary); if (mpersonaldictionary.check("kat", gspellcheckengine.dictionary)) { // it's spelled correctly accourdly to user personal dictionary } else { // it's spelled incorrectly } } getting a list of suggestions to get a list of suggestions for a misspelled word, you
call the suggest() method, specifying the word and an object to be filled with an array of possible suggestions.
XUL Changes for Firefox 1.5 - Archive of obsolete content
this is used typi
cally on gnome systems where possible values are: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network.
... loading overlays dynami
cally xul now supports loading overlays dynami
cally with the document.loadoverlay function.
button - Archive of obsolete content
it is typi
cally rendered as a grey outset rectangle.
... orient type: one of the values below used to specify whether the children of the element are oriented horizontally or verti
cally.
commandset - Archive of obsolete content
typi
cally, this is used to update menu commands such as undo and cut based on when an event occurs.
...you can send a custom event by
calling the updatecommands method of the command dispatcher.
description - Archive of obsolete content
</description> this is a long section of text that will not word wrap <description value="this is a long section of text that will not word wrap"> </description> this is a long section of dynami
cally controlled text that will word wrap <description id="desc" style="width: 300px"></description> document.getelementbyid('desc').textcontent = "this is a long section of dynamic message text that will word wrap"; attributes crop type: one of the values below if the label of the element is too big to fit in its given space, the text will be cropped on the side specified...
...typi
cally, this will cause the text to appear bold.
scrollbox - Archive of obsolete content
if their container doesn't give enough room to hold them (geometri
cally) what happens depends on the enclosing elements; often the content is just clipped off on the bottom or right (depending on what's too big to fit).
... note that this example doesn't use a scrollbox tag; you only need that tag if you want to programmati
cally scroll in addition to the automatic scroll bars.
splitter - Archive of obsolete content
this attribute will be updated automati
cally as the splitter is moved, and is generally used in a stylesheet to apply a different appearance for each state.
... dragging the user is current adjusting the position of the splitter, typi
cally by dragging it with the mouse.
tabs - Archive of obsolete content
onclosetab type: script code this script will be
called when the close tab button is clicked.
... onnewtab not in firefox type: script code this script will be
called when the new tab button is clicked.
treecol - Archive of obsolete content
this attribute is set automati
cally; you shouldn't adjust it yourself.
...if false or not specified, the user can adjust the size of the column, typi
cally by dragging the column header with the mouse.
Custom app bundles for Mac OS X - Archive of obsolete content
mac os x applications are typi
cally packaged as application bundles which are then distributed in .dmg (disk image) files.
... the first sub-directory is
called contents and within that directory you will place several files and folders that are needed by your application bundle.
XULRunner FAQ - Archive of obsolete content
so why is it
called xulrunner, instead of htmlrunner or something?
... xul was always the original language of choice for ui in mozilla applications and the main library is
called libxul, mostly the name is a hangover from that that has now stuck.
Getting started with XULRunner - Archive of obsolete content
call it a xul “hello world” if you want.
... this might also be simplified using a very simple shell script (i
call mine "run.sh"): #!/bin/sh /library/frameworks/xul.framework/xulrunner-bin `pwd`/application.ini linux on ubuntu, you can run the application from a terminal.
Using SOAP in XULRunner 1.9 - Archive of obsolete content
(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])); } v...
...ar req = new soaprequest(url, body); req.action = ns + '#' + method; soapclient.sendrequest(req,
callback); diff between jqsoapclient.js and sasoapclient.js 42c42 < var jsout = $.xmltojson(xdata.responsexml); --- > var jsout = xmlobjectifier.xmltojson(xdata.responsexml); 46,60c46,62 < $.ajax({ < type: "post", < url: soapclient.proxy, < datatype: "xml", < processdata: false, < data: content, < complete: getresponse, < contenttype: soapclient.contenttype + "; charset=\"" + soapclient.charset + "\"", < beforesend: function(req) { < req.setrequestheader("method", "post"); < req.setrequestheader("content-length", soapclient.contentlength); < req.setrequestheader("soapserver", soapclient.soapserver); < req.setrequestheade...
Gecko Compatibility Handbook - Archive of obsolete content
upgrade to the most recent version of hiermenu common coding and server problems this section details solutions to the most common problems affecting standards-based browsers as well as issues that may specifi
cally affect gecko browsers.
... gecko, internet explorer for mac os and internet explorer 6 all use a technique
called doctype sniffing to determine if a page is to be laid out in a fashion compatible with the older browsers or if it is to be laid out in a fashion compatible with the w3 standards.
2006-11-10 - Archive of obsolete content
benjamin smedberg has been "working on some xpt
call refactoring which will allow us to expose xpt
call via a frozen api (and c linkage)".
... he is looking for xpt
call port maintainers to submit patches to bug 349002.
2006-11-03 - Archive of obsolete content
discussions extended validation certificates major discussion this week started by gervase markham about security certificates, more specifi
cally extended validation certificates.
... 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-12-08 - Archive of obsolete content
discussions xpcom cpp to js
callback engaging discussion on a problem with trying to
call back from c++ to a javascript object using an interface the developer created with an idl.
... however, the c++
call that's supposed to be invoking the method on the javascript object is returning with 0x80004005 (ns_error_failure).
Multi-process plugin architecture - Archive of obsolete content
the
calls are transferred to the plugin process via the ipdl protocol language.
... in the plugin process, the shim layer serves as a plugin host, implementing the npn_ functions used by the plugin, and forwards the
calls to the plugin dll: multi-process plugins, also
called out of process plugins or oopp first shipped in firefox 3.6.4 on windows and linux, and in firefox 4 on mac os x.
NPByteRange - Archive of obsolete content
the only plug-in api
call that uses the npbyterange type is npn_requestread(), which lets the plug-in read specified parts of a file without downloading it.
...the browser makes a copy if it needs to keep the objects beyond the
call to npn_requestread().
NPN_DestroyStream - Archive of obsolete content
description the plug-in
calls the npn_destroystream() function to close and delete a stream.
... 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().
NPN_Enumerate - Archive of obsolete content
note: the
caller must
call npn_memfree() on the pointer received through the identifiers parameter of a successful
call to npn_enumerate to release the array of string identifiers when it is no longer needed.
... the
callee allocates this array via npn_memalloc().
NPN_Evaluate - Archive of obsolete content
description the script is evaluated in the context of the window that the
calling plugin instance (the <tt>npp</tt> argument) is loaded in.
... note: the
caller must
call npn_releasevariantvalue() to release the returned value when it's no longer needed.
NPN_InvokeDefault - Archive of obsolete content
syntax #include <npruntime.h> bool npn_invokedefault(npp npp, npobject *npobj, const npvariant *args, uint32_t argcount, npvariant *result); parameters the function has the following parameters: npp the npp indicating which plugin wants to
call the default method on the object.
...when the
caller no longer needs the result, it must
call npn_releasevariantvalue() to release it.
NPN NewStream - Archive of obsolete content
a plug-in can create another instance of itself by specifying its own mime type and a new target name in a
call to npn_newstream.
...the plug-in can use this object in subsequent
calls to npn_write to write data into the stream.
NPN_PostURL - Archive of obsolete content
npn_posturl is typi
cally asynchronous: it returns immediately and only later handles the request.
... for this reason, you may find it useful to
call npn_posturlnotify instead; this function notifies your plug-in upon successful or unsuccessful completion of the request.
NPN_Write - Archive of obsolete content
this indicates that the browser encountered an error while processing the data, so the plug-in should terminate the stream by
calling npn_destroystream().
...a plug-in can
call this function multiple times after creating a stream with npn_newstream().
NPObject - Archive of obsolete content
npobjects are reference counted objects, so
callers need to be careful to properly release acquired references to them.
...npobject behavior is implemented using the set of
callback functions defined in npclass.
NPP - Archive of obsolete content
this pointer--which is an opaque instance handle of a plug-in--identifies the instance on which api
calls should operate.
...the npp_destroy() function informs the plug-in when the npp instance is about to be deleted; after this
call returns, the npp pointer is no longer valid.
NPP_Destroy - Archive of obsolete content
the browser
calls this function when a plug-in instance is deleted, typi
cally because the user has left the page containing the instance, closed the window, or quit the browser.
... if this function is deleting the last instance of a plug-in, np_shutdown is subsequently
called.
NPP_HandleEvent - Archive of obsolete content
description the browser
calls npp_handleevent to tell the plug-in when events take place in the plug-in's window or drawable area.
...when npp_handleevent is
called, the current port is set up so that its origin matches the top-left corner of the plug-in.
NPP_Print - Archive of obsolete content
description npp_print is
called when the user requests printing for a web page that contains a visible plug-in (either embedded or full-page).
...this means that you need to convert the x-y coordinates using the windows api
call dptolp when you output text.
NPP_StreamAsFile - Archive of obsolete content
description when the stream is complete, the browser
calls npp_streamasfile to provide the instance with a full path name for a local file for the stream.
... npp_streamasfile is
called for streams whose mode is set to np_asfileonly or np_asfile only in a previous
call to npp_newstream.
NP_Shutdown - Archive of obsolete content
syntax #include <npapi.h> void np_shutdown(void); windows #include <npapi.h> void winapi np_shutdown(void); description the browser
calls this function once after the last instance of your plug-in is destroyed, before unloading the plug-in library itself.
...the browser
calls np_shutdown only when the library is finally unloaded.
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
histori
cally, most people have chosen to use an install.js script to install a plugin.
...this allows a remote update file to be read periodi
cally and an updated version of the plugin offered to the user or to mark the plugin as compatible with a wider range of applications.
Plugins - Archive of obsolete content
monitoring plugins use an observer service notification to monitor the amount of time spent executing
calls in plugins.
... scripting plugins: macromedia flash this article explains how javascript can be used to access methods from within the flash plugin, as well as how a feature
called fscommands can be used to access javascript functions from within the flash animation.
Version - Archive of obsolete content
different people and groups have largely unilaterally created specifications that they
called rss.
... note: in the list below, although rss 1.0 seems to be out of place, it is actually in the correct place chronologi
cally.
SAX - Archive of obsolete content
after the parsing process is started, handlers receive a series of
callbacks for the content of xml being parsed.
...below is an example of parsing from a string: xmlreader.parsefromstring("<f:a xmlns:f='g' d='1'><bbq/></f:a>", "text/xml"); this
call results in the following output (assuming the content handler from the example above is used): startdocument startelement: namespace='g', localname='a', qname='f:a', attributes={d='1'} startelement: namespace='', localname='bbq', qname='bbq', attributes={} endelement: namespace='', localname='bbq', qname='bbq' endelement: namespace='g', localname='a', qname='f:a' enddocument ...
Threats - Archive of obsolete content
network traffic typi
cally passes through intermediate computers, such as routers, or is carried over unsecured networks, such as wireless hotspots.
...for example, a person can pretend to have the email address jdoe@example.net, or a computer can identify itself as a site
called www.example.net when it is not.
Developing cross-browser and cross-platform pages - Archive of obsolete content
hideelement(id_attribute_value) { if (document.getelementbyid && document.getelementbyid(id_attribute_value) && document.getelementbyid(id_attribute_value).style ) { document.getelementbyid(id_attribute_value).style.visibility = "hidden"; }; } // example: // <button type="button" onclick="hideelement('d1');">hide div</button> // <div id="d1">some text</div> these repeated
calls to document.getelementbyid are not the most efficient way to check for the existence of particular objects or features in the browser's dom implementation, but they serve to illustrate clearly how object support detection works.
... the top-level if clause looks to see if there is support for a method
called getelementbyid on the document object, which is the one of the most basic levels of support for the dom in a browser.
Introduction - Archive of obsolete content
what really happens with the {} notation is that the variables' tostring method is
called, and the returned value is placed in the element.
...serializing one of the most powerful tools of e4x is its ability to serialize an entire xml document (or portion thereof) into a string with one simple
call to .toxmlstring() var element1 = <foo/>; var element2 = <bar/>; element1.appendchild(element2); element1.toxmlstring(); this will print <foo> <bar/> </foo>
calling tostring() will achieve the same effect in this case, though
calling tostring() on an element with only text content will product the text content (e.g., <foo>abc</foo>.tostring(); will simply provide 'abc').
Generator comprehensions - Archive of obsolete content
generator comprehensions are syntacti
cally almost identical to array comprehensions — they use parentheses instead of braces— but instead of building an array they create a generator that can execute lazily.
...nerator comprehension on the other hand would create a new iterator which would create doubled values on demand as they were needed: var it2 = (for (i in it) i * 2); console.log(it2.next()); // the first value from it, doubled console.log(it2.next()); // the second value from it, doubled when a generator comprehension is used as the argument to a function, the parentheses used for the function
call means that the outer parentheses can be omitted: var result = dosomething(for (i in it) i * 2); the significant difference between the two examples being that by using the generator comprehension, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.
GetObject - Archive of obsolete content
you could use the following code to activate a layer within a drawing
called schema.cad: var layerobject = getobject("c:\\cad\\schema.cad!layer3"); if you do not specify the object's class, automation determines which application to start and which object to activate, based on the file name you provide.
...with a single-instance object, getobject always returns the same instance when
called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted.
New in JavaScript 1.3 - Archive of obsolete content
--> 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.
... statements label switch do...while export import built-in objects regexp methods of built-in objects tosource() object.prototype.watch() object.prototype.unwatch() function.arity function.prototype.apply() function.prototype.
call() array.prototype.concat() array.prototype.pop() array.prototype.push() array.prototype.shift() array.prototype.slice() array.prototype.splice() string.prototype.concat() string.prototype.concat() string.prototype.match() string.prototype.search() string.prototype.slice() string.prototype.substr() ...
New in JavaScript 1.8.5 - Archive of obsolete content
function.prototype.bind() creates a new function that, when
called, itself
calls this function in the context provided (with a given sequence of arguments).
... strict mode support array.tostring() now works even on non-arrays by either returning the result of
calling its join() method if one is available or by
calling its tostring() method.
New in JavaScript 1.8 - Archive of obsolete content
when using the javascript shell, javascript xpcom components, or xul <script> elements, the latest js version (js1.8 in mozilla 1.9) is used automati
cally (bug 381031, bug 385159).
...typi
cally you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement.
Building Mozilla XForms - Archive of obsolete content
getting started things to know first: the xforms extension has a dependency on the schema-validation extension, so you need to build both (that's done automati
cally) mozilla switched from cvs to mercurial starting with firefox 3.5.
...configure your build: the .mozconfig file mozilla uses a file
called .mozconfig in your home directory to store the build configuration.
Troubleshooting XForms Forms - Archive of obsolete content
introduction the idea of this page is to collect some solutions to some of the common errors typi
cally made when creating an xforms form.
...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 dynami
cally view model instance data while the xforms is running in the firefox browser.
Mozilla XForms Specials - Archive of obsolete content
(limitation tracked in bug 271724) optional parameters in xpath functions optional parameters in xpath functions are not supported, you will have to specify all parameters when
calling a function.
...we have added a function via the getfeature()
call on each node, that allows the form author to do that.
Using XForms and PHP - Archive of obsolete content
?> but remember this (quote from php documentation): remember that header() must be
called before any actual output is sent, either by normal html tags, blank lines in a file, or from php.
... it is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is
called.
Mozilla's DOCTYPE sniffing - Archive of obsolete content
any unknown doctype, which should include the following (techni
cally known) doctypes: the public identifier "-//w3c//dtd html 4.01//en".
...(this is techni
cally incorrect, since the strings are case sensitive.) see also web development mozilla's quirks mode mozilla quirks mode behavior original document information author(s): david baron last updated date: august 2, 2005 copyright information: copyright (c) david baron ...
Popup Window Controls - Archive of obsolete content
mozilla will attempt to suppress all
calls to window.open() which occur in the following circumstances: global script which is executed as the document is loading script executed as part of a onload event handler script executed in settimeout() or setinterval() what popup windows are not suppressed?
... detecting suppressed popups windows if a user has popup controls enabled for your site, any attempt to
call window.open in global script, in an onload handler or in settimeout() or setinterval() will return null rather than a reference to the opened window.
Using the DOM File API in chrome code - Extensions
] .getservice(components.interfaces.nsiproperties) .get("profd", components.interfaces.nsifile); dsfile.append("myfilename.txt"); var file = file.createfromnsifile(dsfile); this uses the directory service to locate the profile directory (with the location key "profd", see below for more details), then appends the name of the file we want to work with by
calling nsifile.append().
... finally, we instantiate the file object by
calling file.createfromnsifile.
Examples - Game development
hyper vanguard force a neat verti
cally scrolling space shooter.
... x-type verti
cally scrolling space shooter demo.
Game distribution - Game development
cocoonio — the most popular tool specifi
cally for building html5 games for multiple native stores.
... ejecta — a tool specifi
cally for packaging games created with the impactjs framework for ios, built by the impactjs author.
Building up a basic demo with Babylon.js - Game development
for the box size) are unitless, and can basi
cally be anything you deem suitable for your scene — milimeters, meters, feet, or miles — it's up to you.
... conclusion here's the final code listing, along with a viewable live example: you can also see it on github and fork the repository if you want to play with it yourself lo
cally.
GLSL Shaders - Game development
vertex shaders vertex shaders manipulate coordinates in a 3d space and are
called once per vertex.
... fragment shaders fragment (or texture) shaders define rgba (red, blue, green, alpha) colors for each pixel being processed — a single fragment shader is
called once per pixel.
Desktop mouse and keyboard controls - Game development
then the player's ship is drawn on the screen and the next draw is
called from within the requestanimationframe.
... to skip the how to play screen, we can listen for any key being pressed and move on: this.input.keyboard.ondown
callback = 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.
Implementing controls using the Gamepad API - Game development
controls for web games histori
cally playing games on a console connected to your tv was always a totally different experience to gaming on the pc, mostly because of the unique controls.
...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 physi
cally by the user or due to inactivity.) in the demo, the gamepadapi object is used to store everything related to the api: var gamepadapi = { controller: {}, turbo: false, connect: function() {}, disconnect: function() {}, update: function() {}, buttonpressed: function() {}, buttons: [], buttonscache: [], buttonsstatus: [], axesstatus: [] }; the buttons array contains the xbox 3...
asm.js - Game development
it does not allow objects, strings, closures, and basi
cally anything that requires heap allocation.
... asm.js has a very predictable perfomance rate because it is limited to an extremely restricted subset of javascript that provides only strictly-typed integers, floats, arithmetic, function
calls, and heap accesses.
Build the brick field - Game development
r*(brickheight+brickpadding))+brickoffsettop; bricks[c][r].x = brickx; bricks[c][r].y = bricky; ctx.beginpath(); ctx.rect(brickx, bricky, brickwidth, brickheight); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } } } actually drawing the bricks the last thing to do in this lesson is to add a
call to drawbricks() somewhere in the draw() function, preferably at the beginning, between the clearing of the canvas and drawing the ball.
... add the following just above the drawball()
call: drawbricks(); compare your code at this point, the game has got a little more interesting again : exercise: try changing the number of bricks in a row or a column, or their positions.
Collision detection - Game development
olumncount; c++) { for(var r=0; r<brickrowcount; 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; } } } } } activating our collision detection the last thing to do is to add a
call to the collisiondetection() function to our main draw() function.
... add the following line to the draw() function, just below the drawpaddle()
call: collisiondetection(); compare your code the collision detection of the ball is now checked on every frame, with every brick.
Finishing up - Game development
rendering the lives display now you need to add a
call to drawlives() inside the draw() function and add it below the drawscore()
call.
...replace the following line: var interval = setinterval(draw, 10); with simply: draw(); and remove each instance of: clearinterval(interval); // needed for chrome to end game then, at the very bottom of the draw() function (just before the closing curly brace), add in the following line, which causes the draw() function to
call itself over and over again: requestanimationframe(draw); the draw() function is now getting executed again and again within a requestanimationframe() loop, but instead of the fixed 10 milliseconds frame rate, we are giving control of the framerate back to the browser.
Paddle and keyboard controls - Game development
the only thing left to do now is
call the drawpaddle() function from within the draw() function, to actually print it on the screen.
... add the following line inside your draw() function, just below the line that
calls drawball(): drawpaddle(); compare your code here's the working code for you to compare yours against: exercise: make the paddle move faster or slower, or change its size.
Build the brick field - Game development
rendering the brick image next, let's load the image of the brick — add the following load.image()
call just below the others: function preload() { // ...
...add a
call to initbricks at the end of the create() function: function create(){ // ...
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
sometimes, this task is also referred to as "assembling" or "build", which typi
cally indiciates more than just compilation is done, e.g.
...some compilers which translate between similar level languages are
called transpilers or cross-compilers, for instance to compile from typescript to javascript.
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
for example, to set an <input> element's maxlength to 42 using the content attribute, you have to
call setattribute("maxlength", "42") on that element.
...if you pass another type, it is automati
cally converted to a number as specified by the standard javascript rules for type conversion.
Idempotent - MDN Web Docs Glossary: Definitions of Web-related terms
to be idempotent, only the actual back-end state of the server is considered, the status code returned by each request may differ: the first
call of a delete will likely return a 200, while successive ones will likely return a 404.
...
called several times in a row, the client gets the same results: get /pagex http/1.1 get /pagex http/1.1 get /pagex http/1.1 get /pagex http/1.1 post /add_row http/1.1 is not idempotent; if it is
called several times, it adds several rows: post /add_row http/1.1 post /add_row http/1.1 -> adds a 2nd row post /add_row http/1.1 -> adds a 3rd row delete /idx/delete http/1.1 is idempotent, even if the returned status code may change between requests: ...
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
at the time, javascript developers were grasping at straws trying to get their website to work across all devices because there was such a discrepancy between browsers that the website might have to be programmed radi
cally differently and have a much different user interface based upon the user's browser.
...using a polyfill to handle browser-specific implementations is practi
cally non-existent today because modern browsers mostly implement a broad set of apis according to standard semantics.
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
javascript // the primitive let foo = 5; // defining a function that should change the primitive value function addtwo(num) { num += 2; } // another function trying to do the same thing function addtwo_v2(foo) { foo += 2; } //
calling our first function while passing our primitive as an argument addtwo(foo); // getting the current primitive value console.log(foo); // 5 // trying again with our second function...
...if so, read how this code runs: for both the addtwo and addtwo_v2 functions
calls, javascript looks up the value for the identifier foo.
RTCP (RTP Control Protocol) - MDN Web Docs Glossary: Definitions of Web-related terms
this lets control and statistics packets be separated logi
cally and functionally from the media streaming while using the underlying packet delivery layer to transmit the rtcp signals as well as the rtp and media contents.
... rtcp periodi
cally transmits control packets to all of an rtp session's participants, using the same mechanism that is being used to transmit the data packets.
Recursion - MDN Web Docs Glossary: Definitions of Web-related terms
the act of a function
calling itself, recursion is used to solve problems that contain smaller sub-problems.
... examples recursive function
calls itself until condition met the following python code defines a function that takes a number, prints it, and then
calls itself again with the number's value -1.
Synthetic monitoring - MDN Web Docs Glossary: Definitions of Web-related terms
synthetic monitoring involves monitoring the performance of a page in a 'laboratory' environment, typi
cally with automation tooling in an environment that is as consistent as possible.
...the traffic measured is not of your actual users, but rather syntheti
cally generated traffic collecting data on page performance.
Texel - MDN Web Docs Glossary: Definitions of Web-related terms
the process of mapping the appropriate texel’s to their corresponding points on a polygon is
called texture mapping, which is a stage of the process of rendering a 3d image for display.
... texture mapping is typi
cally done prior to lighting the scene; however, in webgl, lighting is performed as part of the texture mapping process.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
css prefixes the major browsers use the following prefixes: -webkit- (chrome, safari, newer versions of opera, almost all ios browsers including firefox for ios; basi
cally, 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 histori
cally, 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); basi
cally, 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); basi
cally, any webkit based browser) moz (firefox) o (old, pre-webkit, versi...
VoIP - MDN Web Docs Glossary: Definitions of Web-related terms
voip allows you to make a
call directly from a computer, a special voip phone, or a traditional phone connected to a special adapter.
...usually, telephone
calls over the internet do not incur further charges beyond what the user is paying for internet access, much in the same way that the user doesn't pay for sending individual emails over the internet.
Mobile accessibility - Learn web development
using the rotor when voiceover is turned on, you have a navigation feature
called the rotor available to you, which allows you to quickly choose from a number of common useful options.
... responsive design responsive design is the practice of making your layouts and other features of your apps dynami
cally change depending on factors such as screen size and resolution, so they are usable and accessible to users of different device types.
Images, media, and form elements - Learn web development
typi
cally these do similar things to those described above, making sure that anything different across browsers is set to a consistent default before you do your own work on the css.
... they are not as important as they once were, as browsers are typi
cally more consistent than in the past.
Type, class, and ID selectors - Learn web development
in the live example below we have created a class
called .highlight, and have applied it to several places in my document.
... id selectors an id selector begins with a # rather than a full stop character, but is basi
cally used in the same way as a class selector.
Styling tables - Learn web development
of albums</th> <th scope="col">most famous song</th> </tr> </thead> <tbody> <tr> <th scope="row">buzzcocks</th> <td>1976</td> <td>9</td> <td>ever fallen in love (with someone you shouldn't've)</td> </tr> <tr> <th scope="row">the clash</th> <td>1976</td> <td>6</td> <td>london
calling</td> </tr> ...
... next, create a new file
called style.css and save it in the same directory as your other files.
Legacy layout methods - Learn web development
in this example case we've chosen <div>s, but you could choose something more semanti
cally appropriate like <article>s, <section>s, and <aside>, or whatever.
... note: normalize is a really useful little css library written by nicolas gallagher, which automati
cally does some useful basic layout fixes and makes default element styling more consistent across browsers.
Normal Flow - Learn web development
in english therefore, or any other horizontal, top to bottom writing mode, block-level elements are laid out verti
cally.
... if two adjacent elements both have the margin set on them and the two margins touch, the larger of the two remains, and the smaller one disappears — this is
called margin collapsing, and we have met this before too.
Getting started with CSS - Learn web development
you can continue to work in styles.css lo
cally, or you can use our interactive editor below to continue with this tutorial.
...to select only an <em> that is nested inside an <li> element i can use a selector
called the descendant combinator, which simply takes the form of a space between two other selectors.
How CSS works - Learn web development
based on the selectors it finds, it works out which rules should be applied to which nodes in the dom, and attaches style to them as required (this intermediate step is
called a render tree).
... the visual display of the page is shown on the screen (this stage is
called painting).
What do common web layouts contain? - Learn web development
basi
cally a two-column layout, but you'll notice many tweaks here and there that visually break up the layout.
...the way the curve of the header's menu ties in with the curve at the bottom of the image, the header and main content look like one thing even though they're techni
cally completely different.
How can we design for all types of users? - Learn web development
relative units also
called proportional units, relative units are computed relative to a parent element.
...yahoo's smushit!, dynamic drive's online image optimizer (which can convert automati
cally from one format to another if it's more bandwidth-efficient) ...
How do I start to design my website? - Learn web development
all of this is
called project ideation and is a necessary first step to reach your goal, whether you are a beginner or an experienced developer.
...what we will present here is a simple method to handle what professionals
call project ideation, project planning, and project management.
What are hyperlinks? - Learn web development
summary hyperlinks, usually
called links, are a foundational concept behind the web.
...that said, there are some nuances worth considering: types of links internal link a link between two webpages, where both webpages belong to the same website, is
called an internal link.
Advanced form styling - Learn web development
appearance: controlling os-level styling in the previous article we said that histori
cally, styling of web form controls was largely taken from the underlying operating system, which is part of the problem with customizing the look of these controls.
... taming search boxes <input type="search"> is basi
cally just a text input, so why is appearance: none; useful here?
HTML forms in legacy browsers - Learn web development
re is an example: modernizr.load({ // this tests if your browser supports the html5 form validation api test : modernizr.formvalidation, // if the browser does not support it, the following polyfill is loaded nope : form-validation-api-polyfill.js, // in any case, your core app file that depends on that api is loaded both : app.js, // once both files are loaded, this function is
called in order to initialize the app.
...performance is a subject on its own, but legacy browsers are very sensitive to it: basi
cally, they are slow and the more polyfills they need, the more javascript they have to process.
Your first form - Learn web development
a web form's html is made up of one or more form controls (sometimes
called widgets), plus some additional elements to help structure the overall form — they are often referred to as html forms.
...it's a container element like a <section> or <footer> element, but specifi
cally for containing forms; it also supports some specific attributes to configure the way the form behaves.
CSS basics - Learn web development
anatomy of a css ruleset let's dissect the css code for red paragraph text to understand how it works : the whole structure is
called a ruleset.
...here are some of the more common types of selectors: selector name what does it select example element selector (sometimes
called a tag or type selector) all html elements of the specified type.
Publishing your website - Learn web development
ftp programs vary widely, but generally, you have to connect to your web server using details provided by your hosting company (typi
cally username, password, hostname).
...github has a very useful feature
called github pages, which allows you to expose website code live on the web.
Adding vector graphics to the Web - Learn web development
it's basi
cally markup, like html, except that you've got many different elements for defining the shapes you want to appear in your image, and the effects you want to apply to those shapes.
... how to include svg code inside your html you can also open up the svg file in a text editor, copy the svg code, and paste it into your html document — this is sometimes
called putting your svg inline, or inlining svg.
From object to iframe — other embedding technologies - Learn web development
these were embedded in a master document
called a frameset, which allowed you to specify the area on the screen that each frame filled, rather like sizing the columns and rows of a table.
...a container for code where it can be used appropriately — or for testing — but can't cause any harm to the rest of the codebase (either accidental or malicious) is
called a sandbox.
What went wrong? Troubleshooting JavaScript - Learn web development
if we look at line 86 in our code editor, we'll find this line: guesssubmit.addeventlistener('click', checkguess); the error message says "guesssubmit.addeventlistener is not a function", which means that the function we're
calling is not recognized by the javascript interpreter.
... syntaxerror: missing ) after argument list this one is pretty simple — it generally means that you've missed the closing parenthesis at the end of a function/method
call.
Test your skills: Object basics - Learn web development
when you are done, write your own object
called cat2, which has the same structure, exactly the same greeting() method, but a different name, breed, and color.
...
call both greeting() methods to check that they log appropriate greetings to the console.
Measuring performance - Learn web development
a performance entry can be directly created by making a performance mark or measure (for example by
calling the mark() method) at an explicit point in an application.
... webpagetest.org is another example of a tool that automati
cally tests your site and returns useful metrics.
Web performance - Learn web development
the rest of our beginner's learning material tried to stick to web best practices such as performance and accessibility as much as possible, however, it is good to focus specifi
cally on such topics too, and make sure you are familiar with them.
...by minimizing the number of dom nodes, making sure the best order and attributes are used for including content such as styles, scripts, media, and third-party scripts, you can drasti
cally improve the user experience.
Server-side website programming - Learn web development
most major websites use some kind of server-side technology to dynami
cally display data as required.
...displaying all of these using different static pages would be extremely inefficient, so instead such sites display static templates (built using html, css, and javascript), and then dynami
cally update the data displayed inside those templates when needed, such as when you want to view a different product on amazon.
Ember resources and troubleshooting - Learn web development
while it is techni
cally possible to use jsx, or any other form of dom creation, there has yet to be anything as robust as ember's templating system.
...ut 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.
Ember app structure and componentization - Learn web development
when you save application.hbs, the development server you started earlier will automati
cally rebuild the app and refresh the browser.
...ter class="footer"> <span class="todo-count"> <strong>0</strong> todos left </span> <ul class="filters"> <li> <a href="#">all</a> <a href="#">active</a> <a href="#">completed</a> </li> </ul> <button type="button" class="clear-completed"> clear completed </button> </footer> finally, the contents of application.hbs should be updated so that they
call the appropriate components, like so: <section class="todoapp"> <h1>todos</h1> <header /> <todolist /> <footer /> </section> with these changes made, run npm start in your terminal again, then head over to http://localhost:4200 to ensure that the todo app still looks as it did before the refactor.
Starting our Svelte Todo list app - Learn web development
being a compiler, svelte can stati
cally analyze our html templates to provide accessibility warnings when components are being compiled.
... moreover, our editor can display this warning even before
calling the compiler: you can tell svelte to ignore this warning for the next block of markup with a comment beginning with svelte-ignore, like this: <!-- svelte-ignore a11y-missing-attribute --> <img height="32" width="88" src="https://udn.realityripple.com/samples/b0/98dase3c7d.png"> note: with vscode you can automati
cally add this ignore comment by clicking on the quick fix...
Handling common accessibility problems - Learn web development
screenreaders tend to act in slightly different ways and have different controls, so you'll have to consult the documentation for your chosen screen reader to get all of the details — saying that, they all work in basi
cally the same sort of way.
... accessibility testing checklist the following list provides a checklist for you to follow to make sure you've carried out the recommended accessibility testing for your project: make sure your html is as semanti
cally correct as possible.
Introduction to cross browser testing - Learn web development
you can make some informed
calls as to what browsers and devices your users will be using (as we'll discuss in the second article in the series — see gotta test 'em all?), but you can't guarantee everything.
...it is also possible to set up an environment that automati
cally runs tests for you, and then only lets you check in your changes to the central code repository if the tests still pass.
Chrome Worker Modules
if you do, know that any
call to module.exports will overwrite all
calls to `exports.foo = bar.
...the module loader supports cyclic
calls to require().
omni.ja (formerly omni.jar)
firefox and thunderbird achieve performance improvements by moving many of their internal parts from being standalone files or sets of jar files into just one jar file
called omni.ja; this reduces the amount of i/o needed to load the application.
... note: prior to firefox 10 and thunderbird 10, omni.ja was
called omni.jar.
Accessibility information for UI designers and developers
only one element has focus at a given time, typi
cally revealed by browsers with a dotted outline.
...this is specifi
cally important in these cases: the user input is about legal commitments or financial transactions it updates or removes the user's data in a system when recording tests responses in those cases, ensure users can change submissions, automati
cally check for errors.
Testopia
all params should now be sent in a hash (struct, dict, hashmap or whatever your language of choice
calls key, value pairs).
... though all attempts have been made to provide continuing support for positional parameters, please be aware that some api
calls may fail until you make this change.
Continuous Integration
the talos harness produces a single number per test (typi
cally the median of all the replicates excluding the first 1-5), which are stored in treeherder's database, and are accessible via the perfherder interface.
... perfherder alerts we track changes to talos and other performance frameworks inside perfherder, and try to automati
cally alert when there is a sustained change exceeding a certain magnitude (specified per test).
Creating reftest-based unit tests
the build process runs reftests in a profile that does not automati
cally grant elevated privileges: requesting them will cause the standard security alert to display, which will likely cause the machine running the test to hang or timeout.
... the reason for using the 'mozreftestinvalidate' event is because a document's initial painting is not typi
cally finished when the 'load' event fires.
Debugging JavaScript
this shows any javascript errors in your app, as well as any logging
calls from the console api.
...in extensions you can print the
callstack using components.stack like this: function getstackdump() { var lines = []; for (var frame = components.stack; frame; frame = frame.
caller) { lines.push(frame.filename + " (" + frame.linenumber + ")"); } return lines.join("\n"); } see also debugging mozilla with gdb setting up an extension development environment (particularly development preferences and development extens...
Debugging a hang on OS X (Archived)
below are steps you can use to attach so-
called "samples" to bug reports.
... by default, sampling of any hanging application will begin automati
cally.
Debugging on Mac OS X
the .app file is typi
cally found inside the dist folder in your build directory.
...instead, add the following to your $home/.lldbinit: # this automati
cally sources the mozilla project's .lldbinit as soon as lldb # starts or attaches to a mozilla app (that's in an object directory).
Debugging
debugging specific parts of the mozilla codebase debugging opengl if you're working on code that involves opengl
calls, and need to debug it, you can turn on a special opengl debugging mode.
... download a debug build recent automati
cally compiled debug builds are available.
Simple SeaMonkey build
(for some mac os x versions, you will find it in a directory
called "optional installs".) install macports.
...if the below is left out, a best guess will be taken automati
cally.
The Firefox codebase: CSS Guidelines
only use generic selectors such as :last-child, when it is what you mean semanti
cally.
...this is especially useful in conjunction with icons using -moz-context-properties: fill; where the icon can adjust to the right platform color automati
cally from the text color.
Interface Compatibility
using these interfaces, and using dynamic
calls to queryinterface, it has been possible to write binary xpcom components which were compatible with multiple versions of firefox.
... js-ctypes is the recommended way for extensions to
call into os or third-party native code.
Multiple Firefox profiles
once done, each one should automati
cally start with the specified profile.
... linux in linux, things aren't as automati
cally set up.
Limitations of frame scripts
therefore frame scripts should not attempt to access the local file system directly, as these
calls will fail.
...in the content process the root tree item is an nsitabchild, that cannot be converted to an nsidomwindow, so the second getinterface
call here will fail.
HTMLIFrameElement.setVisible()
as an example, if the content of a browser <iframe> uses the window.requestanimationframe method and if the visible state is set to true, window.requestanimationframe will be
called as often as necessary.
... however, if the visible state is set to false, window.requestanimationframe will be
called only when there are free resources to do it.
ChromeWorker
summary if you're developing privileged code, and would like to create a worker that can use js-ctypes to perform
calls to native code, you can do so by using chromeworker instead of the standard worker object.
...to use a postmessage with
callback version of chromeworker that features promises, see promiseworker.
Chrome-only API reference
it currently works in (privileged) chrome code on firefox desktop (version 47 and above).chromeworkerif you're developing privileged code, and would like to create a worker that can use js-ctypes to perform
calls to native code, you can do so by using chromeworker instead of the standard worker object.
...to use a postmessage with
callback version of chromeworker that features promises, see promiseworker.
Geckoview-Junit Tests
these tests run on an android device, controlled by a host (typi
cally linux) using mozdevice (adb).
... running tests lo
cally if desired, connect an android device to your computer, or start an emulator, and make sure your device is visible to adb: $ adb devices list of devices attached emulator-5554 device if no device is found, 'mach geckoview-junit' will offer to start an emulator.
How to get a stacktrace with WinDbg
introduction sometimes you need to get a stacktrace (
call stack) for a crash or hang but breakpad fails because it's a special crasher or a hang.
... q: the first four frames of my stack trace look like this: 0012fe20 7c90e89a ntdll!kifastsystem
callret 0012fe24 7c81cd96 ntdll!zwterminateprocess+0xc 0012ff20 7c81cdee kernel32!_exitprocess+0x62 0012ff34 6000179e kernel32!exitprocess+0x14 this looks wrong to me?!
How to implement a custom autocomplete search component
because creating an xpcom component in order to build a custom autocomplete source can be enough to discourage some developers, below is an example javascript xpcom component
called "simple-autocomplete" that implements the necessary interfaces.
...de"},{"value":"mary","comment":"nice lady"},{"value":"jimmy","comment":"very uncool guy"},{"value":"jimbo","comment":null}]' /> how to solve autocomplete panel focus problems in some situations there may be problems with the display of the autocomplete panel (this is the panel where the autocomplete results/suggestions are displayed): the autocomplete panel seems to appear seldom and very errati
cally.
Internationalized Domain Names (IDN) Support in Mozilla Browsers
this process is
called "nameprep" and is performed according to rfc 3491 (nameprep: a stringprep profile for internationalized domain names (idn)) and rfc 3454 (preparation of internationalized strings ("stringprep")).
...during the discussion phase of the idn protocols development, there were some competing ascii-compatible encoding (ace) schemes proposed but an agreement was reached eventually to standardize on a type of ace
called "punycode".
Introduction to Layout in Mozilla
overview basic data flow key data structures detailed walk-through incrementalism future tech-talks wrap-up, q&a basic data flow source document arrives via network apis incrementally “pumped” through the single-threaded layout engine parse, compute style, render; repeat css used for rendering all content content theoreti
cally separate from “presentation” key data structures content node elements, attributes, leaves dom frame rectangular formatting primitive geometric information [0..n] per content node 2nd thru nth are “continuations” style context non-geometric information may be shared by adjacent frames reference counted, owned by frame ...
... view clipping, z-order, transparency [0..1] per frame, owned by frame widget native window [0..1] per view, owned by view key data structures the document owns the content model, and one or more presentations exposed programmati
cally via dom apis the presentation owns the frame hierarchy frames own the style contexts, views, widgets presentation has media type, dimensions, etc.
TypeListener
method overview void ontypeadded(in addontype type) void ontyperemoved(in addontype type) methods ontypeadded()
called when an add-on type has been added.
... void ontypeadded( in addontype type ) parameters type the addontype that is being added needsrestart true if an application restart is necessary for the change to take effect ontyperemoved()
called when an add-on type has been removed.
UpdateCheckListener
method overview void onupdatecheckcomplete(in updateinfo results[]) void onupdatecheckerror(in integer status) methods onupdatecheckcomplete()
called when the update check completed successfully.
... void onupdatecheckcomplete( in updateinfo results[] ) parameters results an array of updateinfo objects representing the available add-on versions onupdatecheckerror()
called when the update check fails.
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.
... return value a new dictionary object containing the same top-level items as the original dictionary on which the copy() method was
called.
JavaScript OS.Constants
o_exlock atomi
cally obtain an exclusive lock.
... o_rsync o_shlock atomi
cally obtain a shared lock.
SourceMap.jsm
the walking function is
called once for each snippet of js and is passed that snippet and its original associated source's line/column location.
... sourcenode.prototype.replaceright(pattern, replacement)
call string.prototype.replace on the very rightmost source snippet.
JavaScript code modules
ctypes.jsm provides an interface that allows javascript code to
call native libraries without requiring the development of an xpcom component.
... jni.jsm abstracts the js-ctypes to provide an interface that allows javascript code to
call code running in native jvms.
Index
mercurial allows localizers to work lo
cally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org).
...more specifi
cally, it's a problem with an already released localization.
Localization and Plurals
chrome://mozapps/locale/downloads/do...tes,hours,days chrome://mozapps/locale/downloads/do...dstitlepercent chrome://browser/locale/browser.prop...auseddownloads version history 0.1: initial version with pluralrule check, properties input loading, table generation, sample output display 0.2: use pluralform.numforms() to get the number of forms instead of figuring out lo
cally to better support future rules - requires build from 2007/01/27 or later 0.3: generate a list of what numbers fall into which plural form to minimize the sample output to at most 3 of each form developing with pluralform the functionality for getting the correct plural forms is provided by a javascript module, pluralform.jsm.
...so for your extension, specify a pluralrule value in the .properties, and
call pluralform.makegetter(pluralrulefromproperties), making sure to save the 2 returned functions.
Localizing with Mercurial
mercurial allows localizers to work lo
cally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org).
...your config file is
called either ~/.hgrc (unix systems) or mercurial.ini (windows), depending on your operating system.
Release phase
keep in mind that the hg commit command will save your changes lo
cally (in the local clone).
... the hg outgoing command compares the two repositories and lists all changesets that are present lo
cally, but not in the remote repository.
Localization technical reviews
your review request symboli
cally represents that you have worked on your localization, tested it successfully, and found it to represent the best of your work.
...when you update your localization for the next release, you'll need to put it through a different form of qa review
called a sign-off review.
What every Mozilla translator should know
n you have a problem use the above mailing lists the person in charge of the mozilla l10n is axel hecht (l10n at mozilla.com), pike on irc another interesting way of getting help is the irc channel #l10n at irc.mozilla.org useful tools the l10n dashboard pontoon narro translate toolkit koala 0.1 mozillatranslator mercurial the hg is organized into several repositories, sometimes
called branches.
... we have the main repository
called mozilla-central (or trunk) where the day to day developing work is done.
MathML Demo: <msqrt>, <mroot> - radicals
about all you can do with them is see how the rendering stretches them in various ways: horizontally sin x cos y , verti
cally 1 2 3 4 and det ( 1 2 3 4 ) 2 , as well as 2 x y z w , 2 1 2 3 4 , and 2 ⌈ det ( 1 2 3 4 ) ⌉ .
...about all you can do with them is see how the rendering stretches them in various ways: horizontally sin x cos y verti
cally 1 2 3 4 and det ( 1 2 3 4 ) 2 as well as 2 x y z w 2 1 2 3 4 and 2 ⌈ det ( 1 2 3 4 ) ⌉ the formula of binet shows how the n-th term in the fibonacci series can be expressed using roots f n = 1 5 [ ( 1 + 5 2 ) n - ( 1 - 5 2 ) n ] ...
Mozilla Web Services Security Model
they do this by creating a file
called web-scripts-access.xml in the root of the server that grants permission for other domains to access web services.
... soap soap requests without verification headers soapv soap requests with verification headers the from attribute the from attribute on the allow element says which
calling sites the allow element applies to.
Mozilla Style System Documentation
the pres context forwards these
calls to its style set object (stylesetimpl, interface nsistyleset), which does the real work (and also maintains the lists of stylesheets and owns the rule tree).
...the functions that form the style context automati
cally adds the context to the tree correctly.
GPU performance
tools pix - can do timing of direct3d
calls.
...guides accurately profiling direct3d api
calls (direct3d 9)- suggests avoiding normal profilers like xperf and instead measuring the time to flush the command buffer.
Intel Power Gadget
this feature has been used in energia, roberto vitillo's tool for systemati
cally measuring differential power usage between different browsers.
... (an energia dashboard can be seen here; please note that the data has not been updated since early 2014.) version 3.0 (available on mac and windows, but not on linux) also exposes an api from which the same measurements can be extracted programmati
cally.
Leak-hunting strategies and tips
[obscure] double-assignment into the same variable: if you release a member variable and then assign into it by
calling another function that does the same thing, you can leak the object assigned into the variable by the inner function.
... tips disabling arena allocation with many lower-level leak tools (particularly trace-malloc based ones, like leaksoup) it can be helpful to disable arena allocation of objects that you're interested in, when possible, so that each object is allocated with a separate
call to malloc.
Memory Profiler
this article details how to use an old profiler specifi
cally designed for firefox os devices.
... the tree view shows functions as
call trees.
Profiling with Instruments
memory profiling instruments will record a
call stack at each allocation point.
... the
call tree view can be quite helpful here.
Profiling with Xperf
once the sdk installs, execute either wpt_x86.msi or wpt_x64.msi in the redist/windows performance toolkit folder of the sdk's install location (typi
cally program files/microsoft sdks/windows/v7.1/redist/windows performance toolkit) to actually install the windows performance toolkit tools.
...the stock windows crt allocator is horrible about fragmentation, and causes memory usage to rise drasti
cally even if only a small fraction of that memory is in use.
powermetrics
the sum of the process values typi
cally exceeds the coalition value slightly, for unknown reasons.
...high frequency timers, which typi
cally have short time-to-deadlines, can cause high power consumption and should be avoided if possible.
Phishing: a short definition
shifting blame to users some quick-to-implement, and cost-effective solutions, hold users accountable for their actions instead of restricting what’s techni
cally possible.
... services assuming responsibility technical solutions can be more efficient if implemented to protect millions of users automati
cally.
Profile Manager
firefox and other xulrunner applications store user settings and data in special folders,
called profiles.
... for this reason, if you attempt to launch firefox using profile manager, and it detects that another instance of firefox is already running, it will automati
cally add the -no-remote argument for you, regardless of whether this launch option was checked.
Debugging out-of-memory problems
out-of-memory exceptions from js setting memory.dump_reports_on_oom in about:config to true will cause the browser to automati
cally write about:memory dumps to a temp file printed to the browser console (note: not web console) when an oom crash is encountered.
..."/sdcard/download/") when
calling adb pull.
L20n HTML Bindings
monolingual mode l20n can also operate in the so-
called monolingual mode, when there is only one locale available.
... it doesn't have any specific locale code (internally, it's
called i-default in compliance to rfc 2277).
Condition Variables
condition variable type condition variable functions conditions are closely associated with a single monitor, which typi
cally consists of a mutex, one or more condition variables, and the monitored data.
... a
call to pr_waitcondvar causes a thread to block until a specified condition variable receives notification of a change of state in its associated monitored data.
I/O Types
to refer specifi
cally to the files in a file system (that is, disk files), this documentation uses the termnormal files.
...different kinds of i/o objects (such as files and sockets) have different i/o methods tables, thus implementing different behavior in response to the same i/o function
call.
Monitors
a
call to pr_wait temporarily returns the entry count to zero.
... when the
calling thread resumes, it has the same entry count it had before the wait operation.
PLHashAllocOps
syntax #include <plhash.h> typedef struct plhashallocops { void *(pr_
callback *alloctable)(void *pool, prsize size); void (pr_
callback *freetable)(void *pool, void *item); plhashentry *(pr_
callback *allocentry)(void *pool, const void *key); void (pr_
callback *freeentry)(void *pool, plhashentry *he, pruintn flag); } plhashallocops; #define ht_free_value 0 /* just free the entry's value */ #define ht_free_entry 1 /* free value and entire entry */ description users of the hash table functions can provide their own memory allocation functions.
...typi
cally pool points to a memory pool used by the memory allocator.
PLHashComparator
syntax #include <plhash.h> typedef printn (pr_
callback *plhashcomparator)( const void *v1, const void *v2); description plhashcomparator is a function type that compares two values of an unspecified type.
...pl_comparevalues compares the values of the arguments v1 and v2 numeri
cally.
PL_CompareValues
compares two void * values numeri
cally.
... syntax #include <plhash.h> printn pl_comparevalues(const void *v1, const void *v2); description pl_comparevalues compares the two void * values v1 and v2 numeri
cally, i.e., it returns the value of the expression v1 == v2.
PRThreadPriority
only one thread at a time typi
cally has this priority.
... pr_priority_last placeholder description in general, an nspr thread of higher priority has a statisti
cally better chance of running relative to threads of lower priority.
PRThreadState
pr_joinable_thread joinable thread references remain valid after they have returned from their root function until pr_jointhread is
called.
... if a thread is created as an unjoinable (also
called detached) thread, it terminates and cleans up after itself after returning from its root function.
PRTimeParamFn
this type defines a
callback function to calculate and return the time parameter offsets from a calendar time object in gmt.
... syntax #include <prtime.h> typedef prtimeparameters (pr_
callback_decl *prtimeparamfn) (const prexplodedtime *gmt); description the type prtimeparamfn represents a
callback function that, when given a time instant in gmt, returns the time zone information (offset from gmt and dst offset) at that time instant.
PR_AcceptRead
syntax #include <prio.h> print32 pr_acceptread( prfiledesc *listensock, prfiledesc **acceptedsock, prnetaddr **peeraddr, void *buf, print32 amount, printervaltime timeout); parameters the function has the following parameters: listensock a pointer to a prfiledesc object representing a socket descriptor that has been
called with the pr_listen function, also known as the rendezvous socket.
...the reason for the failure can be obtained by
calling pr_geterror.
PR_Bind
further information can be obtained by
calling pr_geterror.
...
call pr_getsockname to obtain the address (name) bound to a socket.
PR_CEnterMonitor
if a match is found, then either the
calling thread is already in the monitor (and this is a reentrant
call) or another thread is holding the monitor's mutex.
...in the latter case, the
calling thread is likely to find the monitor locked by another thread and waits for that thread to exit before continuing.
PR_ClearInterrupt
clears the interrupt request for the
calling thread.
...therefore it is sometimes necessary to
call pr_clearinterrupt to clear a previous interrupt request.
PR_CloseDir
description when a prdir object is no longer needed, it must be closed and freed with a
call to pr_closedir
call.
... note that after a pr_closedir
call, any prdirentry object returned by a previous pr_readdir
call on the same prdir object becomes invalid.
PR_CreateIOLayerStub
description a new layer may be allocated by
calling pr_createiolayerstub.
... the
caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack.
PR_DestroyMonitor
description the
caller is responsible for guaranteeing that the monitor is no longer in use before
calling pr_destroymonitor.
... there must be no thread (including the
calling thread) in the monitor or waiting on the monitor.
PR EnumerateAddrInfo
on output, this structure is filled in by the runtime if the result of the
call is not null.
... returns the function returns the value you should specify in the enumptr parameter for the next
call of the enumerator.
PR_ExitMonitor
the monitor object referenced must be one for which the
calling thread currently holds the lock.
... if unsuccessful (the
calling thread has not entered the monitor), pr_failure.
PR_ExplodeTime
params a time parameter
callback function.
...this location must be preallocated by the
caller.
PR GetAddrInfoByName
when no longer needed, this pointer must be destroyed with a
call to pr_freeaddrinfo.
...you can retrieve the reason for the failure by
calling pr_geterror.
PR GetCanonNameFromAddrInfo
syntax #include <prnetdb.h> const char *pr_getcanonnamefromaddrinfo(const praddrinfo *addrinfo); parameters the function has the following parameters: addrinfo a pointer to a praddrinfo structure returned by a successful
call to pr_getaddrinfobyname.
...this pointer is invalidated once the praddrinfo structure is destroyed by a
call to pr_freeaddrinfo.
PR_GetConnectStatus
description after pr_connect on a nonblocking socket fails with pr_in_progress_error, you may wait for the connection to complete by
calling pr_poll on the socket with the in_flags pr_poll_write | pr_poll_except.
... when pr_poll returns,
call pr_getconnectstatus on the socket to determine whether the nonblocking connect has succeeded or failed.
PR_GetCurrentThread
syntax #include <prthread.h> prthread* pr_getcurrentthread(void); returns always returns a valid reference to the
calling thread--a self-identity.
... description the currently running thread may discover its own identity by
calling pr_getcurrentthread.
PR_GetProtoByName
this buffer is allocated by the
caller.
...you can retrieve the reason for the failure by
calling pr_geterror.
PR_GetProtoByNumber
this buffer is allocated by the
caller.
...you can retrieve the reason for the failure by
calling pr_geterror.
PR_GetUniqueIdentity
call pr_getuniqueidentity only once for any particular layer name.
... if you're creating a custom i/o layer, cache the result, and then use that cached result every time you
call pr_createiolayerstub.
PR_INIT_STATIC_CLIST
stati
cally initializes a circular list.
... description pr_init_static_clist stati
cally initializes the specified list to be an empty list.
PR_Init
description nspr is now implicitly initialized, usually by the first nspr function
called by a program.
...
call pr_init as follows: pr_init(pr_user_thread, pr_priority_normal, 0); ...
PR_Initialized
syntax #include <prinit.h> prbool pr_initialized(void); returns the function returns one of the following values: if pr_init has already been
called, pr_true.
... if pr_init has not already been
called, pr_false.
PR_Listen
further information can be obtained by
calling pr_geterror.
...pending connections may be accepted by
calling pr_accept.
PR_LocalTimeParameters
description this is a frequently-used time parameter
callback function.
... you don't normally
call it directly; instead, you pass it as a parameter to pr_explodetime() or pr_normalizetime().
PR_Lock
description when pr_lock returns, the
calling thread is "in the monitor," also
called "holding the monitor's lock." any thread that attempts to acquire the same lock blocks until the holder of the lock exits the monitor.
...
calling it twice on the same thread results in undefined behavior.
PR_NotifyCondVar
if unsuccessful (for example, if the
caller has not locked the lock associated with the condition variable), pr_failure.
... description the
calling thread must hold the lock that protects the condition, as well as the invariants that are tightly bound to the condition.
PR_Now
you cannot assume that the values returned by pr_now() are monotoni
cally increasing because the system clock of the computer may be reset.
... to obtain monotoni
cally increasing time stamps suitable for measuring elapsed time, use pr_intervalnow().
PR_ReadDir
the
caller must not free the prdirentry structure.
... moreover, the prdirentry structure returned by each pr_readdir
call is valid only until the next pr_readdir or pr_closedir
call on the same prdir object.
PR_SendTo
the reason for the failure can be obtained by
calling pr_geterror.
...the
calling thread blocks until all bytes are sent, a timeout has occurred, or there is an error.
PR_SetErrorText
description the text is copied into the thread structure and remains there until the next
call to pr_seterror.
...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_SetSocketOption
the reason for the failure can be obtained by
calling pr_geterror.
... description on input, the
caller must set both the option and value fields of the prsocketoptiondata object pointed to by the data parameter.
PR_SetThreadPriority
description modifying the priority of a thread other than the
calling thread is risky.
...it is preferable for a thread to specify itself in the thread parameter when it
calls pr_setthreadpriority.
PR_VersionCheck
compares the version of nspr assumed by the
caller (the imported version) with the version being offered by the runtime (the exported version).
... returns the function returns one of the following values: if the version of the shared library is compatible with that expected by the
caller, pr_true.
PR_WaitForPollableEvent
blocks the
calling thread until the pollable event is set, and then atomi
cally unsetting the event before returning.
... 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.
PR_WaitSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_waitsemaphore(prsem *sem); parameter the function has the following parameter: sem a pointer to a prsem structure returned from a
call to pr_opensemaphore.
... the "test and decrement" operation is performed atomi
cally.
PR_Writev
the reason for the failure can be obtained by
calling pr_geterror.
... description the thread
calling pr_writev blocks until all the data is written or the write operation fails.
Process Initialization
pr_
callonce ensures that such initialization code is
called only once.
... pr
calloncetype pr
calloncefn pr_
callonce ...
NSPR API Reference
introduction to nspr nspr naming conventions nspr threads thread scheduling setting thread priorities preempting threads interrupting threads nspr thread synchronization locks and monitors condition variables nspr sample code nspr types
calling convention types algebraic types 8-, 16-, and 32-bit integer types signed integers unsigned integers 64-bit integer types floating-point integer type native os integer types miscellaneous types size type pointer difference types boolean types status type for return values threads threading types and constants threading functions creating, joining, and identifying threads controlling thread priorities contr...
...emory-mapped i/o functions anonymous pipe function polling functions pollable events manipulating layers network addresses network address types and constants network address functions atomic operations pr_atomicincrement pr_atomicdecrement pr_atomicset interval timing interval time type and constants interval functions date and time types and constants time parameter
callback functions functions memory management operations memory allocation functions memory allocation macros string operations pl_strlen pl_strcpy pl_strdup pl_strfree floating point number to string conversion pr_strtod pr_dtoa pr_cnvtf long long (64-bit) integers bitmaps formatted printing linked lists linked list types prclist linked list macros pr...
NSS 3.15.4 release notes
new functions cert_forcepostmethodforocsp cert_getsubjectnamedigest cert_getsubjectpublickeydigest ssl_peercertificatechain ssl_recommendedcanfalsestart ssl_setcanfalsestart
callback new types cert_rev_m_force_post_method_for_ocsp: when this flag is used, libpkix will never attempt to use the http get method for ocsp requests; it will always use post.
...in addition to enabling the ssl_enable_false_start option, an application must now register a
callback using the ssl_setcanfalsestart
callback function.
NSS 3.15.5 release notes
nss automati
cally adds the padding extension to clienthello when necessary.
... notable changes in nss 3.15.5 bug 950129: improve the ocsp fetching policy when verifying ocsp responses bug 949060: validate the iov input argument (an array of priovec structures) of ssl_writev (
called via pr_writev).
NSS 3.30 release notes
support for
callback functions that can be used to monitor ssl/tls alerts that are sent or received.
... in ssl.h ssl_alertreceived
callback - register a
callback function, that will be
called whenever an ssl/tls alert is received ssl_alertsent
callback - register a
callback function, that will be
called whenever an ssl/tls alert is sent ssl_setsessionticketkeypair - configures an asymmetric key pair, for use in wrapping session ticket keys, used by the server.
NSS 3.52 release notes
bug 1629661 - mpconfig
calls in ssl initialize policy before nss is initialized.
... bug 1630925 - guard all instances of nsscmssigneddata.signerinfo to avoid a cms crash bug 1571677 - name constraints validation: cn treated as dns name even when syntacti
cally invalid as dns name this bugzilla query returns all the bugs fixed in nss 3.52: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.52 compatibility nss 3.52 shared libraries are backward compatible with all older nss 3.x shared libraries.
nss tech note7
pk11symkey: a symmetric key (often
called a session key), defined in "secmodt.h".
...
call seckey_importderpublickey() with type=ckk_rsa to import a der-encoded rsa public key.
FC_CloseAllSessions
the nss cryptographic module currently doesn't
call the surrender
callback function notify.
... (see pkcs #11 v2.20 section 11.17.1.) a user may
call fc_closeallsessions without logging into the token (to assume the nss user role).
FC_Decrypt
description fc_decrypt decrypts a block of data according to the attributes of the previous
call to fc_decryptinit.
... a user must log into the token (to assume the nss user role) before
calling fc_decrypt.
FC_DecryptUpdate
description fc_decryptupdate decrypts a block of data according to the attributes of the previous
call to fc_decryptinit.
...a user must log into the token (to assume the nss user role) before
calling fc_decryptupdate.
FC_Digest
description fc_digest digests a message in a single operation according to the attributes of the previous
call to fc_digestinit.
... a user may
call fc_digest without logging into the token (to assume the nss user role).
FC_DigestFinal
if pdigest is null the length of the digest is returned and fc_digestfinal may be
called again with pdigest set to retrieve the digest.
... a user may
call fc_digestfinal without logging into the token (to assume the nss user role).
FC_DigestKey
the digest for the entire message is returned by a
call to fc_digestfinal.
... a user must log into the token (to assume the nss user role) before
calling fc_digestkey.
FC_DigestUpdate
the digest for the entire message is returned by a
call to fc_digestfinal.
... a user may
call fc_digestupdate without logging into the token (to assume the nss user role).
FC_Encrypt
description fc_encrypt encrypts a block of data according to the attributes of the previous
call to fc_encryptinit.
... a user must log into the token (to assume the nss user role) before
calling fc_encrypt.
FC_EncryptUpdate
description fc_encryptupdate encrypts a block of data according to the attributes of the previous
call to fc_encryptinit.
...a user must log into the token (to assume the nss user role) before
calling fc_encryptupdate.
FC_Sign
description fc_sign signs a message in a single operation according to the attributes of the previous
call to fc_signinit.
... a user must log into the token (to assume the nss user role) before
calling fc_sign.
FC_SignFinal
if psignature is null the length of the signature is returned and fc_signfinal may be
called again with psignature set to retrieve the signature.
... a user must log into the token (to assume the nss user role) before
calling fc_signfinal.
FC_SignUpdate
the signature for the entire message is returned by a
call to fc_signfinal.
... a user must log into the token (to assume the nss user role) before
calling fc_signupdate.
FC_UnwrapKey
if pwrappedkey is null the length of the wrapped key is returned in puswrappedkeylen and fc_unwrapkey may be
called again with pwrappedkey set to retrieve the wrapped key.
... a user must log into the token (to assume the nss user role) before
calling fc_unwrapkey.
FC_VerifyUpdate
the result for the entire message is returned by a
call to fc_verifyfinal.
... a user must log into the token (to assume the nss user role) before
calling fc_verifyupdate.
FC_WrapKey
if pwrappedkey is null the length of the wrapped key is returned in puswrappedkeylen and fc_wrapkey may be
called again with pwrappedkey set to retrieve the wrapped key.
... a user must log into the token (to assume the nss user role) before
calling fc_wrapkey.
NSS functions
cehandshakewithtimeout mxr 3.11.4 and later ssl_getchannelinfo mxr 3.4 and later ssl_getciphersuiteinfo mxr 3.4 and later ssl_getclientauthdatahook mxr 3.2 and later ssl_getmaxservercachelocks mxr 3.4 and later ssl_getsessionid mxr 3.2 and later ssl_getstatistics mxr 3.2 and later ssl_handshake
callback mxr 3.2 and later ssl_importfd mxr 3.2 and later ssl_inheritmpserversidcache mxr 3.2 and later ssl_invalidatesession mxr 3.2 and later ssl_localcertificate mxr 3.4 and later ssl_optionget mxr 3.2 and later ssl_optiongetdefault mxr 3.2 and later ssl_optionset mxr 3.2 and later ...
...applications that want to use the ssl shared libraries must convert to
calling the new replacement functions listed below.
NSS tools : vfychain
the tasks associated with security module database management are part of a process that typi
cally also involves managing key databases and certificate databases.
... options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by
calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more.
NSS Tools crlutil
-i crl-import-file specify the file which contains the crl to import -f password-file specify a file that will automati
cally supply the password to include in a certificate or to access a certificate database.
... issueraltnames non-critical name-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names add crl number extension: the crl number is a non-critical crl extension which conveys a monotoni
cally increasing sequence number for a given crl scope and crl issuer.
NSS tools : vfychain
the tasks associated with security module database management are part of a process that typi
cally also involves managing key databases and certificate databases.
... options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by
calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more.
Multithreading in Necko
the internal i/o interfaces default to proxying all
callbacks to the main thread.
...the default implementation does not spawn a worker thread, and instead simply
calls pr_getipnodebyname (essentially equivalent to gethostbyname).
Renaming With Pork
typi
cally they require loading the entire project into an ide.
...typi
cally, make cxxflags="-wp,-k,-w0 -save-temps" will work.
Rhino Debugger
controlling execution the debugger provides the following facilities for you to control the execution of scripts you are debugging: step into to single step entering any function
calls, you may do any of the following: select the debug->step into menu item on the menu bar press the step into button on the toolbar press the f11 key on the keyboard execution will resume.
... if the current line in the script contains a function
call control will return to the debugger upon entry into the function.
Rhino history
when netscape stopped work on "javagator," as it was
called, somehow rhino escaped the axe (rumor had it that the executives "forgot" it existed).
...the classfile generation code was moved to an optional, dynami
cally-loaded package.
Rhino serialization
d 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.
...if you are using rhino serialization in an environment where you always define, say, a constructor foo, you should add the following code before
calling writeobject: out.addexcludedname("foo"); out.addexcludedname("foo.prototype"); this code will prevent foo and foo.prototype from being serialized and will cause references to foo or foo.prototype to be resolved to the objects in the new scope upon deserialization.
SpiderMonkey Build Documentation
for a list of other available build options, type (assuming the current working directory is one of the above-created build directories): /bin/sh ../configure.in --help generating a compilation database some tools (like ides, static analyzers and refactoring tools) consume a file
called compile_commands.json which contains a description of all the pieces required to build a piece of software so that tools don't have to also understand a build system.
...we highly recommend
calling the js-config script from your embedding's makefile to set your cflags, ldflags, and so forth.
SpiderMonkey compartments
we
call these objects cross-compartment wrappers.
... see also js_newcompartmentandglobalobject() js_entercrosscompartment
call() js_leavecrosscompartment
call() jsautocompartment invariants spidermonkey internals: thread safety andreas gal blog post bobby holley blog post sfink/contexts_and_compartments xpconnect security membranes ...
JS::AutoIdArray
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... description js::autoidarray takes the ownership of jsidarray, and frees it in destructor by
calling js_destroyidarray.
JS::AutoValueArray
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...this is typi
cally used for local variables being passed to function which requires js::handlevaluearray or a pointer to js::value array.
JS::Handle
first, when several such functions
call each other then redundant rooting of multiple copies of the gc thing can be avoided.
... second, if the
caller does not pass a rooted value a compile error will be generated, which is quicker and easier to fix than when relying on a separate rooting analysis.
JS::HandleValueArray
syntax js::handlevaluearray(const js::rootedvalue& value); js::handlevaluearray(const js::autovaluevector& values); js::handlevaluearray(const js::autovaluearray<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 & an element of newly created 1-length array.
... args js::
callargs & elements of newly created array.
JS::SourceBufferHolder
any code
calling sourcebufferholder::take() must guarantee to keep the memory alive until js compilation completes.
... normally only the js engine should be
calling take().
JS::ToString
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... if v.isstring() is true, it
calls v.tostring().
JSEnumerateOp
jsenumerateop is the type of the jsclass.enumerate
callback.
... description jsenumerateop is
called just before an object is enumerated (via a for...in statement, an array comprehension, or a
call to js_enumerate).
JSErrorReport
callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports.
...we check the strictness of the context's top frame's script; where that isn't appropriate, the
caller should do the right checks itself instead of using this flag.
JSExtendedClass.outerObject
jsextendedclass.outerobject and .innerobject are
callbacks for split objects.
...
callback syntax typedef jsobject * (*jsobjectop)(jscontext *cx, jsobject *obj); name type description cx jscontext * a context.
JSObjectOp
jsobjectop is the type of several jsapi
callbacks that map an object to another object, or null if an error or exception occurred.
... typedef jsobject * (*jsobjectop)(jscontext *cx, jsobject *obj); the
callbacks of this type are: jsextendedclass.outerobject jsextendedclass.innerobject jsextendedclass.wrappedobject jsobjectops.thisobject ...
JSObjectOps.getAttributes
the jsobjectops.getattributes and setattributes
callbacks are
called to access the attributes of a property.
...if prop is non-null, it must come from the *propp out parameter of a prior jsobjectops.defineproperty or jsobjectops.lookupproperty
call.
JSObjectOps.getRequiredSlot
the jsobjectops.getrequiredslot and setrequiredslot
callbacks get and set a required slot—one that should already have been allocated.
...the native ops (js_objectops, see js/src/jsobj.cpp) access slots reserved by including a
call to the jsclass_has_reserved_slots(n) macro in the jsclass.flags initializer.
JSPRINCIPALS_HOLD
application code that stores a pointer to a jsprincipals object must
call jsprincipals_hold(cx, principals) before storing it and jsprincipals_drop(cx, principals) when done with it.
...if the reference count drops to 0, indicating that no one is using the object anymore, jsprincipals_drop also deallocates principals by
calling its destroy method.
JSPropertyDescriptor
properties a descriptor is an object that can have the following key values field name description getter the get syntax binds an object property to a function that will be
called when that property is looked up.
... setter the set syntax binds an object property to a function to be
called when there is an attempt to set that property.
JSPropertySpec
tinyid int8 obsolete since jsapi 31 unique id number for the property to aid in resolving getproperty and setproperty method
calls.
...if a property is read-only, its setter is never
called.
JSReserveSlotsOp
rather, within a jsruntime, every
call to the same reserveslots hook must return the same value (excepting a few internal classes such as function,
call, and block).
... jsclass hooks jsclass offers the following hook: the jsclass.reserveslots
callback is
called each time a new object is created.
JSRuntime
a program typi
cally has only one jsruntime, even if it has many threads.
... all javascript code and most jsapi
calls run within a jscontext.
JSVAL_TO_GCTHING
applications should not
call it directly in most cases.
...another possible alternative is to avoid casting altogether by using an api that operates on jsvals rather than raw pointers (for example, js_
call_value_tracer rather than js_
call_tracer).
JS_CheckForInterrupt
js_checkforinterrupt returns false if interrupt
callback returns false.
... see also mxr id search for js_checkforinterrupt js_setinterrupt
callback js_getinterrupt
callback js_requestinterrupt
callback bug 1058695 ...
JS_ClearDateCaches
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...
call to propagate a system timezone change.
JS_ClearPendingException
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...(there is a pending exception if the most recently thrown exception in cx has not yet been caught or cleared.) when any jsapi
call fails with an exception, the
caller must either use js_clearpendingexception to catch the exception; or return false to allow the exception to propagate to the
caller.
JS_CompareStrings
there is no attempt to use the more complex, semanti
cally oriented definitions of character or string equality and collating order defined in the unicode specification.
... therefore strings that are canoni
cally equal according to the unicode standard could test as unequal.
JS_CompileFunction
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... see also mxr id search for js_compilefunction mxr id search for js_compileucfunction jsfun_bound_method jsfun_global_parent js_
callfunction js_
callfunctionname js_
callfunctionvalue js_decompilefunction js_decompilefunctionbody js_definefunction js_definefunctions js_getfunctionobject js_newfunction js_setbranch
callback js_valuetofunction bug 1089026 ...
JS_CompileFunctionForPrincipals
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... 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_CompileScriptForPrincipals
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... 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.
JS_ContextIterator
on success, the value of *iterp is modified so that repeated
calls cycle through all the contexts in rt.
...each
call to js_contextiterator returns the next context in the cycle.
JS_DecompileScript
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...if script is a function, it
calls js_decompilefunction.
JS_DefineElement
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...while you can assign a setproperty method to a property and set flags to jsprop_readonly, the setter method will not be
called on this property.
JS_DefineProperties
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...each property is defined as though by
calling js_defineproperties.
JS_DeleteElement
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...to remove all elements and properties from an object,
call js_clearscope.
JS_DeleteElement2
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... to remove all properties from an object,
call js_clearscope.
JS_DestroyContext
in a js_threadsafe build, it does not matter whether the
calling thread is in a request on cx.
...if js_setcontext
callback has been
called, this
calls the
callback.
JS_DumpHeap
other users // should sort alphabeti
cally, for consistency.
... see js::value::gckind() and jstrace
callback in <codde>tracer.h</codde> for more details.
JS_EnterCompartment
syntax jscompartment * js_entercompartment(jscontext *cx, jsobject *target); name type description cx jscontext * the context on which a cross-compartment
call is needed.
...any access to an object in a different compartment must be bracketed by
calling js_entercompartment and js_leavecompartment.
JS_EnumerateStandardClasses
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... description the global object's class's enumerate op should
call js_enumeratestandardclasses(cx, obj), to define eagerly during for...in loops any classes not yet resolved lazily.
JS_GetArrayLength
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... description js_getarraylength gets the .length property of obj as though by
calling js_getproperty and converts it to a 32-bit unsigned integer.
JS_GetFunctionArity
specifi
cally, if fun is a native function, the result is the value that was passed to the nargs parameter of js_definefunction.
... note that it is not an error per se to
call a javascript function with more or fewer actual arguments than its arity.
JS_GetGlobalObject
furthermore, some jsapi functions, such as js_executescript, allow the
caller to specify a global object in which the script executes.
...first, it is a convenient place for the application to stash the global object, where it is automati
cally protected from garbage collection and the application can easily access it.
JS_InternString
get an interned string - a jsstring that is protected from gc and automati
cally shared with other code that needs a jsstring with the same value.
...in a js_threadsafe build, the
caller must be in a request on this jscontext.
JS_LeaveCompartment
oldcompartment jscompartment * value returned by previous
call to js_entercompartment.
...any access to an object in a different compartment must be bracketed by
calls to js_entercompartment and js_leavecompartment.
JS_LeaveLocalRootScope
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...leaving a nested local root scope causes all objects created since the matching js_enterlocalrootscope
call to become subject to garbage collection.
JS_MapGCRoots
syntax uint32 js_mapgcroots(jsruntime *rt, jsgcrootmapfun map, void *data);
callback syntax #define js_map_gcroot_next 0 /* continue mapping entries */ #define js_map_gcroot_stop 1 /* stop mapping entries */ #define js_map_gcroot_remove 2 /* remove and free the current entry */ typedef int (*jsgcrootmapfun)(void *rp, const char *name, void *data); description
call js_mapgcroots to map the gc's roots table using map(rp, name, data).
...the map function cannot
call js_gc, js_maybegc, js_beginrequest, or any js api entry point that acquires locks, without double-tripping or deadlocking on the gc lock.
JS_NewCompartmentAndGlobalObject
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... the
caller must ensure that the jsclass remains alive throughout the lifetime of the new object, including the garbage collection cycle that finally frees it.
JS_NewObject
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... if clasp is non-null, the
caller must ensure that the jsclass remains alive throughout the lifetime of the new object, including the garbage collection cycle that finally frees it.
JS_NextProperty
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... iterobj js::handleobject the opaque iterator object returned by a previous
call to js_newpropertyiterator.
JS_PreventExtensions
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... for example, a proxy might refuse to be made non-extensible; this refusal would show up in the post-
call value of *succeeded.
JS_SaveExceptionState
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...the jsexceptionstate created by this function automati
cally roots any pending exception object which needs to be protected from the gc.
JS_SetNativeStackQuota
the stack quotas for each kind of code should be monotoni
cally descending, and may be specified with this function.
... this function may only be
called immediately after the runtime is initialized and before any code is executed and/or interrupts requested.
JS_SetPrivate
in particular: if you allocate memory for private data, you must free it, typi
cally in a jsclass.finalize
callback.
... if your class's private data contains any jsvals or other references to javascript objects, implement the jsclass.mark
callback to ensure they are not prematurely reclaimed by the garbage collector.
JS_SetPrototype
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...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_SetScriptStackQuota
the function must be
called before any script compilation or execution api
calls, i.e.
... either immediately after js_newcontext or from the jscontext_new context
callback.
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.
...the engine automati
cally catches the exception and exits the loop.
JS_ValueToECMAInt32
in a js_threadsafe build, the
caller must be in a request on this jscontext.
... all three functions first convert v to a floating-point number as if by
calling js_valuetonumber; nan values are then converted to zero.
JS_ValueToId
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...if v is not a string, it is converted to a string as if by
calling js_valuetostring.
JS_ValueToInt32
in a js_threadsafe build, the
caller must be in a request on this jscontext.
...first it converts v to a floating-point number as if by
calling js::tonumber.
JS_malloc
if any of these three functions fails to allocate the required amount of memory, it reports an error as though by
calling js_reportoutofmemory(cx) and returns null.
... js_free deallocates a region of memory allocated a previous
call to js_malloc, js_realloc, or js_strdup.
Stored value
the new stored value is the result of getting or setting the property, after the getter or setter, if any, is
called.
...es5 accessor properties, as in {get length() { return 0; }, automati
cally have jsprop_shared.
JSDBGAPI
letrap js_setinterrupt js_clearinterrupt watchpoints js_setwatchpoint js_clearwatchpoint js_clearwatchpointsforobject js_clearallwatchpoints inspecting the stack js_pctolinenumber js_linenumbertopc js_getfunctionscript js_getfunctionnative js_getfunctionfastnative js_getscriptprincipals typedef jsstackframe js_frameiterator js_getframescript js_getframepc js_getscripted
caller js_stackframeprincipals js_evalframeprincipals js_getframeannotation js_setframeannotation js_getframeprincipalarray js_isnativeframe js_getframeobject js_getframescopechain js_getframe
callobject js_getframethis js_getframefunction js_getframefunctionobject js_isconstructorframe js_isdebuggerframe js_getframereturnvalue js_setframereturnvalue js_getframe
calleeobject js_ge...
...luateinstackframe examining object properties typedef jspropertydesc 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_set
callhook 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 p...
SpiderMonkey 24
many jsapi types, functions, and
callback signatures have changed, though most of them still have the same names and do the same things.
... many of the garbage collector changes require type signature changes to jsapi methods: specifi
cally introducing js::rooted, js::handle, and js::mutablehandle types.
Using RAII classes in Mozilla
static analysis static analysis passes are run on our testing infrastructure using our clang plugin, you can also run them lo
cally marking a raii class for the static analysis is very simple, and performing this marking causes the static analysis to produce a build-time error whenever a raii class is allocated as a temporary, on the heap, or in static storage.
... assertions runtime assertions offer two benefits - firstly, they run on windows, which the static analysis currently does not, and secondly they will run lo
cally, even if the developer did not choose to run static analysis lo
cally.
A Web PKI x509 certificate primer
one issue that is not commonly known is that the x509 trust graph is not a forest (a bunch of trees where each root is a trusted root) but a cyclic graph, where the same key/issuer can be a root or an intermediate for another root in the browsers key store (when roots create intermediates for each other it is
called cross-signing).
...this chain of certificates is
called the certificate hierarchy.
AT APIs Support
they typi
cally use standard windows controls for their user interface -- the area outside of the client content window, plus the context menu.
...widgets such as menus, tab panels, tree views and dialogs are provided via an xml language
called xul (extensible user-interface language).
Feed content access API
the actual processing of the parsed feed is done by a method
called handleresult() on the feedtestresultlistener object.
...to initialize a fetch of the feed, we simply
call fetch(url).
The Places database
periodi
cally at runtime, the following happens to expire pages: expire visits that are older than the history expiration threshold.
...there are several ways for orphans to be created, including
calling markpageastyped and then never visiting the page.
Querying Places
typi
cally, you will only have one folder id in this list, which will given you the contents of that folder.
...this viewer will be
called when the result tree changes, either as a result of user action or as a result of notifications from the bookmarks and history systems.
Using the Places livemark service
note: the
caller is responsible for reloading the livemark after changing its feed uri (since the contents are likely to be different given a different feed).
...the expiration time for a livemark is determined by using information provided by the server when the feed was requested, specifi
cally nsicacheentryinfo.expirationtime.
Bundling multiple binary components
possible solutions this article covers two possible ways to make binary components support multiple version of gecko: dynamic method loading stub loader dynamic method loading the idea with this approach is to figure out all the methods imported from gecko and dynami
cally load the methods.
... create small wrappers for
calling the methods, as you may need to thunk parameters depending on how much has changed between gecko versions.
Creating a Python XPCOM component
theoreti
cally, because several components can share an interface, the same file could be used.
... 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.
Generic factory
*/ class nsigenericfactory : public nsifactory { public: static const nsiid& iid() { static nsiid iid = ns_igenericfactory_iid; return iid; } typedef ns_
callback(constructorprocptr) (nsisupports *aouter, refnsiid aiid, void **aresult); /** * establishes the generic factory's constructor function, which will be
called * by createinstance.
...define a constructor function that matches the constructorprocptr prototype, and
call nsigenericfactory::setconstructor with a pointer to that function.
Setting up the Gecko SDK
i used a different firefox profile for testing purposes
called extensions.
... a makefile for unix on linux, the equivalent project settings are typi
cally handled in a makefile.
XPCOM guide
the problem would not exist with java's interfaces).making cross-thread
calls using runnablesin the mozilla platform, most activities such as layout, dom operations, content javascript, and chrome javascript run on the main thread.
... mozilla::services namespacethe services 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 usa...
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.
... determining if a component has to be instantiated or used as a service in the general case it is not possible to programmati
cally determine if a given component has to be instantiated or used as a service.
Components.returnCode
usage components.returncode is a property that can be used to indicate to an xpcom
caller of the javascript method that the method is returning a specific nsresult code.
...by default the successful completion of the javascript method will cause xpconnect to return a result code of ns_ok to the
caller.
Components.utils.evalInWindow
even so, while the code is being evaluated it is in the content's context, so the
caller has to be prepared for the possibility that the content could have redefined behavior (for example, a setter in the script may have been redefined to do something unexpected).
...if the returned object contains a function,
calls to evalinwindow() will throw an error: // page-script.js function bar() { } var somelocalvariablecontainingafunction = {name: "selection1", foo : bar}; // add-on-script.js components.utils.evalinwindow("somelocalvariablecontainingafunction", contentwindow); // error, function can't be cloned ...
Components.utils.importGlobalProperties
knowing that, we can just get a valid blob by importing a known module that has the objects, such as services.jsm const {blob, file, services} = cu.import("resource://gre/modules/services.jsm", {}); reference: stackoverflow :: use blob on firefox add-on hiddendomwindow the hidden domwindow has all of these objects automati
cally imported.
... var domfile = services.appshell.hiddendomwindow.file('/path/to/file'); xpcom components some objects have an xpcom alternative, which typi
cally allows more flexibility then the dom version here is an example of how to use the dom xmlhttprequest through xpcom interface of nsixmlhttprequest: var oreq = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(ci.nsixmlhttprequest); ...
Components.utils.reportError
it must be
called with one parameter, usually an object which was caught by an exception handler.
... examples usage in an exception handler: try { this.could.raise.an.exception; } catch(e) { components.utils.reporterror(e); // report the error and continue execution } sending debugging messages to the error console: components.utils.reporterror("init()
called"); ...
Components.utils.schedulePreciseGC
using scheduleprecisegc() when you
call components.utils.scheduleprecisegc(), you specify a
callback that is executed in once the scheduled garbage collection has been completed: components.utils.scheduleprecisegc( function() { // this code is executed when the garbage collection has completed } ); since the garbage collection doesn't occur until some time in the future (unlike, for example, components.utils.forcegc(), which c...
...auses garbage collection immediately but isn't able to collect all javascript-related memory), the
callback lets you know when that's been finished.
Components.utils.unload
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.
... example you can unload a module
called mymodule.jsm using the following line of code: components.utils.unload("resource://myaddon/modules/mymodule.jsm"); note: currently components.utils.unload clears the global object of an unloaded module.
nsIRegistry
now, i know from visual inspection that there's a key
called "directory" for each profile.
... i don't know how to get the other keys' names automati
cally, but i do know how to look up the directory for a particular profile.
HOWTO
in all
callbacks where your script is finished, i.e.
... both success and error
callbacks, put: gscriptdone = true; if you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait).
Profiling XPCShell
you can just
call the code you want to test.
...the line consists of: the compile count of the function; the
call count of the function; the functions name; the starting line number; the ending line number; the function's size; the amount of time (in milliseconds) the fastest
call took; the time of the slowest
call; the average time spend; the total time; the time spend in the function itself is given (that is the total time excluding the time spend in functions
called from this function).
XPCShell Reference
for instance, assume that you have a file
called test.js with the following contents: for (prop in arguments) { print(prop + "=" + arguments[prop]); } entering the following at the command line should produce the following output: $ xpcshell test.js this is a test 0=this 1=is 2=a 3=test xpcshell extensions once you execute xpcshell without a script you'll be at the js> command line.
...for example, if you created anobject with a property named value and then
called clear(anobject), the property value would no longer exist.
Monitoring HTTP activity
gecko includes the nsihttpactivityobserver interface, which you can implement in your code to monitor http transactions in real time, receiving a
callback as the transactions take place.
...this is very simple, requiring you to implement a single method, nsihttpactivityobserver.observeactivity(), which gets
called each time an action of interest takes place on the http channel.
NS_NewLocalFile
afollowlinks [in] this attribute will determine if the nsilocalfile instance will automati
cally resolve symbolic links.
...on windows, passing true causes shortcuts to be automati
cally resolved, and on macos, passing true causes finder aliases to be automati
cally resolved.
NS_NewNativeLocalFile
afollowlinks [in] this attribute will determine if the nsilocalfile instance will automati
cally resolve symbolic links.
...on windows, passing true causes shortcuts to be automati
cally resolved, and on macos, passing true causes finder aliases to be automati
cally resolved.
Core XPCOM functions
ent manager.ns_getcomponentregistrarthe ns_getcomponentregistrar function returns a reference to the xpcom component registrar.ns_getmemorymanagerthe ns_getmemorymanager function returns a reference to the xpcom memory manager.ns_getservicemanagerthe ns_getservicemanager function returns a reference to the xpcom service manager.ns_initxpcom2the ns_initxpcom2 function initiates use of xpcom in the
calling process.ns_initxpcom3the ns_initxpcom3 function initiates use of xpcom in the
calling process with support for stati
cally defined xpcom modules.
... 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_shutdownxpcom function terminates use of xpcom in the
calling process.nsresultthe nsresult data type is a strongly-typed enum used to represent a value returned by an xpcom function; these are typi
cally error or status codes.
nsACString
this class is typi
cally used to represent ascii or utf-8 character arrays.
...thus, the length of the data contained in the nsacstring should be determined by
calling the nsacstring::length() method.
nsAString
this class is typi
cally used to represent unicode character arrays.
...thus, the length of the data contained in the nsastring should be determined by
calling the nsastring::length method.
IAccessible2
an extended role is a role which is dynami
cally generated by the application.
...an extended state is a state which is dynami
cally generated by the application.
imgICache
any images from windows in private browsing mode will not be present in the cache returned from a
call with a null parameter).
... findentryproperties() find properties used to get properties such as 'type' and 'content-disposition' 'type' is a nsisupportscstring containing the images' mime type such as 'image/png' 'content-disposition' will be a nsisupportscstring containing the header if you
call this before any data has been loaded from a uri, it will succeed, but come back empty.
imgIDecoder
this object also implements the imgidecoderobserver interface; you should queryinterface() it to that interface and
call its notification methods while handling the decode operation.
...if this method was provided as an external facility, a separate char * buffer would need to be used in order to
call the output stream's other write() method.
mozIPlacesAutoComplete
note: pages will not be automati
cally unregistered when private browsing mode is entered or exited.
...note: pages will not be automati
cally unregistered when private browsing mode is entered or exited.
mozIStorageBindingParams
the mozistoragebindingparams interface is used to bind values to parameters prior to
calling mozistoragestatement.executeasync().
... 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().
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().
...the appended parameters will be used when mozistoragestatement.executeasync() is
called.
mozIStorageStatementWrapper
when you
call the mozistorageconnection interface's createstatement() method, you get a mozistoragestatement which has just direct bindings to sqlite.
... params mozistoragestatementparams the parameters; these can be set in lieu of using the
call notation on this.
mozIStorageValueArray
note: c++
callers should be aware that a string value for a null column has isvoid set to distinguish it from an empty string.
... note: c++
callers should be aware that a string value for a null column has isvoid set to distinguish it from an empty string.
mozITXTToHTMLConv
you must set this value to zero before
calling this method.
... remarks you can
call this method repeatedly, passing in updated values for apos, to locate all the urls in a string.
mozIThirdPartyUtil
obtain the bottommost nsidomwindow, and its same-type parent if it exists, from the channel's notification
callbacks.
...
call this the 'bottom uri'.
GetAccessibleAbove
« nsiaccessible page summary this method returns an accessible node geometri
cally above this one.
... nsiaccessible getaccessibleabove(); return value returns an accessible node geometri
cally above this one.
GetAccessibleBelow
« nsiaccessible page summary this method returns an accessible node geometri
cally below this one.
... nsiaccessible getaccessiblebelow(); return value returns an accessible node geometri
cally below this one.
GetAccessibleToLeft
« nsiaccessible page summary this method returns an accessible node geometri
cally to the left of this one.
... nsiaccessible getaccessibletoleft(); return value returns an accessible node geometri
cally to the left of this one.
GetAccessibleToRight
« nsiaccessible page summary this method returns an accessible node geometri
cally to the right of this one.
... nsiaccessible getaccessibletoright(); return value returns an accessible node geometri
cally to the right of this one.
nsIAccessibleRelation
relation_flows_to 0x07 content flows from this object to a target object, that is has content that flows logi
cally to another object in a sequential way, for example text flow.
... relation_flows_from 0x08 content flows to this object from a target object, that is has content that flows logi
cally from another object in a sequential way, for example text flow.
nsIAutoCompleteObserver
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void onsearchresult(in nsiautocompletesearch search, in nsiautocompleteresult result); void onupdatesearchresult(in nsiautocompletesearch search, in nsiautocompleteresult result); methods onsearchresult()
called when a search is complete and the results are ready.
... onupdatesearchresult()
called to update with new results.
nsICacheEntryDescriptor
visitmetadata() this method means that the visitor will be
called with key/value pair for each meta data element.
... void visitmetadata( in nsicachemetadatavisitor visitor ); parameters visitor the visitor to be
called.
nsICacheListener
inherits from: nsisupports last changed in gecko 14 (firefox 14 / thunderbird 14 / seamonkey 2.11) method overview void oncacheentryavailable(in nsicacheentrydescriptor descriptor, in nscacheaccessmode accessgranted, in nsresult status); void oncacheentrydoomed(in nsresult status); methods oncacheentryavailable() this method is
called when the requested access (or appropriate subset) is acquired.
... oncacheentrydoomed() this method is
called when the processing started by nsicachesession.doomentry() is completed.
nsICacheVisitor
inherits from: nsisupports last changed in gecko 1.7 method overview boolean visitdevice(in string deviceid, in nsicachedeviceinfo deviceinfo); boolean visitentry(in string deviceid, in nsicacheentryinfo entryinfo); methods visitdevice() this method is
called to provide information about a cache device.
...visitentry() this method is
called to provide information about a cache entry.
nsIClassInfo
this attribute is similar to the classid attribute; however, this attribute exists so that c++
callers can avoid allocating and freeing a nscid object, as would happen if they used classid.
... for example, if asked for the helper for nsiprogramminglanguage::javascript this might return an object that can be nsisupports.queryinterface()'d into the nsixpcscriptable interface to assist xpconnect in supplying javascript specific behavior to
callers of the instance object.
nsICommandLine
state_remote_auto 1 a remote command line automati
cally redirected to this instance.
... removearguments() removes a range of arguments from the command line; this is typi
cally done once those arguments have been handled.
nsICommandLineRunner
methods init()
called with the argc/argv combination passed to main.
... run() processes the command-line handlers in the proper order, and
calls nsicommandlinehandler.handle() on each.
nsIContentPrefObserver
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void oncontentprefremoved(in astring agroup, in astring aname); void oncontentprefset(in astring agroup, in astring aname, in nsivariant avalue); methods oncontentprefremoved()
called when a content preference is removed.
... oncontentprefset()
called when the value of a preference is set (either by changing its current value or by creating the preference).
nsICycleCollectorListener
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the order of
calls will be
call to begin(); then for every node in the graph a
call to noteobject() and
calls to noteedge() for every edge starting at that node; then a
call to begindescriptions(); then for every black node in the cycle collector graph a
call to either describerefcountedobject() or to describegcedobject(); and then a
call to end().
... if begin() returns an error none of the other functions will be
called.
nsIDOMMozNetworkStatsManager
networkstatsalarmoptions networkstatsalarmoptions is a dictionary object used to filter an alarm request made when
calling addalarm().
... networkstatsgetoptions networkstatsgetoptions is a dictionary object used to filter a network statistics request made when
calling getsamples().
nsIDOMSimpleGestureEvent
mozmagnifygestureupdate - generated periodi
cally while the user is continuing the magnify ("pinch") gesture.
... mozrotategestureupdate - generated periodi
cally while the user is continuing the rotation gesture.
nsIDOMUserDataHandler
dom/interfaces/core/nsidomuserdatahandler.idlscriptable the
callback function for the setuserdata method.
... methods handle() this method is a
callback which will be
called if a node with user data is being cloned, imported or adopted.
nsIDOMWindowInternal
pageyoffset long returns the number of pixels that the document has already been scrolled verti
cally.
... scrollmaxy long returns the maximum number of pixels that the document can be scrolled verti
cally.
nsIDebug
inherits from: nsisupports last changed in gecko 1.7 note: c/c++ consumers who are planning to use the nsidebug interface with the @mozilla.org/xpcom;1 contract should use ns_debugbreak() from xpcom glue instead, or alternatively the ns_abort, ns_assertion, ns_break, and ns_warning macros, which also
call ns_debugbreak() if used in a debugging build.
... assertion() shows an assertion and triggers optional behavior based on the xpcom_debug_break environment variable, defaulting to
calling break() on windows and os/2 and warning on other platforms.
nsIDeviceMotion
methods addlistener() when
called, the accelerometer support implementation must begin to notify the specified nsidevicemotionlistener by
calling its nsidevicemotionlistener.onaccelerationchange() method as appropriate to share updated acceleration data.
... void addlistener( in nsidevicemotionlistener alistener ); parameters alistener the nsidevicemotionlistener object whose nsidevicemotionlistener.onaccelerationchange() method should be
called with updated acceleration data.
nsIDirIndexListener
ormed into an output format (such as rdf, html and so on) inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void onindexavailable(in nsirequest arequest, in nsisupports actxt, in nsidirindex aindex); void oninformationavailable(in nsirequest arequest, in nsisupports actxt, in astring ainfo); methods onindexavailable()
called for each directory entry.
... oninformationavailable()
called for each information line.
nsIDirIndexParser
inherits from: nsistreamlistener last changed in gecko 1.7
called for each directory entry.
... listener nsidirindexlistener the interface to use as a
callback for new entries.
nsIDirectoryServiceProvider
method overview nsifile getfile(in string prop, out prbool persistent); methods getfile() the directory service
calls this method when it gets the first request for a prop or on every request if the prop is not persistent.
...example this code creates a global, read-only string
called currdir with the value of the current working directory.
nsIDownloadManagerUI
methods getattention()
calls attention to the download manager's user interface if it's already open.
... the ui need not be visible to
call this function, nor will the ui be made visible.
nsIDroppedLinkHandler
if a uri is returned the
caller can, for instance, load it.
...if non-empty links array is returned the
caller can, for instance, load it.
nsIExternalHelperAppService
the
caller should pump data into the returned stream listener.
... return value a nsistreamlistener which the
caller should pump the data into.
nsIFile
followlinks prbool determines whether or not the nsifile will automati
cally resolve symbolic links.
... note: this method does not return a new nsifile; it modifies the object it was
called on.
nsIFileOutputStream
the deferred open will be performed when one of the following is
called: seek() tell() write() flush() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well.
... note: using this flag results in the file not being opened during the
call to init().
nsIFileURL
callers must clone before attempting to modify the returned nsifile object.
...the setter clones the nsifile object (allowing the
caller to safely modify the nsifile object after setting it on this interface).
nsIFrameMessageListener
called to deliver a message to the frame handling process;
called with one parameter, which has the following properties: name the name of the message.
... when the listener is
called, the this value is the target of the message.
nsIFrameMessageManager
alistener an object implementing nsiframemessagelistener whose receivemessage method will be
called when the message is received.
... removemessagelistener() removes a message listener previously added by
calling addmessagelistener().
nsIGlobalHistory3
otherwise, nsiglobalhistory2.adduri() should be
called with redirect=true.
...if they do so, then
callers must
call nsiglobalhistory2.adduri() upon getting the ns_error_not_implemented result.
nsIHTMLEditor
void addinsertionlistener( in nsicontentfilter infilter ); parameters infilter function which
callers want
called during insertion.
... void removeinsertionlistener( in nsicontentfilter infilter ); parameters infilter function which
callers do not want
called during insertion.
nsIHttpActivityObserver
if this is false, the observeactivity() method should not be
called.
... methods observeactivity()
called when activity occurs on the http transport.
nsIINIParser
inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) typi
cally, you'll create an nsiiniparser object by
calling nsiiniparserfactory.createiniparser().
...examples getting a value for a key this example provides a function you can
call to obtain the value for a specific key in a given ini file.
nsIINIParserWriter
when you're done and ready to write the ini file to disk,
call the writefile() method.
... method overview void setstring(in autf8string asection, in autf8string akey, in autf8string avalue); void writefile([optional] in nsifile ainifile, [optional] in unsigned long aflags); constants file writing constants these constants are specified when
calling writefile(), in order to change its behavior.
nsIIOService
newchannel() obsolete since gecko 48 a shortcut method to avoid repeated
calls of newuri() and newchannelfromuri().
... newchannel2() a shortcut method to avoid repeated
calls of newuri() and newchannelfromuri().
nsIMessageWakeupService
the method to
call to instantiate the component (either "getservice" or "createinstance").
... alternatively, it is possible to register a wakeup entry programmati
cally via the nsicategorymanager interface.
nsIMessenger
unfortunately, you must
call this before navigating to a position, because
calling this has the side effect of making us adjust our current history position, and not adding the loaded message to the history queue.
...if
caller just wants the count and current pos, they can pass in null for ahistory, which will be more efficent.
nsIMsgDBView
this method will automati
cally expand the destination thread.
... ondeletecompleted()
called when delete is completed on a message.
nsIMsgDBViewCommandUpdater
places: nsmsgdbviewcommandupdater (for the standalone message window) nsmsgdbviewcommandupdater (for the threadpane message window) nsmsgsearchcommandupdater (for search dialogs) method overview void updatecommandstatus(); void displaymessagechanged(in nsimsgfolder afolder, in astring asubject, in acstring akeywords); void updatenextmessageafterdelete(); methods updatecommandstatus()
called when the number of selected items changes.
... displaymessagechanged()
called when the displayed message has changed.
nsIMsgFilterCustomAction
*/ /** * apply the custom action to an array of messages * * @param msghdrs array of nsimsgdbhdr objects of messages * @param actionvalue user-set value to use in the action * @param copylistener
calling method (filtertype manual only) * @param filtertype type of filter being applied * @param msgwindow message window */ void apply(in nsiarray msghdrs /* nsimsgdbhdr array */, in autf8string actionvalue, in nsimsgcopyservicelistener copylistener, in nsmsgfiltertypetype filtertype, in nsimsgwindow msgwindow); /* does ...
...
call onstopcopy when done * using the copylistener to continue.
nsIMsgSearchSession
to create an instance, use: var searchsession = components.classes["@mozilla.org/messenger/searchsession;1"] .createinstance(components.interfaces.nsimsgsearchsession); to use the instance append search terms, set the scope, and then
call search().
... void addscopeterm(in nsmsgsearchscopevalue scope, in nsimsgfolder folder); parameters scope folder adddirectoryscopeterm() void adddirectoryscopeterm(in nsmsgsearchscopevalue scope); parameters scope clearscopes() void clearscopes(); scopeusescustomheaders()
call this function everytime the scope changes!
nsIParserUtils
astring converttoplaintext( in astring src, in unsigned long flags, in unsigned long wrapcol ); parameters src the html source to parse (c++
callers are allowed but not required to use the same string for the return value.) flags conversion option flags defined in nsidocumentencoder.
... astring sanitize( in astring src, in unsigned long flags ); parameters src the html source to parse (c++
callers are allowed but not required to use the same string for the return value).
nsIPrivateBrowsingService
to get access to the service from javascript, use: var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); c++
callers should use the contract id @mozilla.org/privatebrowsing-wrapper;1 instead.
... method overview void removedatafromdomain(in autf8string adomain); attributes attribute type description autostarted boolean indicates whether or not private browsing was started automati
cally at application launch time.
nsIPrompt
normally you would use the prompt service as it is more flexible, but sometimes a
callback will request an nsiprompt via nsiinterfacerequestor.getinterface().
... to get an instance,
call the nsiwindowwatcher.getnewprompter().
nsIScriptError
this is zero if the error was initialized by
calling nsiscripterror.init() instead of initwithwindowid().
...this is zero if the error was initialized by
calling nsiscripterror.init() instead of initwithwindowid().
nsIScriptError2
this is zero if the error was initialized by
calling nsiscripterror.init() instead of initwithwindowid().
...this is zero if the error was initialized by
calling nsiscripterror.init() instead of initwithwindowid().
nsISearchEngine
iconuri nsiuri a nsiuri corresponding to the engine's icon, stored lo
cally.
...this should only be
called on engines created via nsibrowsersearchservice.addenginewithdetails().
nsISelection
as a service: var selection = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsiselection); method overview void addrange(in nsidomrange range); void collapse(in nsidomnode parentnode, in long offset); [noscript,notxpcom,nostd
call] boolean collapsed(); void collapsenative(in nsidomnode parentnode, in long offset); native code only!
... collapsed() [noscript,notxpcom,nostd
call] boolean collapsed(); native code only!collapsenative void collapsenative( in nsinode parentnode, in long offset ); parameters parentnode offset collapsetoend() collapses the whole selection to a single point at the end of the current selection (regardless of direction).
nsIServerSocket
the listener's onsocketaccepted() method will be
called on the same thread that
called asynclisten() (the
calling thread must have an nsieventtarget).
...pass -1 to indicate no preference, and a port will be selected automati
cally.
nsIStackFrame
inherits from: nsisupports last changed in gecko 1.7 method overview string tostring(); attributes attribute type description
caller nsistackframe read only.
... example to output the stack at a particular location: var s = components.stack; while(s) { console.log(s.name); s = s.
caller; } methods tostring() a generic formatter - make it suitable to print, and so forth.
nsIThreadEventFilter
last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview boolean acceptevent(in nsirunnable event);violates the xpcom interface guidelines methods violates the xpcom interface guidelines acceptevent() this method is
called to determine whether or not an event may be accepted by a nested event queue.
... (see nsithreadinternal.pusheventqueue()) warning: this method must not make any
calls on the thread object.
nsIThreadManager
if the
calling thread does not already have a nsithread associated with it, one is created and associate with the current prthread.
... ismainthread boolean this attribute is true if the
calling thread is the main thread of the application process.
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.
...onthreadshuttingdown()
called when a new thread is about to be destroyed by the thread pool.
nsITransport
this means that if the stream has no data and is not closed, then reading from it will block the
calling thread until at least one byte is available or until the stream is closed.
...this means that if the stream is full and is not closed, then writing to it will block the
calling thread until all of the data can be written or until the stream is closed.
nsIURI
path autf8string the path, typi
cally including at least a leading '/' (but may also be empty, depending on the protocol).
... 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.
nsIWebBrowserChrome2
1.0 66 introduced gecko 1.9 inherits from: nsiwebbrowserchrome last changed in gecko 1.9 (firefox 3) method overview void setstatuswithcontext(in unsigned long statustype, in astring statustext, in nsisupports statuscontext); methods setstatuswithcontext()
called when the status text in the chrome needs to be updated.
... this method may be
called instead of nsiwebbrowserchrome.setstatus().
nsIWebProgress
void addprogresslistener( in nsiwebprogresslistener alistener, in unsigned long anotifymask ); parameters alistener the listener interface to be
called when a progress event occurs.
...void removeprogresslistener( in nsiwebprogresslistener alistener ); parameters alistener the listener interface previously registered with a
call to addprogresslistener().
nsIWifiListener
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) method overview void onchange([array, size_is(alen)] in nsiwifiaccesspoint accesspoints, in unsigned long alen); void onerror(in long error); methods onchange()
called when the list of available access points changes.
... onerror()
called when an error occurs while updating the wifi access point list.
nsIWindowCreator
embedding/base/nsiwindowcreator.idlscriptable a
callback interface used by gecko to create new browser windows.
...gecko will/may
call this method, if made available to it, to create new windows.
nsIXULBrowserWindow
xpfe/appshell/public/nsixulbrowserwindow.idlscriptable provides methods that may be
called from the internals of the browser area to tell the containing xul window to update its user interface.
...method overview astring onbeforelinktraversal(in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); void setjsdefaultstatus(in astring status); void setjsstatus(in astring status); void setoverlink(in astring link, in nsidomelement element); methods onbeforelinktraversal()
called before traversing a link to determine the appropriate target into which to load the link.
nsIXULBuilderListener
inherits from: nsisupports last changed in gecko 1.7 method overview void didrebuild(in nsixultemplatebuilder abuilder); void willrebuild(in nsixultemplatebuilder abuilder); methods didrebuild()
called after a template builder has rebuilt its content.
... willrebuild()
called before a template builder rebuilds its content.
nsIXULRuntime
processid unsigned long the system process id of the
caller's process.
... processtype unsigned long the type of the
caller's process.
NS_CStringGetData
« xpcom api reference summary the ns_cstringgetdata function gives the
caller read access to the string's internal buffer.
...it may be null if the
caller is not interested in this information.
NS_CStringGetMutableData
« xpcom api reference summary the ns_cstringgetmutabledata function gives the
caller write access to the string's internal buffer.
...the
caller is not responsible for writing a null-terminator.
XPCOM string functions
this is a low-level api.ns_cstringgetdatathe ns_cstringgetdata function gives the
caller read access to the string's internal buffer.ns_cstringgetmutabledatathe ns_cstringgetmutabledata function gives the
caller write access to the string's internal buffer.ns_cstringinsertdatathe ns_cstringinsertdata function appends data to the existing value of a nsacstring instance.
...this is a low-level api.ns_stringgetdatathe ns_stringgetdata function gives the
caller access to the string's internal buffer.
nsIAbCard/Thunderbird3
these functions are marked <code>[noscript] since xpcconnect performs automatic type conversion on nsivariant such that they are not needed for scripts, only for c++
callers.
...in particular,
calling equals on cards from different address books may return inaccurate results.
XPCOM reference
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.
...for example to mark a message read, you would
call:nsmsgviewflagstypethe nsmsgviewflagstype interface contains constants used for view flags in thunderbird.
Using nsIClassInfo
if you use a c++ class which implements nsiclassinfo from javascript, then you don't have to explicitly
call queryinterface on the javascript object to access the object's interfaces.
... if you're writing javascript code which uses a c++ class implementing nsiclassinfo, you don't need to do anything to activate the auto-interface magic which makes
calling queryinterface unnecessary.
XPCOM ABI
often, compiled xpcom components are
called 'binary' or 'native'.
...represents the compiler abi and may be either: msvc - microsoft visual c++ n32 - irix 6 c++ compiler gcc2 - gnu c++ compiler 2.x gcc3 - gnu c++ compiler 3.x or 4.x sunc - sun c++ compiler ibmc - ibm c++ compiler for example: firefox built with the gnu c++ compiler 4.0.0 for the intel pentium processor would have xpcom abi of x86-gcc3 the xpcom abi string can be retrieved programmati
cally by using the nsixulruntime interface.
XPCOM tasks
its role is to extend them with facilities tailored to xpcom development in general, and specifi
cally the needs of mozilla.
...it could avoid implementing its own file format and io; and in many cases, possibly avoid
calling into components for registration.
Testing Mozilla code
the first part will focus on the modern and robust way of static-analysis and the second part will present the build-time static-analysis.debugging mozilla with valgrindthis page describes how to use valgrind (specifi
cally, its memcheck tool) to find memory errors.firefox and address sanitizeraddress sanitizer (asan) is a fast memory error detector that detects use-after-free and out-of-bound bugs in c/c++ programs.
...in addition, the runtime part replaces the malloc and free functions to check dynami
cally allocated memory.
Account Provisioner
to have logs dumped to the terminal, create a string preference
called mail.provider.logging.dump and set its value to all.
... to have logs dumped to the error console, create a string preference
called mail.provider.logging.console and set its value to all.
Adding items to the Folder Pane
the following code snippet listens for that event: let gnumbersext = { load: function gne_load() { window.removeeventlistener("load", gnumbersext.load, false); let tree = document.getelementbyid("foldertree"); tree.addeventlistener("maprebuild", gnumbersext._insert, false); }, _insert: function gne__insert() { // this function is
called when a rebuild occurs } }; window.addeventlistener("load", gnumbersext.load, true); the structure of folder-tree-items the folder pane stores its current display data in a property
called _rowmap.
...must persist over sessions text (attribute) the text to display in the tree level (attribute) the level in the tree to display the item at open (rw, attribute) whether or not this container is open children (attribute) an array of child items also conforming to this spec getproperties (function) a
call from getrowproperties or getcellproperties for this item will be passed into this function command (function) this function will be
called when the item is double-clicked for our example extension, two different types of folder-tree-items will be defined.
Demo Addon
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 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 items = acollection.items; let data = { messages: [], }; for (let i in items) { data.messages.push({ subject: items[i].subject, date: items[i].date, author: items[i].from.value, }); // ...
Using the Mozilla source server
now, when you click on a frame in the "
calls" window, windbg will prompt you about running cvs to download the associated source code.
... if you click "yes", windbg will display *busy* in the status bar while it downloads the source, and then it will automati
cally open the file and highlight the current line.
Using the Mozilla symbol server
the debugger will not be able to show you the content of all variables and the execution path can seem strange because of inlining, tail
calls, and other compiler optimizations.
... 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 automati
cally fetch symbols.
XPI
xpi modules (so
called "bundles") are employed to install a wide variety of software, including plugins, extensions, themes, and thunderbird dictionaries.
...when downloaded or dropped into an extension manager, xpinstall automati
cally interacts with the installation instructions contained in the xpi, and installs the contained software.
Using C struct and pointers
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.
... using c strings with js-ctypes a pointer to char in javascript is declared as follows: var str = ctypes.pointertype(ctypes.char); now imagine you
call a c function that returns a c string and you want to modify the contents of this string.
ctypes.open
this must be
called before any work can commence.
...a native file for use on unix systems is an so file, which is created and a c function
called add() is written.
ArrayType
this is the result of
calling ctypes.pointertype(the_type).
... arraytype cdata method_overview cdata addressofelement(idx) methods inherited from cdata cdata address() string tosource() string tostring() arraytype cdata methods addressofelement() returns a new cdata object of the appropriate pointer type, whose value points to the specified array element on which the method was
called.
Library
you need to
call this once you're done using the library.
... cdata declare( name[, abi, returntype argtype1, ...] ); parameters name the name of the symbol exported by the native library that is to be declared as usable from javascript abi the abi used by the exported function; this will be ctypes.default_abi for most libraries, except for windows libraries, which will be ctypes.winapi_abi or ctypes.std
call_abi.
Debug eval sources - Firefox Developer Tools
you can debug javascript code that is evaluated dynami
cally, either as a string passed to eval() or as a string passed to the function constructor.
... in the video below, we load a page containing a source like this: var script = `function foo() { console.log('
called foo'); } //# sourceurl=my-foo.js`; eval(script); var button = document.getelementbyid("foo"); button.addeventlistener("click", foo, false); the evaluated string is given the name "my-foo.js" using the //# sourceurl directive.
Performance Analysis - Firefox Developer Tools
it displays the results for each run side by side, or verti
cally if the browser window is narrow: the results for each run are summarised in a table and a pie chart.
... clicking on a slice of the pie takes you to the network monitor for that run, with a filter automati
cally applied to see only that resource type.
Edit fonts - Firefox Developer Tools
note: if you want to use a different unit such as pt for font-size or line-height, you can set the property value applied to the currently inspected element to use that unit via the rules view, and the font editor will automati
cally pick it up and make it available in the associated units dropdown menu.
...this is very useful for quickly finding out what axes are available in a particular font — they can vary quite dramati
cally as font designers can implement basi
cally anything they like.
Animating CSS properties - Firefox Developer Tools
this operation is labeled "layout" but is also sometimes
called "reflow".
...one last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process
called "composition".
Performance - Firefox Developer Tools
you get four sub-tools to examine aspects of the profile in more detail: the waterfall shows the different operations the browser was performing, such as executing layout, javascript, repaints, and garbage collection the
call tree shows the javascript functions in which the browser spent most of its time the flame chart shows the javascript
call stack over the course of the recording the allocations view shows the heap allocations made by your code over the course of the recording.
...
call tree find bottlenecks in your site's javascript.
Debugging Firefox Desktop - Firefox Developer Tools
in this guide, the instance of firefox being debugged is
called the debuggee, and the instance of firefox doing the debugging is
called the debugger.
...to use a different port, pass the desired port number: /path/to/firefox --start-debugger-server 1234 note: in windows, the start-debugger-server
call will only have one dash: firefox.exe -start-debugger-server 1234 note: by default, and for security reasons, the devtools.debugger.force-local option is set.
Console messages - Firefox Developer Tools
for example, code like this will cause an immediate, synchronous, reflow, when it
calls window.getcomputedstyle(thing).height: var thing = document.getelementbyid("the-thing"); thing.style.display = "inline-block"; var thingheight = window.getcomputedstyle(thing).height; because of this, it's a good idea to avoid interleaving write and read
calls to an element's styles when manipulating the dom, because every time you read back a style that has been invalidated by a previous writ...
...e
call, you force a synchronous reflow.
about:debugging - Firefox Developer Tools
if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automati
cally, and you'll see them the next time the content script is loaded or the popup is shown.
...however, you can also debug push notifications lo
cally, without needing the server.
ANGLE_instanced_arrays - Web APIs
ext.drawarraysinstancedangle() behaves identi
cally to gl.drawarrays() except that multiple instances of the range of elements are executed, and the instance advances for each iteration.
... ext.drawelementsinstancedangle() behaves identi
cally to gl.drawelements() except that multiple instances of the set of elements are executed and the instance advances between each set.
AbortController.AbortController() - Web APIs
this associates the signal and controller with the fetch request and allows us to abort it by
calling abortcontroller.abort(), as seen below in the second event listener.
... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is
called, the fetch() promise rejects with an aborterror.
AbortController.abort() - Web APIs
this associates the signal and controller with the fetch request and allows us to abort it by
calling abortcontroller.abort(), as seen below in the second event listener.
... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is
called, the fetch() promise rejects with an aborterror.
AbortController.signal - Web APIs
this associates the signal and controller with the fetch request and allows us to abort it by
calling abortcontroller.abort(), as seen below in the second event listener.
... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is
called, the fetch() promise rejects with an aborterror.
AbortController - Web APIs
this associates the signal and controller with the fetch request and allows us to abort it by
calling abortcontroller.abort(), as seen below in the second event listener.
... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is
called, the fetch() promise rejects with a domexception named aborterror.
AbortSignal - Web APIs
this associates the signal and controller with the fetch request and allows us to abort it by
calling abortcontroller.abort(), as seen below in the second event listener.
... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is
called, the fetch() promise rejects with an aborterror.
AesCtrParams - Web APIs
this extra block is
called the "counter block".
... typi
cally this is achieved by splitting the initial counter block value into two concatenated parts: a nonce (that is, a number that may only be used once).
AesGcmParams - Web APIs
the aes-gcm specification recommends that the iv should be 96 bits long, and typi
cally contains bits from a random number generator.
...if additionaldata is given here then the same data must be given in the corresponding
call to decrypt(): if the data given to the decrypt()
call does not match the original data, the decryption will throw an exception.
AnalyserNode.smoothingTimeConstant - Web APIs
it's basi
cally an average between the current buffer and the last buffer the analysernode processed, and results in a much smoother set of value changes over time.
... if 0 is set, there is no averaging done, whereas a value of 1 means "overlap the previous and current buffer quite a lot while computing the value", which essentially smoothes the changes across analysernode.getfloatfrequencydata/analysernode.getbytefrequencydata
calls.
Animation.finish() - Web APIs
that is, if the animation is playing forward, it sets the playback time to the length of the animation sequence, and if the animation is playing in reverse (having had its reverse() method
called), it sets the playback time to 0.
... interfaceelement.addeventlistener("mousedown", function() { try { player.finish(); } catch(e if e instanceof invalidstate) { console.log("finish()
called on paused or finished animation."); } catch(e); logmyerrors(e); //pass exception object to error handler } }); the following example finishes all the animations on a single element, regardless of their direction of playback.
Animation.onfinish - Web APIs
the finish event occurs when the animation completes naturally, as well as when the animation.finish() method is
called to immediately cause the animation to finish up.
... syntax var finishhandler = animation.onfinish; animation.onfinish = finishhandler; value a function to be
called to handle the finish event, or null if no finish event handler is set.
Animation.onremove - Web APIs
syntax var removehandler = animation.onremove; animation.onremove = removehandler; value a function to be
called to handle the remove event, or null if no remove event handler is set.
...for this reason, modern browsers automati
cally remove overriding forward filling animations.
Animation.play() - Web APIs
if the animation is finished,
calling play() restarts the animation, playing it from the beginning.
... nommingcake.play(); } // when a user holds their mouse down or taps,
call growalice to make all the animations play.
AudioContext.resume() - Web APIs
this method will cause an invalid_state_err exception to be thrown if
called on an offlineaudiocontext.
... example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is
called; if it is suspended, resume() is
called.
AudioContext.suspend() - Web APIs
this method will cause an invalid_state_err exception to be thrown if
called on an offlineaudiocontext.
... example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is
called; if it is suspended, resume() is
called.
AudioListener.speedOfSound - Web APIs
the speedofsound property's default value is 343.3 m/s and is used to calculate the doppler shift appropriate for the speed the panner is travelling at (as defined by pannernode.setvelocity.) note: bear in mind that no propagation delay is automati
cally applied to a sound far from the listener.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioNode.disconnect() - Web APIs
the disconnect() method of the audionode interface lets you disconnect one or more nodes from the node on which the method is
called.
... invalidaccesserror the node on which disconnect() was
called isn't connected to the specified destination node.
AudioScheduledSourceNode.onended - Web APIs
the ended event is only sent to a node configured to loop automati
cally when the node is stopped using its stop() method.
... syntax audioscheduledsourcenode.onended = eventhandler; value a function which is
called by the browser when the ended event occurs on the audioscheduledsourcenode.
AudioScheduledSourceNode.stop() - Web APIs
each time you
call stop() on the same node, the specified time replaces any previously-scheduled stop time that hasn't occurred yet.
... return value undefined exceptions invalidstatenode the node has not been started by
calling start().
AudioScheduledSourceNode - Web APIs
specifi
cally, this interface defines the start() and stop() methods, as well as the onended event handler.
... unless stated otherwise, nodes based upon audioscheduledsourcenode output silence when not playing (that is, before start() is
called and after stop() is
called).
AudioWorkletGlobalScope.registerProcessor - Web APIs
typeerror the processorctor is not a
callable constructor, or the parameterdescriptors property of the constructor exists and doesn't return an array of audioparamdescriptor-based objects.
... // test-processor.js class testprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { return true } } registerprocessor('test-processor', testprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode — passing it the processor name that we used when
calling registerprocessor — and connect it to an audio graph.
AudioWorkletNodeOptions - Web APIs
it is only used when
calling the audioworkletnode() constructor.
...this has the effect of changing the output channel count to dynami
cally change to the computed number of channels, based on the input's channel count and the current setting of the audionode property channelcountmode.
AuthenticatorAssertionResponse.authenticatorData - Web APIs
the bits are as follows, where "bit 0" is the least significant bit and all bits not specifi
cally mentioned below are "reserved for future use": bit 0, user presence (up) - if set, authenticator validated that the user was present through some test of user presence (tup), such as touching a button on the authenticator.
...this is only present during a navigator.credentials.create()
call.
AuthenticatorAttestationResponse.getTransports() - Web APIs
note: an authenticatorattestationresponse instance is available on publickeycredential.response after
calling navigator.credentials.create().
...their values may be : "usb": the authenticator can be contacted via a removable usb link "nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifi
cally bound to the client device (cannot be removed).
BaseAudioContext.createBuffer() - Web APIs
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 automati
cally *resampled* to 44100hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames / 44100hz = 1 second.
BaseAudioContext.createScriptProcessor() - Web APIs
this value controls how frequently the audioprocess event is dispatched and how many sample-frames need to be processed each
call.
... important: webkit currently (version 31) requires that a valid buffersize be passed when
calling this method.
BaseAudioContext - Web APIs
this occurs when the audiocontext's state changes, due to the
calling of one of the state change methods (audiocontext.suspend, audiocontext.resume, or audiocontext.close).
...it basi
cally generates a tone.
Blob.slice() - Web APIs
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.
... return value a new blob object containing the specified subset of the data contained within the blob on which this method was
called.
Blob - Web APIs
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.
...it then
calls url.createobjecturl() to convert the blob into a url.
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.
...a function can be run for this event with the onmessage event handler: // a handler that only logs the event to the console: bc.onmessage = function (ev) { console.log(ev); } disconnecting a channel to leave a channel,
call the close() method on the object.
CSSPseudoElement - Web APIs
instances of this interface may be obtained by
calling element.pseudo().
... examples basic example using element.pseudo using pseudo-elements, most modern browsers will automati
cally add quotation marks around text inside a <q> element.
Managing screen orientation - Web APIs
by using a media query, you can do this easily and automati
cally.
... some devices (mainly mobile devices) can dynami
cally change the orientation of the screen based on their own orientation, ensuring that the user will always be able to read what's on the screen.
Cache.add() - Web APIs
the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then
calls waituntil() to handle the install process for the app.
... this consists of
calling cachestorage.open to create a new cache, then using cache.add to add an asset to it.
CanvasCaptureMediaStreamTrack - Web APIs
the canvascapturemediastreamtrack interface represents the video track contained in a mediastream being generated from a <canvas> following a
call to htmlcanvaselement.capturestream().
...this lets applications that wish to specify the frame capture times directly do so, if they specified a framerate of 0 when
calling capturestream().
CanvasRenderingContext2D.beginPath() - Web APIs
call this method when you want to create a new path.
... html <canvas id="canvas"></canvas> javascript the beginpath() method is
called before beginning each line, so that they may be drawn with different colors.
CanvasRenderingContext2D.closePath() - Web APIs
after that, the triangle's base is created with the closepath() method, which automati
cally connects the shape's first and last points.
... note: although closepath() is
called after all the arcs have been created, only the last arc (sub-path) gets closed.
CanvasRenderingContext2D.setTransform() - Web APIs
the newer type consists of a single parameter, matrix, representing a 2d transformation matrix to set (techni
cally, a dommatrixinit object; any object will do as long as it contains the above components as properties).
... examples skewing a shape this example skews a rectangle both verti
cally (.2) and horizontally (.8).
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 typi
cally, you'll want to
call beginpath() for each new thing you want to stroke.
... if you don't, the previous sub-paths will remain part of the current path, and get stroked every time you
call the stroke() method.
CanvasRenderingContext2D.strokeText() - Web APIs
this method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke()
calls will have no effect on it.
... with that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then
call stroketext() to draw the text "hello world," starting at the coordinates (50, 90).
CanvasRenderingContext2D.translate() - Web APIs
syntax void ctx.translate(x, y); the translate() method adds a translation transformation to the current matrix by moving the canvas and its origin x units horizontally and y units verti
cally on the grid.
... html <canvas id="canvas"></canvas> javascript the translate() method translates the context by 110 horizontally and 30 verti
cally.
Compositing and clipping - Web APIs
in the chapter about drawing shapes i only mentioned the stroke() and fill() methods, but there's a third method we can use with paths,
called clip().
...next, we create the circular clipping path by drawing an arc and
calling clip().
Optimizing canvas - Web APIs
to avoid this, make sure to round all co-ordinates used in
calls to drawimage() using math.floor(), for example.
... var ctx = canvas.getcontext('2d', { alpha: false }); more tips batch canvas
calls together.
Using channel messaging - Web APIs
this saves the transferred port and register an onmessage handler that will be
called each time a message is passed through our messagechannel.
... next, we post a confirmation message back to the main page via the message channel by
calling messageport.postmessage on messagechannel.port2 that was initially transferred to the iframe.
Clipboard.write() - Web APIs
the "clipboard-write" permission of the permissions api, is granted automati
cally to pages when they are in the active tab.
...then write() is
called, specifying both a fulfilment function and an error function.
Clipboard.writeText() - Web APIs
the "clipboard-write" permission of the permissions api, is granted automati
cally to pages when they are in the active tab.
...the promise is rejected if the
caller does not have permission to write to the clipboard.
Clipboard - Web APIs
calls to the methods of the clipboard object will not succeed if the user hasn't granted the needed permissions using the permissions api and the "clipboard-read" or "clipboard-write" permission as appropriate.
... the clipboard is a data buffer that is used for short-term, data storage and/or data transfers, this can be between documents or applications it is usually implemented as an anonymous, temporary data buffer, sometimes
called the paste buffer, that can be accessed from most or all programs within the environment via defined programming interfaces.
console.log() - Web APIs
please be warned that if you log objects in the latest versions of chrome and firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you
call console.log(), but it is the value of the object at the moment you open the console.
... notice: console.log prints the element in an html-like tree console.dir prints the element in a json-like tree specifi
cally, console.log gives special treatment to dom elements, whereas console.dir does not.
Console.profileEnd() - Web APIs
calling this api immediately after console.profile() can cause it to not work.
... to work around this,
call it in a settimeout with at least 5ms delay.
Console.time() - Web APIs
when you
call console.timeend() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.
...this will identify the timer; use the same name when
calling console.timeend() to stop the timer and get the time output to the console.
Console.timeLog() - Web APIs
logs the current value of a timer that was previously started by
calling console.time() to the console.
...in addition, the
call to timeend() has the additional information, "timer ended" to make it obvious that the timer is no longer tracking time.
Credential Management API - Web APIs
calls to get() and store() within an <iframe> element will resolve without effect.
...to take advantage of this, a password must be explicitly stored by
calling credentialscontainer.store().
CredentialsContainer - Web APIs
for example, you might
call this, after a user signs out of a website to ensure that he/she isn't automati
cally signed in on the next site visit.
... earlier versions of the spec
called this method requireusermediation().
Crypto - Web APIs
it allows access to a cryptographi
cally strong random number generator and to cryptographic primitives.
... crypto.getrandomvalues() fills the passed typedarray with cryptographi
cally sound random values.
CustomElementRegistry.define() - Web APIs
// create a class for the element class popupinfo extends htmlelement { constructor() { // always
call super first in constructor super(); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create spans var wrapper = document.createelement('span'); wrapper.setattribute('class','wrapper'); var icon = document.createelement('span'); icon.setattribute('class','icon'); icon.setattribute('tabindex', 0); var info = document.createelement(...
... // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always
call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent return text.split(/\s+/g).length; } var count = 'words: ' + countwords(wcparent); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // creat...
DOMPoint.DOMPoint() - Web APIs
you can also create a dompoint by
calling the dompoint.frompoint() static function.
... examples this example creates a dompoint representing the top-left corner of the current window, then creates a second point based on the first, which is then offset by 100 pixels both verti
cally and horizontally.
DOMPoint - Web APIs
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.
...in the following snippet, the pose of the xr device (such as a vr headset or phone with ar capabilities) can be retrieved by
calling using xrframe.getviewerpose() during an xrsession animation frame, then accessing the resulting xrpose's transform property, which contains two dompointreadonly attributes: position as a vector and orientation as a quaternion.
DOMTokenList - Web APIs
domtokenlist.foreach(
callback [, thisarg]) executes a provided
callback function once per domtokenlist element.
... first, the html: <p class="a b c"></p> now the javascript: let para = document.queryselector("p"); let classes = para.classlist; para.classlist.add("d"); para.textcontent = `paragraph classlist is "${classes}"`; the output looks like this: trimming of whitespace and removal of duplicates methods that modify the domtokenlist (such as domtokenlist.add()) automati
cally trim any excess whitespace and remove duplicate values from the list.
DataTransfer.dropEffect - Web APIs
the datatransfer.dropeffect property controls the feedback (typi
cally visual) the user is given during a drag and drop operation.
...how this is determined is platform specific, but typi
cally the user can press modifier keys such as the alt key to adjust the desired action.
DataTransfer - Web APIs
this value is null for external drags or if the
caller can't access the node.
...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.
DataTransferItem - Web APIs
datatransferitem.type read only the drag data item's type, typi
cally a mime type.
... datatransferitem.getasstring() invokes the specified
callback with the drag data item string as its argument.
DedicatedWorkerGlobalScope.onmessage - Web APIs
the onmessage property of the dedicatedworkerglobalscope interface represents an eventhandler to be
called when the message event occurs and bubbles through the worker — i.e.
...} in the worker.js script, a dedicatedworkerglobalscope.onmessage handler is used to handle messages from the main script: onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); console.log('posting message back to main script'); postmessage(workerresult); } notice how in the main script, onmessage has to be
called on myworker, whereas inside the worker script you just need onmessage because the worker is effectively the global scope (the dedicatedworkerglobalscope, in this case).
Detecting device orientation - Web APIs
in particular, hand-held devices such as mobile phones can use this information to automati
cally rotate the display to remain upright, presenting a wide-screen view of the web content when the device is rotated so that its width is greater than its height.
... window.addeventlistener("deviceorientation", handleorientation, true); after registering your event listener (in this case, a javascript function
called handleorientation()), your listener function periodi
cally gets
called with updated orientation data.
Document.createExpression() - Web APIs
firefox 3 note prior to firefox 3, you could
call this method on documents other than the one you planned to run the xpath against.
... under firefox 3, you must
call it on the same document.
Document.createTreeWalker() - Web APIs
typi
cally this will be an element owned by the document.
... filter optional a nodefilter, that is an object with a method acceptnode, which is
called by the treewalker to determine whether or not to accept a node that has passed the whattoshow check.
Document.execCommand() - Web APIs
don't try using the return value to verify browser support before
calling a command.
... note: this argument is logi
cally backwards (i.e.
Document.exitFullscreen() - Web APIs
this usually reverses the effects of a previous
call to element.requestfullscreen().
...if an error occurs while attempting to exit full-screen mode, the catch() handler for the promise is
called.
Document.getElementsByTagName() - Web APIs
the returned htmlcollection is live, meaning that it updates itself automati
cally to stay in sync with the dom tree without having to
call document.getelementsbytagname() again.
... <p>some div2 text</p> </div> </div> <p>some outer text</p> <p>some outer text</p> <button onclick="getallparaelems();"> show all p elements in document</button><br /> <button onclick="div1paraelems();"> show all p elements in div1 element</button><br /> <button onclick="div2paraelems();"> show all p elements in div2 element</button> </body> </html> notes when
called on an html document, getelementsbytagname() lower-cases its argument before proceeding.
Document.hasStorageAccess() - Web APIs
if the promise gets resolved and a user gesture event was being processed when the function was originally
called, the resolve handler will run as if a user gesture was being processed, so it will be able to
call apis that require user activation.
... } else { // storage access hasn't been granted already; // you may want to
call requeststorageaccess().
Document.onafterscriptexecute - Web APIs
it does not fire if the element is added dynami
cally, such as with appendchild().
... syntax document.onafterscriptexecute = funcref; funcref is a function reference,
called when the event is fired.
Document.onbeforescriptexecute - Web APIs
does not fire if the element is added dynami
cally, eg with appendchild().
... syntax document.onbeforescriptexecute = funcref; funcref is a function reference,
called when the event is fired.
Document.popupNode - Web APIs
typi
cally, this property will be checked during a popupshowing event handler for a context menu to initialize the menu based on the context.
...in these other cases, for example when
calling the popup's showpopup method, you may wish to set the popupnode property directly beforehand.
Document.queryCommandEnabled() - Web APIs
notes for 'cut' and 'copy' commands the method only returns true when
called from a user-initiated thread.
... the 'paste' command return false not only if the feature is unavailable, but also if the script
calling it has insufficient privileges to perform the action.
Document.timeline - Web APIs
this timeline is a special instance of documenttimeline that is automati
cally created on page load.
... this timeline is unique to each document and persists for the lifetime of the document including
calls to document.open().
DocumentOrShadowRoot.activeElement - Web APIs
typi
cally a user can press the tab key to move the focus around the page among focusable elements, and use the space bar to activate one (that is, to press a button or toggle a radio button).
...for example, on macos systems, elements that aren't text input elements are not typi
cally focusable by default.
Examples of web and XML development using the DOM - Web APIs
however, stopevent also
calls an event object method, event.stoppropagation, which keeps the event from bubbling any further up into the dom.
...you might also like to add some elements in the page and
call this function from different event handlers.
How to create a DOM tree - Web APIs
dynami
cally creating a dom tree consider the following xml document: <?xml version="1.0"?> <people> <person first-name="eric" middle-initial="h" last-name="jung"> <address street="321 south st" city="denver" state="co" country="usa"/> <address street="123 main st" city="arlington" state="ma" country="usa"/> </person> <person first-name="jed" last-name="brown"> <address street="321 north st" city="atlanta" state="ga" country="usa"/> <address street="123 west st" city="seattle" state="wa" country="usa"/> <address street="321 south avenue" city...
...another application is that, since xul is xml, the ui of your application can be dynami
cally manipulated, downloaded, uploaded, saved, loaded, converted, or transformed quite easily.
Introduction to the DOM - Web APIs
the following very simple web page provides a <script> element in the header in which you can place functions that test the interface, a few html elements with attributes that you can retrieve, set, or otherwise manipulate, and the web user interface necessary to
call those functions from the browser.
... figure 0.1 sample dom test page in this example, the drop-down menus dynami
cally update such dom—accessible aspects of the web page as its background color (bgcolor), the color of the hyperlinks (alink), and color of the text (text).
EXT_texture_filter_anisotropic - Web APIs
constants ext.max_texture_max_anisotropy_ext this is the pname argument to the gl.getparameter()
call, and it returns the maximum available anisotropy.
... ext.texture_max_anisotropy_ext this is the pname argument to the gl.gettexparameter() and gl.texparameterf() / gl.texparameteri()
calls and sets the desired maximum anisotropy for a texture.
Element.animate() - Web APIs
you can get a list of the animations that affect an element by
calling element.getanimations().
...although this is techni
cally optional, keep in mind that your animation will not run if this value is 0.
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.
..., ${random(255)})`; } button.onclick = function() { button.style.backgroundcolor = randomcolor(); }; button.onauxclick = function(e) { e.preventdefault(); button.style.color = randomcolor(); } button.oncontextmenu = function(e) { e.preventdefault(); } notice that in addition to capturing the auxclick event using onauxclick, the contextmenu event is also captured, and preventdefault()
called on that event, in order to prevent the context menu from popping up after the color change is applied.
Element.classList - Web APIs
ele.attachevent( "onpropertychange", whenpropchanges ); } try { // much faster & cleaner version for ie8 & ie9: // should work in ie8 because element.prototype instanceof node is true according to the specs window.object.defineproperty(window.element.prototype, "classlist", { enumerable: 1, get: function(val){ if (!hasownprop.
call(this, "classlist")) polyfillclasslist(this); return this.classlist; }, configurable: 0, set: function(val){this.classname = val} }); } catch(e) { // less performant fallback for older browsers (ie 6-8): window[" ucl"] = polyfillclasslist; // the below code ensures polyfillclasslist is applied to ...
...unction(value){ for (var i=0,len=this.length; i !== len; ++i) if (this[i] === value) return true; return false; }; if (!domtokenlistproto.foreach) domtokenlistproto.foreach = function(f){ if (arguments.length === 1) for (var i = 0, len = this.length; i !== len; ++i) f( this[i], i, this); else for (var i=0,len=this.length,targ=arguments[1]; i !== len; ++i) f.
call(targ, this[i], i, this); }; if (!domtokenlistproto.entries) domtokenlistproto.entries = function(){ var nextindex = 0, that = this; return {next: function() { return nextindex<that.length ?
Element: contextmenu event - Web APIs
this event is typi
cally triggered by clicking the right mouse button, or by pressing the context menu key.
... any right-click event that is not disabled (by
calling the event's preventdefault() method) will result in a contextmenu event being fired at the targeted element.
Element.getAttributeNS() - Web APIs
note: earlier versions of the dom specification had this method described as returning an empty string for non-existent attributes, but it was not typi
cally implemented this way since null makes more sense.
...for that reason, you should use hasattributens() to check for an attribute's existence prior to
calling getattributens() if it is possible that the requested attribute does not exist on the specified element.
Element.getClientRects() - Web APIs
when
called on svg elements other than an outer-<svg>, the "viewport" that the resulting rectangles are relative to is the viewport that the element's outer-<svg> establishes (and to be clear, the rectangles are also transformed by the outer-<svg>'s viewbox transform, if any).
... tablerectdiv.style.width = (rect.width - 2) + 'px'; tablerectdiv.style.height = (rect.height - 2) + 'px'; document.body.appendchild(tablerectdiv); } } (function() { /*
call function addclientrectsoverlay(elt) for all elements with assigned class "withclientrectsoverlay" */ var elt = document.getelementsbyclassname('withclientrectsoverlay'); for (var i = 0; i < elt.length; i++) { addclientrectsoverlay(elt[i]); } })(); result specifications specification status comment css object model (cssom) view modulethe definition o...
Element.msZoomTo() - Web APIs
if no value is specified, defaults to the current centerpoint of visible content, verti
cally.
... this method has no effect if
called from a parent document to scroll or zoom content hosted in an iframe.
Element.onfullscreenchange - Web APIs
this function determines which element it was
called on by checking the value of event.target, then compares the document's fullscreenelement value to the element to see if they're the same node.
... this gives us a value, isfullscreen, which we pass into a function
called adjustmycontrols(), which we imagine to be a function that makes adjustments to the app's user interface to present itself optimally when it's in full-screen mode versus being displayed in a window.
Element.scroll() - Web APIs
syntax element.scroll(x-coord, y-coord) element.scroll(options) parameters
calling with coordinates x-coord the pixel along the horizontal axis of the element that you want displayed in the upper left.
...
calling with options options a scrolltooptions dictionary.
Element.tagName - Web APIs
the tagname read-only property of the element interface returns the tag name of the element on which it's
called.
...for example, tagname
called on a <div> element returns "div".
Element - Web APIs
element.scrolltop a number representing number of pixels the top of the document is scrolled verti
cally.
... wheel fired when the user rotates a wheel button on a pointing device (typi
cally a mouse).
Event.eventPhase - Web APIs
event listeners registered for capture mode when eventtarget.addeventlistener() was
called are triggered during this phase.
...event listeners registered for this phase are
called at this time.
EventListener - Web APIs
eventlistener.handleevent() a function that is
called whenever an event of the specified type occurs.
... example html <button id="btn">click here!</button> javascript const buttonelement = document.getelementbyid('btn'); // add a handler for the 'click' event by providing a
callback function.
EventTarget - Web APIs
void seteventhandler(domstring type, eventhandler handler) eventhandler geteventhandler(domstring type) example simple implementation of eventtarget var eventtarget = function() { this.listeners = {}; }; eventtarget.prototype.listeners = null; eventtarget.prototype.addeventlistener = function(type,
callback) { if (!(type in this.listeners)) { this.listeners[type] = []; } this.listeners[type].push(
callback); }; eventtarget.prototype.removeeventlistener = function(type,
callback) { if (!(type in this.listeners)) { return; } var stack = this.listeners[type]; for (var i = 0, l = stack.length; i < l; i++) { if (stack[i] ===
callback){ stack.splice(i, 1); return;...
... } } }; eventtarget.prototype.dispatchevent = function(event) { if (!(event.type in this.listeners)) { return true; } var stack = this.listeners[event.type].slice(); for (var i = 0, l = stack.length; i < l; i++) { stack[i].
call(this, event); } return !event.defaultprevented; }; specifications specification status comment domthe definition of 'eventtarget' in that specification.
FetchEvent - Web APIs
this constructor is not typi
cally used.
... the browser creates these objects itself and provides them to fetch event
callbacks.
Fetch API - Web APIs
this will allow them to be used wherever they are needed in the future, whether it’s for service workers, cache api, and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your responses programmati
cally (that is, the use of computer program or personal programming instructions).
...it is implemented in multiple interfaces, specifi
cally window and workerglobalscope.
FileReader.result - Web APIs
it works by creating a filereader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the
callback function provided to read().
... 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
abort fired when a read has been aborted, for example because the program
called filereader.abort().
... progress fired periodi
cally as data is read.
FileRequest.onprogress - Web APIs
summary this property specifies a
callback function to be run repeatedly while the operation represented by a filerequest object is in progress.
... each time the function
callback is
called, it gets an object as its first parameter.
FileSystem - Web APIs
basic concepts there are two ways to get access to a filesystem object: you can directly ask for one representing a sandboxed file system created just for your web app directly by
calling window.requestfilesystem().
... if that
call is successful, it executes a
callback handler, which receives as a parameter a filesystem object describing the file system.
FileSystemEntry.getMetadata() - Web APIs
syntax filesystementry.getmetadata(success
callback[, error
callback]); parameters success
callback a function which is
called when the copy operation is succesfully completed.
... error
callback optional an optional
callback which is executed if an error occurs while looking up the metadata.
FileSystemEntry.toURL() - Web APIs
this can be used to help deal with files whose types aren't recognized automati
cally by the user agent.
... example if you have a filesystemfileentry corresponding to an image file in a file system available to your web site or app, you can
call tourl() to get its url for use in html.
Using the Gamepad API - Web APIs
once one gamepad has been interacted with, other gamepads that are connected will automati
cally be visible.
...values are monotoni
cally 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.
Geolocation - Web APIs
the geolocation interface represents an object able to programmati
cally obtain the position of the device.
... geolocation.watchposition() secure context returns a long value representing the newly established
callback function to be invoked whenever the device location changes.
GlobalEventHandlers.onanimationiteration - Web APIs
syntax var animiterationhandler = target.onanimationiteration; target.onanimationiteration = function value a function to be
called when an animationiteration event occurs indicating that a css animation has reached the end of an iteration while running on the target, where the target object is an html element (htmlelement), document (document), or window (window).
... example let's create an animation which automati
cally pauses at the end of each iteration, allowing the user to choose whether or not to start the next iteration.
GlobalEventHandlers.onauxclick - Web APIs
specifi
cally, event behavior is being updated so that click only fires for primary button clicks (e.g., left mouse button), while auxclick fires for non-primary button clicks.
... histori
cally, click has generally fired for the click of any device input button, although with browser behavior being somewhat inconsistent.
HTMLAreaElement - Web APIs
techni
cally, the url-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moving to the htmlhyperlinkelementutils mixin, and htmlareaelement implements this mixin.
... recommendation techni
cally, the properties tabindex and accesskey are now defined on htmlelement.
HTMLCollection - Web APIs
note: this interface is
called htmlcollection for historical reasons (before the modern dom, collections implementing this interface could only have html elements as their items).
... an htmlcollection in the html dom is live; it is automati
cally updated when the underlying document is changed.
HTMLElement.offsetHeight - Web APIs
typi
cally, offsetheight is a measurement in pixels of the element's css height, including any borders, padding, and horizontal scrollbars (if rendered).
...these elements are typi
cally contained within scrollable elements; consequently, these non-scrollable elements may be completely or partly invisible, depending on the scrolltop setting of the scrollable container.
HTMLFormElement.requestSubmit() - Web APIs
notfounderror the specified submitter isn't a member of the form on which requestsubmit() was
called.
... if, on the other hand, requestsubmit() isn't available, this code falls back to
calling the form's submit() method.
HTMLFormElement - Web APIs
htmlformelement.autocomplete a domstring reflecting the value of the form's autocomplete html attribute, indicating whether the controls in this form can have their values automati
cally populated by the browser.
... 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 <form> element and set some of its attributes: <form name="forma" action="/cgi-bin/test" method="post"> <p>press "info" for form details, or "set" to change those details.</p> <p> <button type="button" onclick="getforminfo();">info</button> <button type="button" onclick="setforminfo(this.form);">set</button> <button type="reset">res...
HTMLImageElement.sizes - Web APIs
this provides the ability to automati
cally select among different images—even images of different orientations or aspect ratios—as the document state changes to match different media conditions.
...because a source size descriptor is used to specify the width to use for the image during layout of the page, the media condition is typi
cally (but not necessarily) based entirely on width information.
HTMLInputElement.select() - Web APIs
html <input type="text" id="text-box" size="20" value="hello world!"> <button onclick="selecttext()">select text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.select(); } result notes
calling element.select() will not necessarily focus the input, so it is often used with htmlelement.focus().
... in browsers where it is not supported, it is possible to replace it with a
call to htmlinputelement.setselectionrange() with parameters 0 and the input's value length: <input onclick="this.select();" value="sample text" /> <!-- equivalent to --> <input onclick="this.setselectionrange(0, this.value.length);" value="sample text" /> specifications specification status comment html living standardthe definition of 'select' in that specification.
HTMLInputElement.webkitEntries - Web APIs
this property is
called webkitentries in the specification due to its origins as a google chrome-specific api.
...more specifi
cally, files are represented by filesystemfileentry objects, and, if they're allowed, directories are represented by filesystemdirectoryentry objects.
HTMLMediaElement.load() - Web APIs
usage notes
calling load() aborts all ongoing operations involving this media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s).
... example this example finds a <video> element in the document and resets it by
calling load().
HTMLMediaElement: play event - Web APIs
either the ' + 'play() method was
called or the autoplay attribute was toggled.'); }); using the onplay event handler property: const video = document.queryselector('video'); video.onplay = (event) => { console.log('the boolean paused property is now false.
... either the ' + 'play() method was
called or the autoplay attribute was toggled.'); }; specifications specification status html living standardthe definition of 'play media event' in that specification.
HTMLScriptElement - Web APIs
note: when inserted using the document.write() method, <script> elements execute (typi
cally synchronously), but when inserted using innerhtml or outerhtml, they do not execute at all.
... examples dynami
cally 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).
HTMLSelectElement - Web APIs
you can also access an item by specifying the index in array-style brackets or parentheses, without
calling this method explicitly.
...you can also access an item by specifying the name in array-style brackets or parentheses, without
calling this method explicitly.
HTMLTableElement - Web APIs
the htmlcollection is live and is automati
cally updated when the htmltableelement changes.
...the htmlcollection is live and is automati
cally updated when the htmltableelement changes.
HTMLTableRowElement - Web APIs
the htmlcollection is live and is automati
cally updated when cells are added or removed.
... htmltablerowelement.valign is a domstring representing an enumerated value indicating how the content of the cell must be verti
cally aligned.
HTMLTableSectionElement - Web APIs
the htmlcollection is live and is automati
cally updated when rows are added or removed.
... htmltablesectionelement.valign is a domstring representing an enumerated value indicating how the content of the cell must be verti
cally aligned.
HTMLTextAreaElement - Web APIs
on being set, the control behaves as if setselectionrange() had been
called with this as the second argument, and selectionstart as the first argument.
...on being set, the control behaves as if setselectionrange() had been
called with this as the first argument, and selectionend as the second argument.
File drag and drop - Web APIs
the following code snippet shows how this is done with a <div> element: <div id="drop_zone" ondrop="drophandler(event);"> <p>drag one or more files to this drop zone ...</p> </div> typi
cally, an application will include a dragover event handler on the drop target element and that handler will turn off the browser's default drag behavior.
...file[' + i + '].name = ' + ev.datatransfer.files[i].name); } } } prevent the browser's default drag behavior the following dragover event handler
calls preventdefault() to turn off the browser's default drag and drop handler.
Recommended Drag Types - Web APIs
for example: event.datatransfer.setdata("text/plain", "this is text to drag"); dragging text in textboxes and selections on web pages is done automati
cally by the browser, so you do not need to handle it yourself.
...note that
callers from a different domain will not be able to access the node even when it has been dropped.
History.back() - Web APIs
it has the same effect as
calling history.go(-1).
... if there is no previous page, this method
call does nothing.
History.go() - Web APIs
if no value is passed or if delta equals 0, it has the same result as
calling location.reload().
... examples to move back one page (the equivalent of
calling back()): history.go(-1) to move forward a page, just like
calling forward(): history.go(1) to move forward two pages: history.go(2); to move backwards by two pages: history.go(-2); and, finally either of the following statements will reload the current page: history.go(); history.go(0); specifications specification status comment html living standardthe definition of 'history.go()' in that specification.
History.pushState() - Web APIs
note that the browser won't attempt to load this url after a
call to pushstate(), but it might attempt to load the url later, for instance after the user restarts the browser.
... description in a sense,
calling pushstate() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document.
IDBCursor.update() - Web APIs
be aware that you can't
call update() (or idbcursor.delete()) on cursors obtained from idbindex.openkeycursor().
...note also that you can't directly put cursor.value into an update
call, hence the below example using an intermediary updatedata variable.
IDBCursor - Web APIs
it starts at the lower bound of the key range and moves upwards (monotoni
cally increasing in the order of keys).
...it starts at the upper bound of the key range and moves downwards (monotoni
cally decreasing in the order of keys).
IDBDatabase.transaction() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror the close() method has previously been
called on this idbdatabase instance.
... invalidaccesserror the function was
called with an empty list of store names.
IDBDatabaseException - Web APIs
constant value description abort_err 8 a request was aborted, for example, through a
call to idbtransaction.abort.
... not_allowed_err 6 an operation was
called on an object where it is not allowed or at a time when it is not allowed.
IDBObjectStore.createIndex() - Web APIs
note that this method must be
called only from a versionchange transaction mode
callback.
... invalidstateerror occurs if either: the method was not
called from a versionchange transaction mode
callback, i.e.
IDBObjectStore.deleteIndex() - Web APIs
note that this method must be
called only from a versionchange transaction mode
callback.
... return value undefined exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the method was not
called from a versionchange transaction mode
callback.
IDBTransaction.objectStore() - Web APIs
every
call to this method on the same transaction object, with the same name, returns the same idbobjectstore instance.
... if this method is
called on a different transaction object, a different idbobjectstore instance is returned.
IIRFilterNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "max" channel count same as on the input channel interpretation "speakers" typi
cally, it's best to use the biquadfilternode interface to implement higher-order filters.
... there are several reasons why: biquad filters are typi
cally less sensitive to numeric quirks.
ImageCapture - Web APIs
the track is then used to create an imagecapture object so that takephoto() and grabframe() can be
called.
... finally, it shows how to apply the results of these
calls to a canvas object.
IntersectionObserver.thresholds - Web APIs
regardless of the order your original threshold array was in, this one is always sorted in numeri
cally increasing order.
...although the options object you can specify when creating an intersectionobserver has a field named threshold, this property is
called thresholds.
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.
...the value returned by this property may not be the same as the one specified when
calling the constructor as it may be changed to match internal requirements.
IntersectionObserverEntry.intersectionRatio - Web APIs
example in this simple example, an intersection
callback sets each target element's opacity to the intersection ratio of that element with the root.
... function intersection
callback(entries) { entries.foreach(function(entry) { entry.target.style.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
IntersectionObserverEntry.intersectionRect - Web APIs
example in this simple example, an intersection
callback stores the intersection rectangle for later use by the code that draws the target elements' contents, so that only the visible area is redrawn.
... function intersection
callback(entries) { entries.foreach(function(entry) { refreshzones.push({ element: entry.target, rect: entry.intersectionrect }); }); } specifications specification status comment intersection observerthe definition of 'intersectionobserverentry.intersectionrect' in that specification.
IntersectionObserverEntry.isIntersecting - Web APIs
example in this simple example, an intersection
callback is used to update a counter of how many targeted elements are currently intersecting with the intersection root.
... function intersection
callback(entries) { entries.foreach(function(entry) { if (entry.isintersecting) { intersectingcount += 1; } else { intersectingcount -= 1; } }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
IntersectionObserverEntry.target - Web APIs
syntax var target = intersectionobserverentry.target; value the intersectionobserverentry's target property specifies which element previously targeted by
calling intersectionobserver.observe() experienced a change in intersection with the root.
... function intersection
callback(entries) { entries.foreach(function(entry) { entry.target.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
KeyboardEvent.code - Web APIs
this will use the same four keys physi
cally regardless of what the actual corresponding characters are, such as if the user is using an azerty keyboard.
...tion refresh() { let x = position.x - (shipsize.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 - Web APIs
keyboardevent.repeat read only returns a boolean that is true if the key is being held down such that it is automati
cally repeating.
... auto-repeat on some gtk environments such as ubuntu 9.4 in some gtk-based environments, auto-repeat dispatches a native key-up event automati
cally during auto-repeat, and there's no way for gecko to know the difference between a repeated series of keypresses and an auto-repeat.
LocalMediaStream - Web APIs
the localmediastream interface was part of the media capture and streams api, representing a stream of data being generated lo
cally (such as by getusermedia().
...instead, media is stopped by
calling mediastreamtrack.stop() on each track that needs to be stopped.
Location: assign() - Web APIs
after the navigation occurs, the user can navigate back to the page that
called location.assign() by pressing the "back" button.
...this happens if the origin of the script
calling the method is different from the origin of the page originally described by the location object, mostly when the script is hosted on a different domain.
Lock - Web APIs
the lock interface of the the web locks api provides the name and mode of a previously requested lock, which is received in the
callback to lockmanager.request().
... examples the following examples show how the mode and name properties are passed in the
call to lockmanager.request().
LockedFile.flush() - Web APIs
periodi
cally, the data are written onto disk.
...to avoid that, it's possible to force a write onto the disk by
calling the flush method.
LockedFile.truncate() - Web APIs
if the method is
called with no argument, the operation removes all the bytes starting at the index set in lockedfile.location.
... if the method is
called with an argument, the operation removes all the bytes starting at the index corresponding to the parameter and regardless of the value of lockedfile.location.
MediaDeviceInfo.groupId - Web APIs
then navigator.mediadevices.enumeratedevices() is
called to get the list of all media devices.
... finally, the list, which now contains a mediadeviceinfo object for each device in the same group, is returned to the
caller.
MediaDeviceInfo - Web APIs
the list of devices obtained by
calling navigator.mediadevices.enumeratedevices() is an array of mediadeviceinfo objects, one per media device.
...it is un-guessable by other applications and unique to the origin of the
calling application.
MediaKeySession - Web APIs
event handlers mediakeysession.onkeystatuseschange sets the eventhandler
called when there has been a change in the keys in a session or their statuses.
... mediakeysession.onmessage sets the eventhandler
called when the content decryption module has generated a message for the session.
MediaKeyStatusMap - Web APIs
mediakeystatusmap.foreach(
callback[, argument]) read only
calls
callback once for each key-value pair in the status map, in insertion order.
... if argument is present it will be passed to the
callback.
MediaPositionState.duration - Web APIs
the mediapositionstate dictionary's duration property is used when
calling the mediasession method setpositionstate() to provide the user agent with the overall total duration in seconds of the media currently being performed.
... example in this example, an app performing a live stream provides information to the browser by preparing a mediapositionstate object and submitting it by
calling navigator.mediasession.setpositionstate().
MediaPositionState.playbackRate - Web APIs
the mediapositionstate dictionary's playbackrate property is used when
calling the mediasession method setpositionstate() to tell the user agent the rate at which media is currently being played.
...it begins by creating a mediapositionstate object, then submits it to the browser it by
calling navigator.mediasession.setpositionstate().
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.pause() - Web APIs
when a mediarecorder object’s pause()method is
called, the browser queues a task that runs the below steps: if mediarecorder.state is "inactive", raise a dom invalidstate error and terminate these steps.
...if you
call pause() while already paused, it silently does nothing.
MediaRecorder.requestData() - Web APIs
the mediarecorder.requestdata() method (part of the mediarecorder api) is used to raise a dataavailable event containing a blob object of the captured media as it was when the method was
called.
... syntax mediarecorder.requestdata() errors an invalidstate error is raised if the requestdata() method is
called while the mediarecorder object’s mediarecorder.state is not "recording" — the media cannot be captured if recording is not occurring.
MediaRecorder.start() - Web APIs
you can record the entire duration of the media into a single blob (or until you
call requestdata()), or you can specify the number of milliseconds to record at a time.
...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.
MediaSessionActionDetails.action - Web APIs
the action property is the only required property mediasessionactiondetails dictionary, specifying the type of media session action which the action handler
callback is being executed for.
... syntax let mediasessionactiondetails = { action: actiontype }; let actiontype = mediasessionactiondetails.action; value a domstring specifying which of the action types the
callback is being invoked for: nexttrack advances playback to the next track.
MediaStream.clone() - Web APIs
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.onaddtrack - Web APIs
the mediastream.onaddtrack property is an eventhandler which specifies a function to be
called when the addtrack event occurs on a mediastream instance.
... the addtrack event does not get fired when javascript code explicitly adds tracks to the stream (by
calling addtrack()).
MediaStream.onremovetrack - Web APIs
the mediastream.onremovetrack property is an eventhandler which specifies a function to be
called when the removetrack event occurs on a mediastream instance.
... the removetrack event does not get fired when javascript code explicitly removes tracks from the stream (by
calling removetrack()).
MediaStreamTrackAudioSourceNode - Web APIs
this interface is similar to mediastreamaudiosourcenode, except it lets you specifi
cally state the track to use, rather than assuming the first audio track on a stream.
... 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.
MediaTrackConstraints.aspectRatio - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.aspectratio as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints.channelCount - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.channelcount as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints.echoCancellation - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.echocancellation as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints.frameRate - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.framerate as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints.height - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.height as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints.latency - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.latency as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints.sampleRate - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplerate as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints.sampleSize - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplesize as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackControls.volume - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.volume as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints.width - Web APIs
if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.width as returned by a
call to mediadevices.getsupportedconstraints().
... however, typi
cally this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with.
MediaTrackConstraints - Web APIs
a constraints dictionary is passed into applyconstraints() to allow a script to establish a set of exact (required) values or ranges and/or preferred values or ranges of values for the track, and the most recently-requested set of custom constraints can be retrieved by
calling getconstraints().
... for each constraint, you can typi
cally specify an exact value you need, an ideal value you want, a range of acceptable values, and/or a value which you'd like to be as close to as possible.
MediaTrackSupportedConstraints.autoGainControl - Web APIs
you can access the supported constraints dictionary by
calling navigator.mediadevices.getsupportedconstraints().
... the autogaincontrol constraint indicates whether or not the browser offers the ability to automati
cally control the gain (volume) on media tracks; this obviously is contingent on whether or not the individual device supports automatic gain control as well; it's typi
cally a feature provided by microphones.
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
you can access the supported constraints dictionary by
calling navigator.mediadevices.getsupportedconstraints().
... the noisesuppression constraint indicates whether or not the browser offers the ability to automati
cally control the gain (volume) on media tracks; this obviously is contingent on whether or not the individual device supports automatic gain control as well.
Media Session API - Web APIs
since multiple pages may be simultaneously using this api, the user agent is responsible for
calling the correct page's event handlers.
... mediapositionstate used to contain information about the current playback position, playback speed, and overall media duration when
calling the mediasession method setpositionstate() to establish the media's length, playback position, and playback speed.
MessagePort: message event - Web APIs
targetframe.postmessage('init', targetorigin, [channel.port2]); the target can receive the port and start listening for messages on it using code like this: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.start(); }); note that the listener must
call messageport.start() before any messages will be delivered to this port.
... this is only needed when using the addeventlistener() method: if the receiver uses onmessage instead, start() is
called implicitly: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.onmessage = (event) => { received.textcontent = event.data; }; }); specifications specification status html living standard living standard ...
MessagePort: messageerror event - Web APIs
messages and message errors on it using code like this: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.addeventlistener('messageerror', (event) => { console.error(event.data); }); myport.start(); }); note that the listener must
call messageport.start() before any messages will be delivered to this port.
... this is only needed when using the addeventlistener() method: if the receiver uses onmessage instead, start() is
called implicitly: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.onmessage = (event) => { received.textcontent = event.data; }; myport.onmessageerror = (event) => { console.error(event.data); }; }); specifications specification status html living standard living standard ...
MessagePort - Web APIs
event handlers inherits event handlers from its parent, eventtarget onmessage an eventlistener
called when messageevent of type message is fired on the port—that is, when the port receives a message.
... onmessageerror an eventlistener
called when a messageevent of type messageerror is fired—that is, when it receives a message that cannot be deserialized.
Microdata DOM API - Web APIs
when
called, the method must return a live nodelist object containing all the elements in the document, in tree order, that are each top-level microdata items whose types include all the types specified in the method's argument, having obtained the types by splitting the string on spaces.
...when the method is invoked on a document object again with the same argument, the user agent may return the same object as the object returned by the earlier
call.
MouseEvent.button - Web APIs
users may change the configuration of buttons on their pointing device so that if an event's button property is zero, it may not have been caused by the button that is physi
cally left–most on the pointing device; however, it should behave as if the left button was clicked in the standard button layout.
... syntax var buttonpressed = instanceofmouseevent.button return value a number representing a given button: 0: main button pressed, usually the left button or the un-initialized state 1: auxiliary button pressed, usually the wheel button or the middle button (if present) 2: secondary button pressed, usually the right button 3: fourth button, typi
cally the browser back button 4: fifth button, typi
cally the browser forward button as noted above, buttons may be configured differently to the standard "left to right" layout.
MouseEvent - Web APIs
example this example demonstrates simulating a click (that is programmati
cally generating a click event) on a checkbox using dom methods.
... 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("button").addeventlistener('click', simulateclick); result specifications specification status comment css object model (cssom) view modulethe definition of 'mouseevent' in that specification.
MutationObserver.disconnect() - Web APIs
the observer can be reused by
calling its observe() method again.
... const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer = new mutationobserver(
callback); observer.observe(targetnode, observeroptions); /* some time later...
MutationObserverInit.characterDataOldValue - Web APIs
by default, only changes to the text of the node specified as the target parameter when you
called observe() are monitored.
... if you set characterdataoldvalue to true, characterdata is automati
cally assumed to be true, even if you don't expressly set it as such.
NDEFReader - Web APIs
ndefreader.onerror an event handler for error event which is
called to notify that an error occured during reading.
... ndefreader.scan()
called to activate the reader (after ensuring hardware and ua compatibility and obtaining permission from the user) or get an error explaining why feature is not available.
Navigator.getBattery() - Web APIs
syntax var batterypromise = navigator.getbattery(); return value a promise which, when resolved,
calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state.
... exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: securityerror the user agent does not expose battery information to insecure contexts and this method was
called from insecure context.
Navigator.registerProtocolHandler() - Web APIs
this might happen if: the registered scheme (protocol) is invalid, such as a scheme the browser handles itself (https:, about:, etc.) the handler url’s origin does not match the origin of the page
calling this api.
... the browser requires that this function is
called from a secure context.
Navigator.requestMediaKeySystemAccess() - Web APIs
consider that when deciding when to
call requestmediakeysystemaccess(); you don't want those requests to happen at inconvenient times.
... as a general rule, this function should be
called only when it's about time to create and use a mediakeys object by
calling the returned mediakeysystemaccess object's createmediakeys() method.
Navigator.share() - Web APIs
nt.queryselector('button'); const resultpara = document.queryselector('.result'); // must be triggered some kind of "user activation" btn.addeventlistener('click', async () => { try { await navigator.share(sharedata) resultpara.textcontent = 'mdn shared successfully' } catch(err) { resultpara.textcontent = 'error: ' + err } }); sharing files to share files, first test for and
call navigator.canshare().
... then include an array of files in the
call to navigator.share(): notice: that the sample handles feature detection by testing for navigator.canshare() rather than for navigator.share().
Navigator - Web APIs
standard navigator.canshare() returns true if a
call to navigator.share() would succeed.
... non-standard navigator.mozislo
callyavailable() lets code check to see if the document at a given uri is available without using the network.
Node.childNodes - Web APIs
adding or removing children will change the list's `length` } } remove all children from a node // this is one way to remove all children from a node // box is an object reference to an element while (box.firstchild) { //the list is live so it will re-index each
call box.removechild(box.firstchild); } notes the items in the collection of nodes are objects, not strings.
...(for example, to get the name of the first childnode: elementnodereference.childnodes[1].nodename.) the document object itself has 2 children: the doctype declaration and the root element, typi
cally referred to as documentelement.
Node.compareDocumentPosition() - Web APIs
return value an integer value whose bits represent the othernode's relationship to the
calling node.
...for example, if othernode is located earlier in the document and contains the node on which comparedocumentposition() was
called, then both the document_position_contains and document_position_preceding bits would be set, producing a value of 10 (0x0a).
Node.getRootNode() - Web APIs
this will differ in exact form depending on where you
called getrootnode(); for example:
calling it on an element inside a standard web page will return an htmldocument object representing the entire page.
...
calling it on an element inside a shadow dom will return the associated shadowroot.
Node.insertBefore() - Web APIs
(that is, it will automati
cally 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 that the copies made with clonenode() will not be automati
cally kept in sync.
Node.setUserData() - Web APIs
handler is a
callback which will be
called any time the node is being cloned, imported, renamed, as well as if deleted or adopted; a function can be used or an object implementing the handle method (part of the userdatahandler interface).
... example var d = document.implementation.createdocument('', 'test', null); d.documentelement.setuserdata('key', 15, {handle:function (o, k, d, s, ds) {console.log(o+'::'+k+'::'+d+'::'+s+'::'+ds)}}); // 2::key::15::[object element]::[object element] console.log(d.documentelement.getuserdata('key')); // 15 var e = document.importnode(d.documentelement, true); // causes handler to be
called console.log(e.getuserdata('key')); // null since user data is not copied specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'node.setuserdata()' in that specification.
NodeIterator.nextNode() - Web APIs
the first
call to nextnode() returns the first node in the set.
... in old browsers, as specified in old versions of the specifications, the method may throws the invalid_state_err domexception if this method is
called after the nodeiterator.detach()method.
NodeList - Web APIs
live nodelists in some cases, the nodelist is live, which means that changes in the dom automati
cally update the collection.
... there is also an internet explorer-compatible way to use array.prototype.foreach for iteration: const list = document.queryselectorall('input[type=checkbox]'); array.prototype.foreach.
call(list, function (checkbox) { checkbox.checked = true; }); specifications specification status comment domthe definition of 'nodelist' in that specification.
Notification.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.
... at the end of the function, it also
calls close() inside a addeventlistener() function to remove the notification when the relevant content has been read on the webpage.
Notification.requestPermission() - Web APIs
note: this feature is not available in sharedworker note: safari still uses the
callback syntax to get the permission.
...}); previously, the syntax was based on a simple
callback; this version is now deprecated: notification.requestpermission(
callback); parameters
callback optional deprecated since gecko 46 an optional
callback function that is
called with the permission value.
Notification - Web APIs
notification.requireinteraction read only a boolean indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automati
cally.
... notification.close() programmati
cally closes a notification instance.
OfflineAudioContext - Web APIs
event handlers offlineaudiocontext.oncomplete is an eventhandler
called when processing is terminated, that is when the complete event (of type offlineaudiocompletionevent) is raised, after the event-based version of offlineaudiocontext.startrendering() is used.
...sole.log('rendering completed successfully'); 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 startrendering is
called a second time on an offlineaudiocontext }); }); } request.send(); } // run getdata to start the process off getdata(); specifications specification status comment web audio apithe definition of 'offlineaudiocontext' in that specification.
OscillatorNode - Web APIs
if the default values are acceptable, you can simply
call the baseaudiocontext.createoscillator() factory method.
... methods inherits methods from its parent, audioscheduledsourcenode, and adds the following: oscillatornode.setperiodicwave() sets a periodicwave which describes a periodic waveform to be used instead of one of the standard waveforms;
calling this sets the type to custom.
PaintWorklet.registerPaint - Web APIs
the paintworklet.registerpaint() method of the paintworklet interface registers a class programmati
cally generate an image where a css property expects a file.
...note that registerpaint() is
called without a reference to paintworklet.
ParentNode.replaceChildren() - Web APIs
you simply
call it on the parent node without any argument specified: mynode.replacechildren(); transferring nodes between parents replacechildren() enables you to easily transfer nodes between parents, without having to resort to verbose looping code.
...it then
calls replacechildren() on the list to transfer the options to, using the spread operator to pass in all the options contained in both constants.
PaymentDetailsBase - Web APIs
paymentdetailsinit provides payment information when
calling the paymentrequest() constructor.
...this can be delivered to the payment interface using either paymentdetailsupdateevent.updatewith() or by returning it from the optional detailsupdate promise provided to the paymentrequest.show()
call that begins the user interaction.
PaymentRequest: merchantvalidation event - Web APIs
typi
cally, a client should not access the validation url.
...the content delivered by the validation server is forwarded to the merchant server and is then returned from the fetch()
call's fulfillment handler to the complete() method on the event.
PaymentRequest.shippingAddress - Web APIs
you can trigger this by setting paymentoptions.requestshipping to true when
calling the paymentrequest constructor.
...when the paymentrequest.onshippingaddresschange is
called, updatedetails() is
called to update the details of the paymentrequest, using shippingaddress to set the correct shipping cost.
PaymentRequest.shippingOption - Web APIs
this attribute is only populated if the constructor is
called with the requestshipping flag set to true.
...in each
calls to updatedetails() are made, one using a promise, and the other with a plain js object.
PaymentRequest: shippingoptionchange event - Web APIs
for example, if there are three options (such as "free ground shipping", "2-day air", and "next day"), each time the user chooses one of those options, this event handler is
called to recalculate the total based on the changed shipping option.
...the revised total is submitted back to the payment request by
calling the event's updatewith() method.
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.
...it must be on the same origin as the
calling page.
PaymentResponse: payerdetailchange event - Web APIs
if any are invalid, appropriate error messages should be configured and the retry() method should be
called on the paymentresponse to ask the user to update the invalid entries.
... response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payername, payeremail, payerphone } = response; // validate each value which changed by
calling a function // that validates each type of data, returning a promise which // resolves if the data is valid.
PaymentResponse.shippingAddress - Web APIs
you can trigger this by setting paymentoptions.requestshipping to true when
calling the paymentrequest constructor.
...when the paymentrequest.onshippingaddresschange is
called, updatedetails() is
called to update the details of the paymentrequest, using shippingaddress to set the correct shipping cost.
PaymentResponse.shippingOption - Web APIs
syntax var shippingoption = paymentrequest.shippingoption; example in the example below, the paymentrequest.onshippingaoptionchange event is
called.
... it
calls updatedetails() to toggle the shipping method between "standard" and "express".
Payment processing concepts - Web APIs
note this function must go through the merchant server, because a client typi
cally does not access the validation url itself.
...for instance, safari has integrated support for apple pay, so the apple pay payment handler uses this to ensure that apple pay can be used to pay the merchant by sending merchantvalidation to the client, instructing it to fetch the server's validation data and deliver it to the payment handler by
calling complete().
performance.now() - Web APIs
it's important to keep in mind that to mitigate potential security threats such as spectre, browsers typi
cally round the returned value by some amount in order to be less predictable.
... syntax t = performance.now(); example const t0 = performance.now(); dosomething(); const t1 = performance.now(); console.log(`
call to dosomething took ${t1 - t0} milliseconds.`); unlike other timing data available to javascript (for example date.now), the timestamps returned by performance.now() are not limited to one-millisecond resolution.
Performance: resourcetimingbufferfull event - Web APIs
bubbles yes cancelable yes interface event event handler property onresourcetimingbufferfull examples the following example sets a
callback function on the onresourcetimingbufferfull property.
... function buffer_full(event) { console.log("warning: resource timing buffer is full!"); performance.setresourcetimingbuffersize(200); } function init() { // set a
callback if the resource buffer becomes filled performance.onresourcetimingbufferfull = buffer_full; } <body onload="init()"> note that you could also set up the handler using the addeventlistener() function: performance.addeventlistener('resourcetimingbufferfull', buffer_full); specifications specification status comment resource timing level 1the definition of 'onresourcetimingbufferfull' in that specification.
PerformanceEntry.entryType - Web APIs
mark performancemark domstring the name used when the mark was created by
calling performance.mark().
... measure performancemeasure domstring name used when the measure was created by
calling performance.measure().
PerformanceEntry.name - Web APIs
domstring performancemark mark the name used when the mark was created by
calling performance.mark().
... domstring performancemeasure measure name used when the measure was created by
calling performance.measure().
PerformanceEntry.startTime - Web APIs
"mark" - returns the timestamp when the mark was created by a
call to performance.mark().
... "measure" - returns the timestamp when the measure was created by a
call to performance.measure().
PerformanceObserverEntryList.getEntries() - Web APIs
the list's members are determined by the set of entry types specified in the
call to the observe() method.
... the list is available in the observer's
callback function (as the first parameter in the
callback).
Permissions.revoke() - Web APIs
syntax this method is
called on the global permissions object navigator.permissions.
... returns a promise that
calls its fulfillment handler with a permissionstatus object indicating the result of the request.
Permissions API - Web APIs
concepts and usage histori
cally different apis handle their own permissions inconsistently — for example the notifications api allows for explicit checking of permission status and requesting permission, whereas the geolocation api doesn't (which causes problems if the user denied the initial permission request).
... examples we have made a simple example available
called location finder.
PointerEvent.pointerType - Web APIs
example this example illustrates using the value of the pointertype property to
call the appropriate pointer type processing function.
... targetelement.addeventlistener('pointerdown', function(event) { //
call the appropriate pointer type handler switch (event.pointertype) { case 'mouse': process_pointer_mouse(event); break; case 'pen': process_pointer_pen(event); break; case 'touch': process_pointer_touch(event); break; default: console.log(`pointertype ${event.pointertype} is not suported`); } }, false); specifications specification status comment pointer eventsthe definition of 'pointertype' in that specification.
PointerEvent - Web APIs
typi
cally, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media.
...if you use pointer events, you should
call event.preventdefault() to keep the mouse event from being sent as well.
Multi-touch interaction - Web APIs
// save this event for later processing (this could be part of a // multi-touch interaction) and update the background color push_event(ev); if (logevents) log("pointerdown: name = " + ev.target.id, ev); update_background(ev); } pointer move the pointermove handler is
called when the pointer moves.
... it may be
called multiple times (for example, if the user moves the pointer) before a different event type is fired.
PublicKeyCredential - Web APIs
this identifier can be used to look up credentials for future
calls to credentialscontainer.get.
...it is either of type authenticatorattestationresponse if the publickeycredential was the results of a navigator.credentials.create()
call, or of type authenticatorassertionresponse if the publickeycredential was the result of a navigator.credentials.get()
call.
PushManager.register() - Web APIs
syntax var request = navigator.push.register(); return a domrequest object to handle the success or failure of the method
call.
... if the method
call is successful, the request's result will be a string, which is the endpoint url.
PushManager.registrations() - Web APIs
syntax var request = navigator.push.registrations(); return a domrequest object to handle the success or failure of the method
call.
... if the method
call is successful, the request's result will be an array of pushregistration objects.
PushMessageData - Web APIs
unlike the similar methods in the fetch api, which only allow the method to be invoked once, these methods can be
called multiple times.
... messages received through the push api are sent encrypted by push services and then automati
cally decrypted by browsers before they are made accessible through the methods of the pushmessagedata interface.
RTCDataChannel.bufferedAmount - Web APIs
the queue may build up as a result of
calls to the send() method.
... the user agent may implement the process of actually sending data in any way it chooses; this may be done periodi
cally during the event loop or truly asynchronously.
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
the user agent may implement the process of actually sending data in any way it chooses; this may be done periodi
cally during the event loop or truly asynchronously.
....bufferedamountlowthreshold = threshold; value the number of queued outgoing data bytes below which the buffer is considered to be "low." example in this snippet of code, bufferedamountlowthreshold is set to 64kb, and a handler for the bufferedamountlow event is established by setting the rtcdatachannel.onbufferedamountlow property to a function which should send more data into the buffer by
calling send().
RTCDataChannel: close event - Web APIs
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.
... dc.addeventlistener("close", ev => { messageinputbox.disabled = true; sendbutton.disabled = true; connectbutton.disabled = false; disconnectbutton.disabled = true; }, false); all this code does in response to receiving the close event is to disable an input box and its "send" button, and to enable the button used to start a
call (while disabling the one that ends a
call).
RTCDataChannel.label - Web APIs
a data channel's label is set when the channel is created by
calling rtcpeerconnection.createdatachannel().
... syntax var name = adatachannel.label; value a string identifier assigned by the web site or app when the data channel was created, as specified when rtcpeerconnection.createdatachannel() was
called to create the channel.
RTCDataChannel.maxRetransmits - Web APIs
this can only be set when the rtcdatachannel is created by
calling rtcpeerconnection.createdatachannel(), using the maxretransmits field in the specified options.
... syntax var tries = adatachannel.maxretransmits; value the maximum number of times the browser will try to retransmit a message before giving up, or null if not set when rtcpeerconnection.createdatachannel() was
called.
RTCDataChannel.onclose - Web APIs
the rtcdatachannel.onclose property is an eventhandler which specifies a function to be
called by the browser when the close event is received by the rtcdatachannel.
... syntax rtcdatachannel.onclose = function; value a function which the browser will
call to handle the close event.
RTCDataChannel.onerror - Web APIs
the rtcdatachannel.onerror property is an eventhandler which specifies a function to be
called when the error event is received.
... syntax rtcdatachannel.onerror = function; value a function which the browser will
call to handle the error event when it occurs on the data channel.
RTCDataChannel.onmessage - Web APIs
the rtcdatachannel.onmessage property stores an eventhandler which specifies a function to be
called when the message event is fired on the channel.
... syntax rtcdatachannel.onmessage = function; value a function which the browser will
call to handle the message event.
RTCDataChannel.onopen - Web APIs
the rtcdatachannel.onopen property is an eventhandler which specifies a function to be
called when the open event is fired; this is a simple event which is sent when the data channel's underlying data transport—the link over which the rtcdatachannel's messages flow—is established or re-established.
... syntax rtcdatachannel.onopen = function; value a function which the browser will
call to handle the open event.
RTCDataChannel.send() - Web APIs
specifications exist to define how to automati
cally fragment large messages, but not all browsers implement them, and those that do have various additional restrictions.
... example in this example, a routine
called sendmessage() is created; it accepts an object as input and sends to the remote peer, over the rtcdatachannel, a json string with the specified object and a time stamp.
RTCError - Web APIs
this message is then displayed using a function
called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
... any other error is treated as terminal, causing a terminatemyconnection() function to be
called.
RTCErrorEvent.error - Web APIs
this message is then displayed using a function
called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
... any other error is treated as terminal, causing a terminatemyconnection() function to be
called.
RTCIceCandidate.protocol - Web APIs
protocol is null by default if not specified properly in the sdp, but this is an error condition and will result in a thrown exception when you
call rtcpeerconnection.addicecandidate().
...the value is automati
cally extracted from the candidate a-line, if it's formatted properly.
RTCIceCandidate. toJSON() - Web APIs
the rtcicecandidate method tojson() converts the rtcicecandidate on which it's
called into json in the form of an rtcicecandidateinit object.
... you can then get a stringified version of the object by
calling stringify() on the returned object.
RTCIceCandidate - Web APIs
when starting a webrtc peer connection, typi
cally a number of candidates are proposed by each end of the connection, until they mutually agree upon one which describes the connection they decide will be best.
... examples for examples, see the article signaling and video
calling, which demonstrates the entire process.
RTCIceCandidatePairStats - Web APIs
the circuit breaker is triggered whenever a connection times out or otherwise needs to be automati
cally aborted.
... usage notes the currently-active ice candidate pair—if any—can be obtained by
calling the rtcicetransport method getselectedcandidatepair(), which returns an rtcicecandidatepair object, or null if there isn't a pair selected.
RTCIceCandidateStats - Web APIs
this function is then
called for rtcstats objects whose type is local-candidate, indicating that the object is in fact an rtcicecandidatestats with information about a local ice candidate.
... const isusablenetworktype = stats => { switch(stats.networktype) { case "ethernet": case "vpn": return true; case "bluetooth": case "cellular": case "wimax": case "unknown": default: return false; } } if (rtcstats && rtcstats.type === "local-candidate") { if (!isusablenetworktype(rtcstats)) { abortconnection(); return; } } this code
calls a function
called abortconnection() if the rtcstats object represents information about a local candidate is which would be using a network connection other than ethernet or a vpn.
RTCIceTransport.getRemoteCandidates() - Web APIs
each time your signaling code
calls rtcpeerconnection.addicecandidate() to add a received candidate to the ice session, the ice agent places it in the list returned by this function.
...to find the best match found so far,
call rtcicetransport.getselectedcandidatepair().
RTCIceTransport.ongatheringstatechange - Web APIs
the ongatheringstatechange event handler for the rtcicetransport interface specifies an event handler that is to be
called when the gatheringstatechange event occurs on the transport.
... syntax rtcicetransport.ongatheringstatechange = statechangehandler; value a function to be
called when the rtcicetransport object's gathering state changes.
RTCIceTransport.onstatechange - Web APIs
syntax rtcicetransport.onstatechange = statechangehandler; value set this property to reference a function you provide that is
called by the webrtc layer when the rtcicetransport object's state changes.
... example this snippet establishes a handler for the statechange event that looks to see if the transport has entered the "failed" state, which indicates that the connection has failed with no chance of being automati
cally restored.
RTCIceTransportState - Web APIs
a value of "disconnected" means that a transient issue has occurred that has broken the connection, but that should resolve itself automati
cally without your code having to take any action.
...if the restart occured during a transient "disconnected" state, the state transitions to "checking" the disconnected state "disconnected" is a transient state that occurs when the connection between the two peers fails in a manner that the webrtc infrastructure can automati
cally correct once the connection is available again.
RTCInboundRtpStreamStats.qpSum - Web APIs
since the value of qp is typi
cally larger to indicate higher compression factors, the larger this sum is, the more heavily compressed the stream generally has been.
... it's important to keep in mind that the value of qp can change periodi
cally—even every frame—so it's difficult to know for certain how substantial the compression is.
RTCOfferAnswerOptions.voiceActivityDetection - Web APIs
the default value, true, indicates that voice detection should be used and that if possible, the user agent should automati
cally disable or mute outgoing audio when the audio source is not sensing a human voice.
...the default value, true, indicates that the user agent should monitor the audio coming from the microphone or other audio source and automati
cally cease transmitting data or mute when the user isn't speaking into the microphone, a value of false indicates that the audio should continue to be transmitted regardless of whether or not speech is detected.
RTCOfferAnswerOptions - Web APIs
it's used as the base type for the options parameter when
calling createoffer() or createanswer() on an rtcpeerconnection.
... properties voiceactivitydetection optional for configurations of systems and codecs that are able to detect when the user is speaking and toggle muting on and off automati
cally, this option enables and disables that behavior.
RTCOutboundRtpStreamStats.qpSum - Web APIs
since the value of qp is typi
cally larger to indicate higher compression factors, the larger this sum is, the more heavily compressed the stream generally has been.
... it's important to keep in mind that the value of qp can change periodi
cally—even every frame—so it's difficult to know for certain how substantial the compression is.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
this property is only set after having
called rtcpeerconnection.setremotedescription().
... note: this property's value is determined once the local peer has
called rtcpeerconnection.setremotedescription(); the provided description is used by the ice agent to determine whether or not the remote peer supports trickled ice candidates.
RTCPeerConnection: icecandidateerror event - Web APIs
this handler looks specifi
cally for 701 errors that indicate that candidates couldn't reach the stun or turn server.
... when this happens, the server url and the error message are passed to a function
called reportconnectfail() to log or output the connection failure.
RTCPeerConnection.onaddstream - Web APIs
the event is sent immediately after the
call setremotedescription() and doesn't wait for the result of the sdp negotiation.
... example this code, based on an older version of our signaling and video
calling sample, responds to addstream events by setting the video source for a <video> element to the stream specified in the event, and then enabling a "hang up" button in the app's user interface.
RTCPeerConnection.onconnectionstatechange - Web APIs
the rtcpeerconnection.onconnectionstatechange property specifies an eventhandler which is
called to handle the connectionstatechange event when it occurs on an instance of rtcpeerconnection.
... syntax rtcpeerconnection.onconnectionstatechange = eventhandler; value a function which is
called by the browser when the connectionstatechange event occurs on the rtcpeerconnection.
RTCPeerConnection.ondatachannel - Web APIs
the rtcpeerconnection.ondatachannel property is an eventhandler which specifies a function which is
called when the datachannel event occurs on an rtcpeerconnection.
... this event, of type rtcdatachannelevent, is sent when an rtcdatachannel is added to the connection by the remote peer
calling createdatachannel().
RTCPeerConnection.onicecandidate - Web APIs
the rtcpeerconnection property onicecandidate property is an eventhandler which specifies a function to be
called when the icecandidate event occurs on an rtcpeerconnection instance.
... example the example below, which is based on the code from the article signaling and video
calling, sets up a handler for icecandidate events to send the candidates to the remote peer.
RTCPeerConnection.peerIdentity - Web APIs
example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the
caller.
... if an error occurs and the promise is rejected, this logs the error to the console and returns null to the
caller.
RTCPeerConnectionIceErrorEvent.address - Web APIs
for example, on a mobile phone, there are typi
cally at least two network interfaces available: the cellular connection and a wifi connection.
... examples this example creates a handler for icecandidateerror events which creates human readable messages describing the local network interface for the connection as well as the ice server that was being used to try to open the connection, then
calls a function to display those as well as the event's errortext property's contents.
RTCRtpEncodingParameters - Web APIs
dtx only used for an rtcrtpsender whose kind is audio, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is turned off or the microphone muted automati
cally in the absence of voice activity).
...this is typi
cally only relevant for audio encodings.
RTCRtpSendParameters.encodings - Web APIs
dtx only used for an rtcrtpsender whose kind is audio, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is turned off or the microphone muted automati
cally in the absence of voice activity).
...this is typi
cally only relevant for audio encodings.
RTCRtpSendParameters - Web APIs
the webrtc api's rtcrtpsendparameters dictionary is used to specify the parameters for an rtcrtpsender when
calling its setparameters() method.
... transactionid a string containing a unique id for the last set of parameters applied; this value is used to ensure that setparameters() can only be
called to alter changes made by a specific previous
call to getparameters().
RTCRtpSender.setStreams() - Web APIs
function addtrackstostream(stream) { let senders = pc.getsenders(); senders.foreach((sender) => { if (sender.track && (sender.transport.state === connected)) { sender.setstreams(stream); } }); } after
calling the rtcpeerconnection method getsenders() to get the list of the connection's senders, the addtrackstostream() function iterates over the list.
... for each sender, if the sender's track is non-null and its transport's state is connected, we
call setstreams() to add the track to the stream specified.
RTCRtpStreamStats.qpSum - Web APIs
since the value of qp is typi
cally larger to indicate higher compression factors, the larger this sum is, the more heavily compressed the stream generally has been.
... it's important to keep in mind that the value of qp can change periodi
cally—even every frame—so it's difficult to know for certain how substantial the compression is.
RTCSessionDescription() - Web APIs
the session negotiation process begins with an offer being sent from the
caller to the
callee.
... 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.
ReadableStreamDefaultController.close() - Web APIs
a cancel() function is also provided to stop the generation if readablestream.cancel() is
called for any reason.
...it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is
called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'close()' in that specification.
ReadableStreamDefaultController.enqueue() - Web APIs
a cancel() function is also provided to stop the generation if readablestream.cancel() is
called for any reason.
...it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is
called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'enqueue()' in that specification.
ReadableStreamDefaultReader.cancel() - Web APIs
that data is lost after cancel is
called, and the stream is not readable any more.
...current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and
call this function again return reader.read().then(processtext); }); } specifications specification status comment streamsthe definition of 'cancel()' in that specification.
ReportingObserver() - Web APIs
syntax new reportingobserver(
callback[, options]); parameters
callback a
callback function that runs when the observer starts to collect reports (i.e.
...the
callback function is given two parameters: reports: a sequence of report objects representing the reports collected in the observer's report queue.
Request.credentials - Web APIs
same-origin: send user credentials (cookies, basic http auth, etc..) if the url is on the same origin as the
calling script.
... include: always send user credentials (cookies, basic http auth, etc..), even for cross-origin
calls.
Resize Observer API - Web APIs
such a solution tends to only work for limited use cases, be bad for performance (continually
calling the above methods would result in a big performance hit), and often won't work when the browser window size is not changed.
...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.
Response.redirected - Web APIs
instead, you should actually instead do the filtering when you
call fetch().
... elem.innerhtml = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when
calling fetch(), like this: fetch("awesome-picture.jpg", { redirect: "error" }).then(function(response) { return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); specifications specification status comment fetchthe definition of 'redirected' in that specif...
Response - Web APIs
examples in our basic fetch example (run example live) we use a simple fetch()
call to grab an image and display it in an <img> element.
... the fetch()
call returns a promise, which resolves to the response object associated with the resource fetch operation.
SVGElement: abort event - Web APIs
this basi
cally implements the standard abort dom event.
... bubbles no cancelable no interface svgevent event handler property onabort examples svgelem.addeventlistener('abort', () => { console.log('load aborted.'); }) specifications not really described anywhere specifi
cally, but mentioned in the svg 2 spec.
SVGFEDropShadowElement - Web APIs
svgfedropshadowelement.stddeviationx read only an svganimatednumber corresponding to the (possibly automati
cally computed) x component of the stddeviationx attribute of the given element.
... svgfedropshadowelement.stddeviationy read only an svganimatednumber corresponding to the (possibly automati
cally computed) y component of the stddeviationy attribute of the given element.
SVGFEGaussianBlurElement - Web APIs
svgfegaussianblurelement.stddeviationx read only an svganimatednumber corresponding to the (possibly automati
cally computed) x component of the stddeviation attribute of the given element.
... svgfegaussianblurelement.stddeviationy read only an svganimatednumber corresponding to the (possibly automati
cally computed) y component of the stddeviation attribute of the given element.
ServiceWorkerContainer.startMessages() - Web APIs
it's possible to start dispatching these messages earlier by
calling serviceworkercontainer.startmessages(), for example if you've invoked a message handler using eventtarget.addeventlistener() before the page has finished loading, but want to start processing the messages right away.
... note: the messages start being sent automati
cally when setting the handler directly using serviceworkercontainer.onmessage.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
ion.options) .then(subscription => { return fetch("register", { method: "post", headers: { "content-type": "application/json" }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by
calling the push manager's subscribe() method.
...this is delivered to the app server using a fetch()
call to post a json formatted rendition of the subscription's endpoint to the app server.
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.
... therefore, it's common to
call self.skipwaiting() from inside of an installevent handler.
ServiceWorkerRegistration - Web APIs
an active worker will control a serviceworkerclient if the client's url falls within the scope of the registration (the scope option set when serviceworkercontainer.register is first
called.) serviceworkerregistration.navigationpreload read only returns the instance of navigationpreloadmanager associated with the current service worker registration.
... 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.
ServiceWorkerState - Web APIs
during this state, extendableevent.waituntil() can be
called inside the install event handler to extend the life of the installing worker until the passed promise resolves successfully.
...during this state, extendableevent.waituntil() can be
called inside the onactivate event handler to extend the life of the active worker until the passed promise resolves successfully.
Service Worker API - Web APIs
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.
... note: because oninstall/onactivate could take a while to complete, the service worker spec provides a waituntil method, once this is
called oninstall or onactivate, it passes a promise.
SharedWorker - Web APIs
abstractworker.onerror is an eventlistener that is
called whenever an errorevent of type error bubbles through the worker.
...otherwise
called implicitly by onmessage setter.
SharedWorkerGlobalScope - Web APIs
some additional global functions, namespaces objects, and constructors, not typi
cally associated with the worker global scope, but available on it, are listed in the javascript reference.
... sharedworkerglobalscope.onconnect is an eventhandler representing the code to be
called when the connect event is raised — that is, when a messageport connection is opened between the associated sharedworker and the main thread.
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.
... usage notes if the parent mediasource is in its "ended" readystate,
calling changetype() will transition the media source to the "open" readystate and fire a simple event named sourceopen at the parent media source.
SourceBuffer.mode - Web APIs
segment timestamps are generated automati
cally for the segments that observe this order.
... this property cannot be changed during while the sourcebuffer is processing either an appendbuffer() or remove()
call.
SourceBuffer.remove() - Web APIs
this method can only be
called when sourcebuffer.updating equals false.
... if sourcebuffer.updating is not equal to false,
call sourcebuffer.abort().
SourceBuffer - Web APIs
event handlers sourcebuffer.onabort fired whenever sourcebuffer.appendbuffer() or sourcebuffer.appendstream() is ended by a
call to sourcebuffer.abort().
... sourcebuffer.changetype() changes the mime type that future
calls to appendbuffer() will expect the new data to conform to.
SpeechSynthesisErrorEvent.error - Web APIs
possible codes are: canceled a speechsynthesis.cancel method
call caused the speechsynthesisutterance to be removed from the queue before it had begun being spoken.
... interrupted a speechsynthesis.cancel method
call caused the speechsynthesisutterance to be interrupted after it had begun being spoken and before it completed.
SubtleCrypto.unwrapKey() - Web APIs
this means that it takes as its input a key that has been exported and then encrypted (also
called "wrapped").
...this is sometimes
called the "unwrapping key".
Text.wholeText - Web APIs
the text.wholetext read-only property returns the full text of all text nodes logi
cally adjacent to the node.
...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.
Text - Web APIs
text.wholetext read only returns a domstring containing the text of all text nodes logi
cally adjacent to this node, concatenated in document order.
... text.replacewholetext replaces the text of the current node and all logi
cally adjacent nodes with the specified text.
TextEncoder.prototype.encodeInto() - Web APIs
if the output allocation (typi
cally within wasm heap) is expected to be short-lived, it makes sense to simply allocate s.length * 3 bytes for the output, in which case the first conversion attempt is guaranteed to convert the whole string.
... if your wasm program uses c strings, it's your responsibility to write the 0x00 sentinel and you can't prevent your wasm program from seeing a logi
cally truncated string if the javascript string contained u+0000.
TextRange - Web APIs
if you want to select the modified range after modifying the selection, you need to
call the textrange.select method.
... however, in other browsers, document does not have a so-
called selection attribute - they operate on the selection through the standard selection api, that is, they get the selection object through the window.getselection() method, and use the standard range object to process the text fragment.
TextTrackList.onchange - Web APIs
the texttracklist property onchange is an event handler which is
called when the change event occurs, indicating that a change has occurred on a texttrack in the videotracklist.
... syntax texttracklist.onchange = eventhandler; example this snippet establishes a handler for the change event that looks at each of the tracks in the list,
calling a function to update the state of a user interface control that indicates the current state of the track.
Multi-touch interaction - Web APIs
it also
calls preventdefault() to keep the browser from applying further event handling (for example, mouse event emulation).
... ev.preventdefault(); // cache the touch points for later processing of 2-touch pinch/zoom if (ev.targettouches.length == 2) { for (var i=0; i < ev.targettouches.length; i++) { tpcache.push(ev.targettouches[i]); } } if (logevents) log("touchstart", ev, true); update_background(ev); } touch move handler the touchmove handler
calls preventdefault() for the same reason mentioned above, and invokes the pinch/zoom handler.
Transferable - Web APIs
note: the transferable interface techni
cally no longer exists.
... the functionality of transferable objects still exists, however, but is implemented at a more fundamental level (techni
cally speaking, using the [transferable] webidl extended attribute).
URLSearchParams.forEach() - Web APIs
the foreach() method of the urlsearchparams interface allows iteration through all values contained in this object via a
callback function.
... syntax searchparams.foreach(
callback); parameters
callback a
callback function that is executed against each parameter, with the param value provided as its parameter.
URL API - Web APIs
url api interfaces the url api is a simple one, with only a couple of interfaces to its name: url urlsearchparams older versions of the specification included an interface
called urlutilsreadonly, which has since been merged into the workerlocation interface.
... note the
call to urlsearchparams.sort() to sort the parameter list before generating the table.
USBEndpoint - Web APIs
this value is used to identify the endpoint when
calling methods on usbdevice.
... "isochronous" - provides unreliable data transfer for payloads that must be delivered periodi
cally.
USBInTransferResult - Web APIs
the usbintransferresult interface of the webusb api provides the result from a
call to the transferin() and controltransferin() methods of the usbdevice interface.
...a stall on a bulk or interrupt endpoint must be cleared by
calling clearhalt() before transferin() can be
called again.
USBInterface - Web APIs
it can be changed by
calling usbdevice.selectalternateinterface() with any other value found in alternates.
... usbinterface.claimedread only returns whether or not this interface has been claimed by the current page by
calling usbdevice.claiminterface().
USBOutTransferResult - Web APIs
the usbouttransferresult interface of the webusb api provides the result from a
call to the transferout() and controltransferout() methods of the usbdevice interface.
...a stall on a bulk or interrupt endpoint must be cleared by
calling clearhalt() before transferout() can be
called again.
Vibration API - Web APIs
you may specify as many vibration/pause pairs as you like, and you may provide either an even or odd number of entries; it's worth noting that you don't have to provide a pause as your last entry since the vibration automati
cally stops at the end of each vibration period.
... canceling existing vibrations
calling navigator.vibrate() with a value of 0, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern.
VideoPlaybackQuality.creationTime - Web APIs
example this example
calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped.
... if that exceeds 10% (0.1), a function
called lostframesthresholdexceeded() is
called to, perhaps, update a quality indicator to show an increase in frame loss.
VideoPlaybackQuality.droppedVideoFrames - Web APIs
frames are typi
cally dropped either before or after decoding them, when it's determined that it will not be possible to draw them to the screen at the correct time.
... example this example
calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been dropped.
VideoPlaybackQuality.totalVideoFrames - Web APIs
example this example
calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped.
... if that exceeds 10% (0.1), a function
called lostframesthresholdexceeded() is
called to, perhaps, update a quality indicator to show an increase in frame loss.
WakeLockSentinel - Web APIs
an acquired wakelocksentinel can be released manually via the release() method, or automati
cally via the platform wake lock.
... event handlers onrelease fired when the release() method is
called or the wake lock is released by the user agent.
WebGL2RenderingContext.copyBufferSubData() - Web APIs
gl.copy_read_buffer: buffer for copying from one buffer object to another (provided specifi
cally for copy operations).
... gl.copy_write_buffer: buffer for copying from one buffer object to another (provided specifi
cally for copy operations).
WebGLRenderingContext - Web APIs
to get an access to a webgl context for 2d and/or 3d graphics rendering,
call getcontext() on a <canvas> element, supplying "webgl" as the argument: var canvas = document.getelementbyid('mycanvas'); var gl = canvas.getcontext('webgl'); once you have the webgl rendering context for a canvas, you can render within it.
... webglrenderingcontext.finish() blocks execution until all previously
called commands are finished.
Boilerplate 1 - Web APIs
specifi
cally, the html has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>.
...basi
cally, it gets the webgl rendering context from the canvas element, initializes the drawing buffer, clears it black, and returns the initialized context.
Clearing by clicking - Web APIs
note how we embed the webgl function
calls inside the event handler function.
...this is // the function
call that actually does the drawing.
Color masking - Web APIs
note that the
calls to colormask() only occur when the user clicks on one of the toggle buttons.
...the color mask state of webgl is preserved, so we do not need to
call colormask() every frame to set up the color mask.
Raining rectangles - Web APIs
in addition, the example demonstrates how to integrate the webgl function
calls within a game loop.
...so we reschedule // the timeout to
call drawanimation again in 17ms.
Compressed texture formats - Web APIs
if supported, it will return an extension object with constants for the added formats and the formats will also be returned by
calls to gl.getparameter(gl.compressed_texture_formats).
...ext.compressed_rgba_s3tc_dxt1_ext for the webgl_compressed_texture_s3tc extension.) these can then be used with compressedteximage[23]d or compressedtexsubimage[23]d instead of teximage2d
calls.
Matrix math for the web - Web APIs
by convention, this dimension is
called the perspective, and is represented by the letter w.
...we'll look at the type of matrix (cleverly
called a rotation matrix) you use to do this later.
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); } requestanimationframe(render); this code uses requestanimationfr...
...ame to ask the browser to
call the function "render" on each frame.
Creating 3D objects using WebGL - Web APIs
to do this efficiently, we're going to switch from drawing using the vertices directly by
calling the gl.drawarrays() method to using the vertex array as a table, and referencing individual vertices in that table to define the positions of each face's vertices, by
calling gl.drawelements().
... 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); ...
Getting started with WebGL - Web APIs
<body> <canvas id="glcanvas" width="640" height="480"></canvas> </body> preparing the webgl context the main() function in our javascript code, is
called when our script is loaded.
... once we have the canvas, we try to get a webglrenderingcontext for it by
calling getcontext() and passing it the string "webgl".
Introduction to WebRTC protocols - Web APIs
turn some routers using nat employ a restriction
called ‘symmetric nat’.
... techni
cally, then, sdp is not truly a protocol, but a data format used to describe connection that shares media between devices.
WebSocket.bufferedAmount - Web APIs
the websocket.bufferedamount read-only property returns the number of bytes of data that have been queued using
calls to send() but not yet transmitted to the network.
...this value does not reset to zero when the connection is closed; if you keep
calling send(), this will continue to climb.
WebSocket.onclose - Web APIs
the websocket.onclose property is an eventhandler that is
called when the websocket connection's readystate changes to closed.
... it is
called with a closeevent.
WebSocket.onmessage - Web APIs
the websocket.onmessage property is an eventhandler that is
called when a message is received from the server.
... it is
called with a messageevent.
WebSocket.onopen - Web APIs
the websocket.onopen property is an eventhandler that is
called when the websocket connection's readystate changes to 1; this indicates that the connection is ready to send and receive data.
... it is
called with an event.
Web Animations API Concepts - Web APIs
this means we can use it to create and manipulate css-like animations that go from one pre-defined state to another, or we can use variables, loops, and
callbacks to create interactive animations that adapt and react to changing inputs.
...animation objects accept media in the form of animation effects, specifi
cally keyframe effects (we’ll get to those in a moment).
Web Audio API best practices - Web APIs
browser vendors decided that web audio contexts should not be allowed to automati
cally play audio; they should instead be started by a user.
... when working with an audiocontext, if you create the audio context from inside a click event the state should automati
cally be set to running.
Visualizations with Web Audio API - Web APIs
we return the analysernode.frequencybincount value, which is half the fft, then
call uint8array() with the frequencybincount as its length argument — this is how many data points we will be collecting, for that fft size.
... 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.
Attestation and Assertion - Web APIs
ons fido u2f - 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 cryptographi
cally prove that a newly generated key pair came from a specific device.
...when registering an authenticator for a new account, typi
cally a trust on first use (tofu) model applies; and when adding an authenticator to an existing account, a user has already been authenticated and has established a secure session.
Web Storage API - Web APIs
stores data with no expiration date, and gets cleared only through javascript, or clearing the browser cache / lo
cally stored data.
... examples to illustrate some typical web storage usage, we have created a simple example, imaginatively
called web storage demo.
Window: beforeunload event - Web APIs
according to the specification, to show the confirmation dialog an event handler should
call preventdefault() on the event.
... the html specification states that
calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.
Window.captureEvents() - Web APIs
when you
call the captureevents() method on the window, events of the type you specify (for example, event.click) no longer pass through to "lower" objects in the hierarchy.
... in order for events to "bubble up" in the way that they normally do, you must
call window.releaseevents() ( ) on the window to keep it from trapping events.
Window.controllers - Web APIs
however, the added controllers must be explicitly removed when the window is unloaded, as this is not done automati
cally.
... each missing removal can cause bug 415775: assertion: xpconnect is being
called on a scope without a 'components' property!
Window.getComputedStyle() - Web APIs
the returned style is a live cssstyledeclaration object, which updates automati
cally when the element's styles are changed.
...for css 2.0 properties, getcomputedstyle returns the old meaning of computed values, now
called used values.
Window.scrollY - Web APIs
the read-only scrolly property of the window interface returns the number of pixels that the document is currently scrolled verti
cally.
... syntax var y = window.scrolly value in practice, the returned value is a double-precision floating-point value indicating the number of pixels the document is currently scrolled verti
cally from the origin, where a positive value means the content is scrolled to upward.
WindowEventHandlers.onunload - Web APIs
note: browsers equipped with pop-up blockers will ignore all window.open() method
calls in onunload event handler functions.
...}; typi
cally, it is better to use window.addeventlistener() and the unload event, instead of onunload.
WindowOrWorkerGlobalScope - Web APIs
windoworworkerglobalscope.crossoriginisolated read only returns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage()
call.
... windoworworkerglobalscope.queuemicrotask() enqueues a microtask—a short function to be executed after execution of the javascript code completes and control isn't being returned to a javascript
caller, but before handling
callbacks and other tasks.
WorkerGlobalScope - Web APIs
close is an eventhandler representing the code to be
called when the close event is raised.
...this change was made to stop close() being available on service workers, as it isn't supposed to be used there and always throws an exception when
called (see bug 1336043).
XDomainRequest.onerror - Web APIs
an event handler which is
called when an xdomainrequest encounters an error.
... syntax xdr.onerror = funcref; parameters funcref a function to
call when an error occurs.
XDomainRequest.ontimeout - Web APIs
an event handler which is
called when a pending xdomainrequest times out.
... syntax xdr.ontimeout = funcref; parameters funcref a function to be
called when the event times out.
XDomainRequest - Web APIs
event handlers xdomainrequest.onprogress a handler for when the request has made progress between the send method
call and the onload event.
...est){ 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 timeout (see window.settimeout() to prevent an issue with the interface where some requests are lost if multiple xdomainrequests are being sent at the same time.
Sending and Receiving Binary Data - Web APIs
}; oreq.send(); receiving binary data in older browsers the load_binary_resource() function shown below loads binary data from the specified url, returning it to the
caller.
...in that case, you don't have to set the content-length header yourself, as the information is fetched from the stream automati
cally: // make a stream from a file.
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.
... note: when this is set, the onload handler and other event handlers are not reset after the first xmldocument is loaded, and the onload handler is
called after each part of the response is received.
XMLHttpRequest.timeout - Web APIs
the xmlhttprequest.timeout property is an unsigned long representing the number of milliseconds a request can take before automati
cally being terminated.
... using a timeout with an asynchronous request in internet explorer, the timeout property may be set only after
calling the open() method and before
calling the send() method.
XMLHttpRequestEventTarget.onabort - Web APIs
the xmlhttprequesteventtarget.onabort is the function
called when an xmlhttprequest transaction is aborted, such as when the xmlhttprequest.abort() function is
called.
... syntax xmlhttprequest.onabort =
callback; values
callback is the function to be executed when the transaction is aborted.
XMLHttpRequestEventTarget.onerror - Web APIs
the xmlhttprequesteventtarget.onerror is the function
called when an xmlhttprequest transaction fails due to an error.
... syntax xmlhttprequest.onerror =
callback; values
callback is the function to be executed when the request fails.
XMLHttpRequestEventTarget.onloadstart - Web APIs
the xmlhttprequesteventtarget.onloadstart is the function
called when an xmlhttprequest transaction starts transferring data.
... syntax xmlhttprequest.onloadstart =
callback; values
callback is the function to be
called when the transaction begins to transfer data.
XMLHttpRequestEventTarget.onprogress - Web APIs
the xmlhttprequesteventtarget.onprogress is the function
called periodi
cally with information when an xmlhttprequest before success completely.
... syntax xmlhttprequest.onprogress =
callback; values
callback is the function to be
called periodi
cally before the request is completed.
XMLSerializer - Web APIs
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().
XRBoundedReferenceSpace.boundsGeometry - Web APIs
this boundary is typi
cally configured by the user, using the software that controls their xr hardware.
...theoreti
cally, a more advanced system might use sensors or other detection methods to determine the bounds of a dedicated xr room (notice how we carefully don't
call it a holodeck?).
XRFrame.getViewerPose() - Web APIs
exceptions invalidstateerror a domexception indicating that getviewerpose() was not
called within the context of a
callback to a session's xrsession.requestanimationframe().
... examples in this
callback function for requestanimationframe(), the xrviewerpose describing the viewer's viewpoint on the world is obtained by
calling getviewerpose() on the xrframe passed into the
callback.
XRFrame - Web APIs
a webxr device api xrframe object is passed into the requestanimationframe()
callback function and provides access to the information needed in order to render a single frame of animation for an xrsession describing a vr or ar sccene.
...the information about a specific object can be obtained by
calling one of the methods on the object.
XRHandedness - Web APIs
function updateinputsources(session, frame, refspace) { for (let source of session.inputsources) { if (source.gripspace) { let grippose = frame.getpose(source.gripspace, refspace); if (grippose) { myrenderhandobject(grippose, inputsource.handedness); } } } } this function, which would be
called every animation frame (or possibly just periodi
cally, depending on the degree of smoothness required and any performance constraints), scans the list of input sources looking for any which have a gripspace which isn't null.
...assuming that's then valid, a function
called myrenderhandobject() is
called with the grip's pose and the value of handedness.
XRInputSource.gripSpace - Web APIs
examples in tis example, taken from the frame rendering
callback, the gripspace is used to render a mesh that represents the position and orieintation of the controller in the virtual environment.
...if a valid pose is returned, a method mydrawmeshusingtransform() is
called to draw the controller's mesh transformed using the grip pose's transform matrix.
XRInputSource.handedness - Web APIs
function updateinputsources(session, frame, refspace) { for (let source of session.inputsources) { if (source.gripspace) { let grippose = frame.getpose(source.gripspace, refspace); if (grippose) { myrenderhandobject(grippose, inputsource.handedness); } } } } this function, which would be
called every animation frame (or possibly just periodi
cally, depending on the degree of smoothness required and any performance constraints), scans the list of input sources looking for any which have a gripspace which isn't null.
...assuming that's then valid, a function
called myrenderhandobject() is
called with the grip's pose and the value of handedness.
XRInputSource.targetRayMode - Web APIs
example this fragment of code shows part of a function to be
called once every frame.
...for tracked pointers, a function myrendertargetrayasbeam() is
called to render a beam from the input controller's virtual position outward in the direction it's pointing.
XRInputSourceArray.length - Web APIs
rces; if (sources.length === 0) { showalertdialog("you need to have at least one controller to play super duper shark jump fest 9000.", [ { label: "shop now", url: "https://www.amazon.com/s?k=vr+controllers" }, { label: "quit" handler: quitgame } ]); } here, if length is 0, a hypothetical showalertdialog() function is
called with a prompt string explaining the need for a controller, and an array of objects, each describing a button and what should happen when it's clicked.
... the first takes the user to an amazon.com search for vr controllers, and the second
calls a quitgame() function to start shutting the game program down.
XRInputSourceEvent - Web APIs
more specifi
cally, they represent a change in the state of an xrinputsource.
...because this is an event frame, not an animation frame, you cannot
call the xrframe method getviewerpose() on it; instead, use getpose().
XRPermissionDescriptor.optionalFeatures - Web APIs
this is used for environments in which the user can physi
cally move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions.
...otherwise, typi
cally, one of the other reference space types will be used more often.
XRReferenceSpace.onreset - Web APIs
the xrreferencespace interface's onreset event handler property can be set to a function which is
called when the xrreferencespace receives a reset event, signaling that the xr device has experienced a discontinuity large enough to require that the position and/or orientation of the origin be significantly altered to compensate.
... syntax xrreferencespace.onreset = eventhandler; eventhandler = xrreferencespace.onreset; value an event handler function which will be
called whenever the reset event is received by the xrreferencespace.
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.
XRRigidTransform() - Web APIs
then requestanimationframe() is
called to ask for a new animation frame to draw into.
... the drawframe()
callback will be executed when the system is ready to draw the next frame.
XRRigidTransform - Web APIs
the advantage to using xrrigidtransform in these places rather than bare arrays that providing the matrix data is that the xrrigidtransform automati
cally does things like computing the inverse of the transform.
...it then requests the first animation frame
callback by
calling the session's requestanimationframe() method.
XRSession.inputSources - Web APIs
these controllers may include handheld controllers, xr-equipped gloves, opti
cally tracked hands, and gaze-based input methods.
... syntax inputsources = xrsession.inputsources; value an xrinputsourcearray object listing all of the currently-connected input controllers which are linked specifi
cally to the xr device currently in use.
XRSession.requestReferenceSpace() - Web APIs
this is used for environments in which the user can physi
cally move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions.
...otherwise, typi
cally, one of the other reference space types will be used more often.
XRSession.updateRenderState() - Web APIs
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.
XRSpace - Web APIs
the origin of an xrboundedreferencespace is always at floor level, with its x and z coordinates typi
cally defaulting to a location near the room's center.
... xrreferencespace represents a reference space which is typi
cally expected to remain static for the duration of the xrsession.
XRView.eye - Web APIs
for dynami
cally-rendered 3d content, you can usually ignore this and simply render each of the viewer's views, one after another.
...kipview = updateinjury(body.righteye); } if (!skipview) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); renderscene(gl, view); } } for each of the views, the value of eye is checked and if it's either left or right, we check to see if the body.lefteye.injured or body.righteye.injured property is true; if so, we
call a function updateinjury() on that eye to do things such as allow a bit of healing to occur, track the progress of a poison effect, or the like, as appropriate for the game's needs.
XRView.transform - Web APIs
the read-only transform property of the xrview interface is an xrrigidtransform object which provides the position and orientation of the viewpoint relative to the xrreferencespace specified when the xrframe.getviewerpose() method was
called to obtain the view object.
... finally, we
call the object's render() routine, passing along the modelviewmatrix and normalmatrix so the renderer can place and light the object properly.
XRViewport.y - Web APIs
the read-only xrviewport interface's y property indicates the offset from the bottom edge of the destination surface (typi
cally a xrwebgllayer to the bottom edge of the viewport within the surface into which webxr content is to be rendered.
... note: although other web apis typi
cally consider the y axis to begin at the top and grow larger progressing downward, webgl reverses this, with y growing larger as it goes upward on the screen.
XRViewport - Web APIs
x read only the offset from the origin of the destination graphics surface (typi
cally a xrwebgllayer) to the left edge of the viewport, in pixels.
... these values may be passed directly into the webglrenderingcontext.viewport() method: let xrviewport = xrwebgllayer.getviewport(xrview); gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height); example this example sets up an animation frame
callback using requestanimationframe().
XRWebGLLayer - Web APIs
examples binding the layer to a webgl context this snippet, taken from drawing a frame in movement, orientation, and motion: a webxr example, shows how the xrwebgllayer is obtained from the xrsession object's rendering state and is then bound as the current rendering webgl framebuffer by
calling the webgl bindframebuffer() function.
... let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); rendering every view in a frame each time the gpu is ready to render the scene to the xr device, the xr runtime
calls the function you specified when you
called the xrsession method requestanimationframe() to ask to render the frame.
ARIA Screen Reader Implementors Guide - Accessibility
when no wai-aria markup is present, automati
cally present some changes unless the user configures all live changes to off.
... for example, automati
cally speak changes that are caused by the user's own input, as part of the context of that input.
Using the alert role - Accessibility
<h2 role="alert">your form could not be submitted because of 3 validation errors.</h2> example 2: dynami
cally adding an element with the alert role this snippet dynami
cally creates an element with an alert role and adds it to the document structure.
...the element that the alert role is used on does not have to be able to receive focus, as screen readers will automati
cally announce the alert regardless of where keyboard focus is currently located.
ARIA: application role - Accessibility
in addition, a set of so-
called quick navigation keys has been established over the years that allows blind users to skim through a page via a certain element type.
...the screen reader mode, often
called forms mode or focus mode, lets all keyboard input go through to the browser again.
ARIA: figure role - Accessibility
again, this can be done semanti
cally, without aria, with html's <figure> and <figcaption> elements <figure> ...
...nd their relative priority order — music, cats, nature, and ice cream"> <pre><code> let awesome = ['music', 'cats', 'nature', 'ice cream']; </code></pre> <p id="figure-1">figure 1: the four layers of awesome.</p> </div> best practices only use role="figure" if you have to — for example if you don't have control over your html but are able to improve accessibility dynami
cally after the fact with javascript.
ARIA: form role - Accessibility
using the <form> element will automati
cally communicate a section of content as a form landmark, if it is provided an accessible name.
... best practices prefer html using the <form> element will automati
cally communicate a section has a role of form.
ARIA: gridcell role - Accessibility
instead use the native html td element in conjunction with the and contenteditable attribute: <td>potato</td> <td>cabbage</td> <td>onion</td> description gridcells with dynami
cally added, hidden, or removed rows and columns any element with a role="gridcell" applied to it should use aria to describe its order in the table-style grouping, provided the table, grid, or treegrid has the ability to have rows and/or columns dynami
cally added, hidden, or removed.
...>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 programati
cally described by using aria-describedby.
ARIA: Main role - Accessibility
by classifying and labeling sections of a page, structural information conveyed visually through layout can be represented programmati
cally.
... <main> <h1>active <code>main</code> element</h1> <!-- content --> </main <main hidden> <h1>hidden <code>main</code> element</h1> <!-- content --> </main> best practices prefer html using the <main> element will automati
cally communicate a section has a role of main.
ARIA: switch role - Accessibility
the developer is required to change the value of the aria-checked attribute dynami
cally when the switch is toggled.
... all elements that are descendants of an element with the switch role applied to it are automati
cally assigned role presentation.
ARIA: heading role - Accessibility
changing attribute values usually not required, unless dynami
cally inserting content.
...although theoreti
cally you can go higher, and some screen readers may support it, the results can be unpredictable with other browser/screen reader combinations.
Basic form hints - Accessibility
web developers typi
cally use presentational strategies to indicate required or invalid fields.
... the aria-invalid state can be programmati
cally applied, to indicate to an at which data fields have incorrect data, so that the user knows they have entered invalid data.
ARIA - Accessibility
along with placing them directly in the markup, aria attributes can be added to the element and updated dynami
cally using javascript code like this: // find the progress bar <div> in the dom.
...progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be
called at any time to update // the value of the progress bar.
Accessibility and Spacial Patterns - Accessibility
the two images below are from nasa research, specifi
cally, from the article, "designing with blue" "spatial localization.
... for example, blue text on a gray background is easier to perceive if it is surrounded "lo
cally" by black than by white.
Robust - Accessibility
form inputs, buttons, links, etc.) should be programmati
cally determinable.
... when using semantic elements correctly for their intended purpose, this criterion should be passed automati
cally.
-webkit-mask-repeat-x - CSS: Cascading Style Sheets
es */ -webkit-mask-repeat-x: repeat; -webkit-mask-repeat-x: no-repeat; -webkit-mask-repeat-x: space; -webkit-mask-repeat-x: round; /* multiple values */ -webkit-mask-repeat-x: repeat, no-repeat, space; /* global values */ -webkit-mask-repeat-x: inherit; -webkit-mask-repeat-x: initial; -webkit-mask-repeat-x: unset; syntax values repeat the mask image is repeated both horizontally and verti
cally.
... repeat the mask image is repeated both horizontally and verti
cally.
:active - CSS: Cascading Style Sheets
when using a mouse, "activation" typi
cally starts when the user presses down the primary mouse button.
... note: on systems with multi-button mice, css3 specifies that the :active pseudo-class must only apply to the primary button; on right-handed mice, this is typi
cally the leftmost button.
src - CSS: Cascading Style Sheets
<font-face-name> specifies the name of a lo
cally-installed font face using the local() function, which uniquely identifies a single font face within a larger family.
... description the value of this descriptor is a prioritized, comma-separated list of external references or lo
cally-installed font face names.
update - CSS: Cascading Style Sheets
slow the layout may change dynami
cally according to the usual rules of css, but the output device is not able to render or display changes quickly enough for them to be perceived as a smooth animation.
... fast the layout may change dynami
cally according to the usual rules of css, and the output device is not unusually constrained in speed, so regularly-updating things like css animations can be used.
Using CSS animations - CSS: Cascading Style Sheets
this animation will last for 3 seconds, be
called “slidein”, repeat 3 times, and alternate direction each time.
...this code configures our event listeners; we
call it when the document is first loaded in order to set things up.
Box alignment in grid layout - CSS: Cascading Style Sheets
should you be in a vertical writing mode the inline axis will run verti
cally.
... the block axis crosses the inline axis in the direction that blocks are displayed down the page — for example paragraphs in english are displayed one below the other verti
cally.
Basic concepts of flexbox - CSS: Cascading Style Sheets
the flex container an area of a document laid out using flexbox is
called a flex container.
...typi
cally if we had all of our items set to flex: 1 1 200px and then wanted one item to grow at twice the rate, we would set that item to flex: 2 1 200px.
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
typi
cally flexbox-based grid systems work by taking flexbox back to the familiar world of float-based layouts.
...thus, if a flex container has only one flex line, dynami
cally collapsing or uncollapsing items may change the flex container’s main size, but is guaranteed to have no effect on its cross size and won’t cause the rest of the page’s layout to "wobble".
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
while certain languages will use a particular writing mode or text direction, we can also use these properties for creative effect, such as running a heading verti
cally.
... the css logical properties and values specification includes logical versions of the properties that control margins, padding and borders as well as other mappings for things that we have typi
cally used physical directions to specify.
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
sizing rows in the implicit grid the default for automati
cally created rows in the implicit grid is for them to be auto-sized.
...plate-columns: repeat(4, 1fr); grid-auto-rows: 100px; grid-gap: 10px; } .wrapper div:nth-child(4n+1) { grid-column-end: span 2; grid-row-end: span 2; background-color: #ffa94d; } .wrapper div:nth-child(2) { grid-column: 3; grid-row: 2 / 4; } .wrapper div:nth-child(5) { grid-column: 1 / 3; grid-row: 1 / 3; } filling in the gaps so far, other than items we have specifi
cally placed, grid is always progressing forward and keeping items in dom order.
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
{ grid-column: 1; grid-row: 2; } <div class="wrapper"> <div class="box box1"><a href="">one</a></div> <div class="box box2"><a href="">two</a></div> <div class="box box3"><a href="">three</a></div> <div class="box box4"><a href="">four</a></div> <div class="box box5"><a href="">five</a></div> </div> the specification says that in this scenario, if box 1 really makes sense logi
cally in that position, we should go back to our source and make the change there rather than reordering using grid layout.
...an example would be where some content was semanti
cally marked up as a list but you decide to use a set of <div> elements instead as then you can have the element to be a direct child of a container set to display: grid.
Using CSS counters - CSS: Cascading Style Sheets
for example, you can use counters to automati
cally number the headings in a webpage.
... '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 automati
cally created in child elements.
Layout and the containing block - CSS: Cascading Style Sheets
contain: paint;) note: the containing block in which the root element (<html>) resides is a rectangle
called the initial containing block.
... example 1 in this example, the paragraph is stati
cally positioned, so its containing block is <section> because it's the nearest ancestor that is a block container.
Center an element - CSS: Cascading Style Sheets
centering both horizontally and verti
cally was difficult before flexbox, with the box alignment properties it is now straightforward.
... requirements to place an item into the center of another box horizontally and verti
cally.
Pagination - CSS: Cascading Style Sheets
requirements the pagination pattern typi
cally displays items in a row.
... typi
cally, the pagination component will be centered horizontally underneath the content.
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
this is, basi
cally, a thin strip of wallpaper that could be stretched across the entire height of a block.
... source: one specified dimension with intrinsic ratio when a dimension is specified, rule 1 applies that dimension from the svg to the rendered background unless specifi
cally overridden by the css.
Specificity - CSS: Cascading Style Sheets
although techni
cally !important has nothing to do with specificity, it interacts directly with it.
...will also render as: this is because the h1 selector targets the element specifi
cally, but the green selector is only inherited from its parent.
border-image - CSS: Cascading Style Sheets
if the image contains information critical to understanding the page's overall purpose, it is better to describe it semanti
cally in the document.
...the source for the border image is a ".png" file of 81 by 81 pixels, with three diamonds going verti
cally and horizontally: html <div id="bitmap">this element is surrounded by a bitmap-based border image!</div> css to match the size of a single diamond, we will use a value of 81 divided by 3, or 27, for slicing the image into corner and edge regions.
bottom - CSS: Cascading Style Sheets
auto specifies that: for absolutely positioned elements, the position of the element is based on the top property, while height: auto is treated as a height based on the content; or if top is also auto, the element is positioned where it should verti
cally be positioned if it were a static element.
... for relatively positioned elements, the distance of the element from its normal position is based on the top property; or if top is also auto, the element is not moved verti
cally at all.
column-span - CSS: Cascading Style Sheets
/* keyword values */ column-span: none; column-span: all; /* global values */ column-span: inherit; column-span: initial; column-span: unset; an element that spans more than one column is
called a spanning element.
...content in the normal flow that appears before the element is automati
cally balanced across all columns before the element appears.
conic-gradient() - CSS: Cascading Style Sheets
why is it
called a "conic" gradient?
...if the image contains information critical to understanding the page's overall purpose, it is better to describe it semanti
cally in the document.
font-optical-sizing - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | none examples disabling optical sizing <p class="optical-sizing">this paragraph is opti
cally sized.
... this is the default across browsers.</p> <p class="no-optical-sizing">this paragraph is not opti
cally sized.
font-size - CSS: Cascading Style Sheets
the em is a very useful unit in css, since it automati
cally adapts its length relative to the font that the reader chooses to use.
...this is often
called compounding.
hyphens - CSS: Cascading Style Sheets
it can prevent hyphenation entirely, hyphenate at manually-specified points within the text, or let the browser automati
cally insert hyphens where appropriate.
... auto the browser is free to automati
cally break words at appropriate hyphenation points, following whatever rules it chooses.
image() - CSS: Cascading Style Sheets
the #xywh=#,#,#,# media fragment syntax is 'backwards compatible' in that a media fragment will be ignored if not understood, and won't break the source
call when used with url().
...if the image contains information critical to understanding the page's overall purpose, it is better to describe it semanti
cally in the document.
<length> - CSS: Cascading Style Sheets
rem represents the font-size of the root element (typi
cally <html>).
... rlh equal to the computed value of the line-height property on the root element (typi
cally <html>), converted to an absolute length.
max-block-size - CSS: Cascading Style Sheets
<p>writing mode <code>horizontal-tb</code> (the default):</p> <div class="standard-box horizontal">
call me ishmael.
...</div> <p>writing mode <code>vertical-rl</code>:</p> <div class="standard-box vertical">
call me ishmael.
overscroll-behavior-block - CSS: Cascading Style Sheets
the outer box has a large height set on it so the page will scroll verti
cally.
... the inner box has a small width (and height) set on it so it sits comforably inside the viewport, but its content is given a large height so it will also scroll verti
cally.
top - CSS: Cascading Style Sheets
auto specifies that: for absolutely positioned elements, the position of the element is based on the bottom property, while height: auto is treated as a height based on the content; or if bottom is also auto, the element is positioned where it should verti
cally be positioned if it were a static element.
... for relatively positioned elements, the distance of the element from its normal position is based on the bottom property; or if bottom is also auto, the element is not moved verti
cally at all.
touch-action - CSS: Cascading Style Sheets
applications using touch events disable the browser handling of gestures by
calling preventdefault(), but should also use touch-action to ensure the browser knows the intent of the application before any event listeners have been invoked.
...this means that in practice, touch-action is typi
cally applied only to top-level elements which have some custom behavior, without needing to specify touch-action explicitly on any of that element's descendants.
WAI ARIA Live Regions/API Support - Developer guides
if the screen reader automati
cally reads too much, then the web page will be too annoying to use.
... key presses yes mouse clicks yes mouse hovers no page load events no everything else, including focus changes, timer
callbacks, xmlhttprequest
callbacks, etc.
Event developer guide - Developer guides
the events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be
called and the manner in which that sequence can be controlled.
...such events are commonly
called synthetic events, as opposed to the events fired by the browser itself.dom on-event handlersthe web platform provides several ways to get notified of dom events.
Content categories - Developer guides
flow content elements belonging to the flow content category typi
cally contain text or embedded content.
... interactive content interactive content includes elements that are specifi
cally designed for user interaction.
HTML5 - Developer guides
this set is sometimes
called html5 & friends and often shortened to just html5.
... offline and storage: allowing webpages to store data on the client-side lo
cally and operate offline more efficiently.
Index - Developer guides
such events are commonly
called synthetic events, as opposed to the events fired by the browser itself.
... 28 guide to web apis api, guide, landing, web the web includes a wide array of apis that can be used from javascript to build increasingly more powerful and capable applications, running either on the web, lo
cally, or through technology such as node.js, on a server.
Printing - Developer guides
open and automati
cally close a popup window when finished if you want to be able to automati
cally close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>javascript window close example </title> <script type="text/javascr...
...you can also try changing the code to use <code>beforeprint</code> to see the difference.</p> <p><a href="javascript: popuponclick()">open popup window</a></p> </body> </html> view live examples print an external page without opening it if you want to be able to print an external page without opening it, you can utilize a hidden <iframe> (see: htmliframeelement), automati
cally removing it after the user prints its contents.
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
usage notes heading information may be used by user agents, for example, to construct a table of contents for a document automati
cally.
...ry-navigation"> <h2 id="primary-navigation">primary navigation</h2> <!-- navigation items --> </nav> </header> <!-- page content --> <footer> <nav aria-labelledby="footer-navigation"> <h2 id="footer-navigation">footer navigation</h2> <!-- navigation items --> </nav> </footer> in this example, screen reading technology would announce that there are two <nav> sections, one
called "primary navigation" and one
called "footer navigation".
<basefont> - HTML: Hypertext Markup Language
if no font listed is installed on the local system, the browser typi
cally defaults to the proportional or fixed-width font for that system.
...further, browsers, and even successive versions of browsers, never implemented it in the same way: practi
cally, using it has always brought indeterminate results.
<i>: The Idiomatic Text element - HTML: Hypertext Markup Language
histori
cally, these have been presented using italicized type, which is the original source of the <i> naming of this element.
...a browser will typi
cally still display the contents of the <i> element in italic type, but is, by definition, no longer required to do so.
<input type="date"> - HTML: Hypertext Markup Language
n>september</option> <option>october</option> <option>november</option> <option>december</option> </select> </span> <span> <label for="year">year:</label> <select id="year" name="year"> </select> </span> </div> </form> the months are hardcoded (as they are always the same), while the day and year values are dynami
cally generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.) span { padding-left: 5px; } input:invalid + span::after { content: '✖'; } input:valid + span::after { content: '✓'; } javascript the other part of the code that may be of interest is the feature detection code —...
...ocument.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.display = 'block'; // populate the days and years dynami
cally // (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 t...
<input type="file"> - HTML: Hypertext Markup Language
grab the filelist object that contains the information on all the selected files, and store it in a variable
called curfiles.
... generate a thumbnail preview of the image by
calling url.createobjecturl(curfiles[i]).
<input type="month"> - HTML: Hypertext Markup Language
the list of available year values is dynami
cally generated depending on the current year (see the code comments below for detailed explanations of how these functions work).
...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 dynami
cally // (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 = yea...
<input type="reset"> - HTML: Hypertext Markup Language
<input type="reset" value="reset the form"> if you don't specify a value, you get an button with the default label (typi
cally "reset," but this will vary depending on the user agent): <input type="reset"> using reset buttons <input type="reset"> buttons are used to reset forms.
...this is especially true since the modifiers are typi
cally non-standard to avoid conflicts.
<input type="text"> - HTML: Hypertext Markup Language
it is not as semanti
cally useful as other ways to explain your form, and can cause unexpected technical issues with your content.
...look at the following example: <form> <div> <label for="uname">choose a username: </label> <input type="text" id="uname" name="name" placeholder="lower case, all one word"> </div> <div> <button>submit</button> </div> </form> you can see how the placeholder is rendered below: the placeholder is typi
cally rendered in a lighter color than the element's foreground color, and automati
cally vanishes when the user begins to enter text into the field (or whenever the field has a value set programmati
cally by setting its value attribute.
<input type="time"> - HTML: Hypertext Markup Language
/p> <div class="fallbacktimepicker"> <div> <span> <label for="hour">hour:</label> <select id="hour" name="hour"> </select> </span> <span> <label for="minute">minute:</label> <select id="minute" name="minute"> </select> </span> </div> </div> </form> the hour and minutes values for their <select> elements are dynami
cally generated.
...ment.createelement('input'); try { test.type = 'time'; } 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 hours and minutes dynami
cally populatehours(); populateminutes(); } function populatehours() { // populate the hours <select> with the 6 open hours of the day for(var i = 12; i <= 18; i++) { var option = document.createelement('option'); option.textcontent = i; hourselect.appendchild(option); } } function populateminutes() { // populate the minutes <select> with the 60 minutes of each hour for(var...
<label> - HTML: Hypertext Markup Language
associating a <label> with an <input> element offers some major advantages: the label text is not only visually associated with its corresponding text input; it is programmati
cally associated with it too.
... <input type="checkbox" name="peas"> </label> other usage notes: the form control that the label is labeling is
called the labeled control of the label element.
<summary>: The Disclosure Summary element - HTML: Hypertext Markup Language
default label text if a <details> element's first child is not a <summary> element, the user agent will use a default string (typi
cally "details") as the label for the disclosure box.
...this makes it possible to change or remove the icon displayed as the disclosure widget next to the label from the default, which is typi
cally a triangle.
autocapitalize - HTML: Hypertext Markup Language
the autocapitalize global attribute is an enumerated attribute that controls whether and how text input is automati
cally capitalized as it is entered/edited by the user.
...the behavior of such mechanisms is that they often assist users by automati
cally capitalizing the first letter of sentences.
style - HTML: Hypertext Markup Language
even if all styling is removed, a page should remain semanti
cally correct.
... typi
cally it shouldn't be used to hide irrelevant information; this should be done using the hidden attribute.
tabindex - HTML: Hypertext Markup Language
the user won't be able to focus any element with a negative tabindex using the keyboard, but a script can do so by
calling the focus() method.
...the content should be semanti
cally described using interactive elements (<a>, <button>, <details>, <input>, <select>, <textarea>, etc.) instead.
Inline elements - HTML: Hypertext Markup Language
html (hypertext markup language) elements histori
cally were categorized as either "block-level" elements or "inline-level" elements.
...block elements, on the other hand, typi
cally cause a line break to occur (although, as usual, this can be changed using css).
Link types - HTML: Hypertext Markup Language
<a>, <area>, <form> <link> pingback defines an external resource uri to
call if one wishes to make a comment or a citation about the webpage.
... the protocol used to make such a
call is defined in the pingback 1.0 specification.
Microdata - HTML: Hypertext Markup Language
the groups are
called items, and each name-value pair is a property.
... localization in some cases, search engines covering specific regions may provide lo
cally-specific extensions of microdata.
Microformats - HTML: Hypertext Markup Language
hierarchical data is represented with nested microformats, typi
cally as property values themselves.
...the "e-" prefix can also be mnemoni
cally remembered as "element tree", "embedded markup", or "encapsulated markup".
Reason: CORS header 'Access-Control-Allow-Origin' missing - HTTP
to allow any site to make cors requests without using the * wildcard (for example, to enable credentials), your server must read the value of the request's origin header and use that value to set access-control-allow-origin, and must also set a vary: origin header to indicate that some headers are being set dynami
cally depending on the origin.
...the configuration is typi
cally found in a .conf file (httpd.conf and apache.conf are common names for these), or in an .htaccess file.
Using HTTP cookies - HTTP
typi
cally, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example.
...if this domain is the same as the domain of the page you are on, the cookie is
called a first-party cookie.
Feature Policy - HTTP
inferring the policy scripts can programati
cally query information about the feature policy via the featurepolicy object located at either document.featurepolicy or htmliframeelement.featurepolicy.
...existing features that later integrate with feature policy will typi
cally use existing mechanisms.
Accept-Charset - HTTP
if the server cannot serve any character encoding from this request header, it can theoreti
cally send back a 406 not acceptable error code.
... ;q=<weight> any encoding is placed in an order of preference, expressed using a relative quality value
called the weight.
Accept-Encoding - HTTP
typi
cally, microsoft recommends not to compress if a server uses more than 80% of its computational power.
... ;q= (qvalues weighting) any value is placed in an order of preference expressed using a relative quality value
called weight.
Accept-Language - HTTP
if the server cannot serve any matching language, it can theoreti
cally send back a 406 (not acceptable) error code.
... ;q= (q-factor weighting) any value placed in an order of preference expressed using a relative quality value
called weight.
CSP: script-src - HTTP
some browsers specifi
cally exclude blob and filesystem from source directives.
... examples violation case given this csp header: content-security-policy: script-src https://example.com/ the following script is blocked and won't be loaded or executed: <script src="https://not-example.com/js/library.js"></script> note that inline event handlers are blocked as well: <button id="btn" onclick="dosomething()"> you should replace them with addeventlistener
calls: document.getelementbyid("btn").addeventlistener('click', dosomething); unsafe inline script note: disallowing inline styles and inline scripts is one of the biggest security wins csp provides.
Set-Cookie - HTTP
when
calling xmlhttprequest.send() or fetch().
... lax: the cookie is withheld on cross-site subrequests, such as
calls to load images or frames, but is sent when a user navigates to the url from an external site, such as by following a link.
Link prefetching FAQ - HTTP
this header is typi
cally generated by webservers when serving up static content.
... basi
cally, there are two ways of looking at this issue: websites can already cause things to be silently downloaded using js/dom hacks.
POST - HTTP
the difference between put and post is that put is idempotent:
calling it once or several times successively has the same effect (that is no side effect), where successive identical post may have additional effects, like passing an order several times.
... a post request is typi
cally sent via an html form and results in a change on the server.
Proxy servers and tunneling - HTTP
the http protocol specifies a request method
called connect.
...the javascript function contained in the pac file defines the function: the auto-config file should be saved to a file with a .pac filename extension: proxy.pac and the mime type set to: application/x-ns-proxy-autoconfig the file consists of a function
called findproxyforurl.
A typical HTTP session - HTTP
to work around this problem, web developers use several techniques: ping the server periodi
cally via the xmlhttprequest, fetch apis, using the websockets api, or similar protocols.
... sending a client request once the connection is established, the user-agent can send the request (a user-agent is typi
cally a web browser, but can be anything else, a crawler, for example).
HTTP response status codes - HTTP
this is typi
cally the response sent after post requests, or some put requests.
... 401 unauthorized although the http standard specifies "unauthorized", semanti
cally this response means "unauthenticated".
Equality comparisons and sameness - JavaScript
but most browsers permit a very narrow class of objects (specifi
cally, the document.all object for any page), in some contexts, to act as if they emulate the value undefined.
...however, since typed arrays are available, we can have distinct instances, which don't behave identi
cally in all contexts.
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.
...once remembered, the substring can be re
called for other use.
extends - JavaScript
examples using extends the first example creates a class
called square from a class
called polygon.
... class square extends polygon { constructor(length) { // here, it
calls the parent class' constructor with lengths // provided for the polygon's width and height super(length, length); // note: in derived classes, super() must be
called before you // can use 'this'.
Deprecated and obsolete features - JavaScript
function properties the
caller and arguments properties are deprecated, because they leak the function
caller.
... object.getnotifier() creates an object that allows to syntheti
cally trigger a change.
TypeError: can't define property "x": "obj" is not extensible - JavaScript
'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.
... var obj = { }; object.preventextensions(obj); object.defineproperty(obj, 'x', { value: "foo" } ); // typeerror: can't define property "x": "obj" is not extensible to fix this error, you will either need to remove the
call to object.preventextensions() entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible.
TypeError: "x" is read-only - JavaScript
(techni
cally, it is a non-writable data property.) this error happens only in strict mode code.
...ined 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 (anatomi
cally unlikely, though) ...
JavaScript error reference - JavaScript
nvalid array lengthrangeerror: invalid daterangeerror: precision is out of rangerangeerror: radix must be an integerrangeerror: repeat count must be less than infinityrangeerror: repeat count must be non-negativereferenceerror: "x" is not definedreferenceerror: assignment to undeclared variable "x"referenceerror: can't access lexical declaration "x" before initializationreferenceerror: deprecated
caller or arguments usagereferenceerror: invalid assignment left-hand sidereferenceerror: reference to undefined property "x"syntaxerror: "0"-prefixed octal literals and octal escape seq.
...mistyped as assignment (=)?syntaxerror: unterminated string literaltypeerror: "x" has no propertiestypeerror: "x" is (not) "y"typeerror: "x" is not a constructortypeerror: "x" is not a functiontypeerror: "x" is not a non-null objecttypeerror: "x" is read-onlytypeerror: 'x' is not iterabletypeerror: more arguments neededtypeerror: reduce of empty array with no initial valuetypeerror: x.prototype.y
called on incompatible typetypeerror: can't access dead objecttypeerror: can't access property "x" of "y"typeerror: can't assign to property "x" on "y": not an objecttypeerror: can't define property "x": "obj" is not extensibletypeerror: can't delete non-configurable array elementtypeerror: can't redefine non-configurable property "x"typeerror: cannot use "in" operator to search for "x" in "y"typeerro...
Rest parameters - JavaScript
formally defined in function expression), while the arguments object contains all arguments passed to the function; the arguments object is not a real array, while rest parameters are array instances, meaning methods like sort, map, foreach or pop can be applied on it directly; the arguments object has additional functionality specific to itself (like the
callee property).
... from arguments to an array rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments // before rest parameters, "arguments" could be converted to a normal array using: function f(a, b) { let normalarray = array.prototype.slice.
call(arguments) // -- or -- let normalarray = [].slice.
call(arguments) // -- or -- let normalarray = array.from(arguments) let first = normalarray.shift() // ok, gives the first argument let first = arguments.shift() // error (arguments is not a normal array) } // now, you can easily gain access to a normal array using a rest parameter function f(...args) { let normalarray = args let first = normalarray.shift() // ok, gives the first argument } examples using rest parameters in this example, ...
Array.prototype.concat() - JavaScript
if all valuen parameters are omitted, concat returns a shallow copy of the existing array on which it is
called.
... description the concat method creates a new array consisting of the elements in the object on which it is
called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array).
Array.prototype.join() - JavaScript
var a = ['wind', 'water', 'fire']; a.join(); // 'wind,water,fire' a.join(', '); // 'wind, water, fire' a.join(' + '); // 'wind + water + fire' a.join(''); // 'windwaterfire' joining an array-like object the following example joins array-like object (arguments), by
calling function.prototype.
call on array.prototype.join.
... function f(a, b, c) { var s = array.prototype.join.
call(arguments); console.log(s); // '1,a,true' } f(1, 'a', true); //expected output: "1,a,true" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.join' in that specification.
Array.prototype.sort() - JavaScript
if comparefunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no
call to comparefunction).
...i) { return { index: i, value: el.tolowercase() }; }) // sorting the mapped array containing the reduced values mapped.sort(function(a, b) { if (a.value > b.value) { return 1; } if (a.value < b.value) { return -1; } return 0; }); // container for the resulting order var result = mapped.map(function(el){ return list[el.index]; }); there is an open source library available
called mapsort which applies this approach.
Array.prototype.toSource() - JavaScript
this method is usually
called internally by javascript and not explicitly in code.
... you can
call tosource while debugging to examine the contents of an array.
Array.prototype.toString() - JavaScript
javascript
calls the tostring method automati
cally when an array is to be represented as a text value or when an array is referred to in a string concatenation.
...object.prototype.tostring() will be
called, and the resulting value will be returned.
ArrayBuffer() constructor - JavaScript
calling an arraybuffer constructor as a function without new, will throw a typeerror from now on.
... var dv = arraybuffer(10); // typeerror:
calling a builtin arraybuffer constructor // without new is forbidden var dv = new arraybuffer(10); examples creating an arraybuffer in this example, we create a 8-byte buffer with a int32array view referring to the buffer: var buffer = new arraybuffer(8); var view = new int32array(buffer); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer' in that specification.
AsyncFunction - JavaScript
this is less efficient than declaring an async function with an async function expression and
calling it within your code, because such functions are parsed with the rest of the code.
... when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the asyncfunction constructor was
called.
Atomics - JavaScript
wait and notify the wait() and notify() methods are modeled on linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typi
cally used as blocking constructs.
...if waiting is not allowed in the
calling agent then it throws an error exception.
BigInt64Array - JavaScript
bigint64array.prototype.foreach()
calls a function for each element in the array.
... bigint64array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
BigUint64Array - JavaScript
biguint64array.prototype.foreach()
calls a function for each element in the array.
... biguint64array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Date.prototype.toString() - JavaScript
the tostring() method is automati
cally
called when a date is to be represented as a text value, e.g.
...if
called on a non–date instance, a typeerror is thrown.
FinalizationRegistry.prototype.register() - JavaScript
the register() method registers an object with a finalizationregistry instance so that if the object is garbage-collected, the registry's
callback may get
called.
... notes see the avoid where possible and notes on cleanup
callbacks sections of the finalizationregistry page for important caveats.
Float32Array - JavaScript
float32array.prototype.foreach()
calls a function for each element in the array.
... float32array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Float64Array - JavaScript
float64array.prototype.foreach()
calls a function for each element in the array.
... float64array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Function.arguments - JavaScript
if function f appears several times on the
call stack, the value of f.arguments represents the arguments corresponding to the most recent invocation of the function.
... the value of the arguments property is normally null if there is no outstanding invocation of the function in progress (that is, the function has been
called but has not yet returned.
Generator.prototype.next() - JavaScript
.next(); // object {value: (3) [1, 2, 3], done: false} page.next(); // object {value: (3) [4, 5, 6], done: false} page.next(); // object {value: (2) [7, 8], done: false} page.next(); // object {value: undefined, done: true} sending values to the generator in this example, next is
called with a value.
... note that the first
call does not log anything, because the generator was not yielding anything initially.
GeneratorFunction - JavaScript
this is less efficient than declaring a generator function with a function* expression and
calling it within your code, because such functions are parsed with the rest of the code.
... when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the generatorfunction constructor was
called.
Int16Array - JavaScript
int16array.prototype.foreach()
calls a function for each element in the array.
... int16array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Int32Array - JavaScript
int32array.prototype.foreach()
calls a function for each element in the array.
... int32array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Int8Array - JavaScript
int8array.prototype.foreach()
calls a function for each element in the array.
... int8array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Intl.Locale.prototype.minimize() - JavaScript
the intl.locale.prototype.minimize() method attempts to remove information about the locale that would be added by
calling locale.maximize().
...other subtags after the "-u" in the locale indentifier are
called extension subtags and are not affected by the minimize() method.
Intl.Locale.prototype.script - JavaScript
description a script, sometimes
called writing system, is one of the core attributes of a locale.
...for instance, the script associated with english is latin, whereas the script typi
cally associated with korean is hangul.
Intl - JavaScript
static methods intl.getcanoni
callocales() returns canonical locale names.
... this registry is periodi
cally updated over time, and implementations may not always be up to date, so be careful not to rely too much on tags being universally supported.
Math.imul() - JavaScript
opa will automati
cally be coerced.
... // floating points give us 53 bits of precision to work with plus 1 sign bit // automati
cally handled for our convienence: // 1.
Object.prototype.__defineSetter__() - JavaScript
the __definesetter__ method binds an object's property to a function to be
called when an attempt is made to set that property.
... fun a function to be
called when there is an attempt to set the specified property.
Object.defineProperties() - JavaScript
polyfill assuming a pristine execution environment with all names and properties referring to their initial values, object.defineproperties is almost completely equivalent (note the comment in is
callable) to the following reimplementation in javascript: function defineproperties(obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.
call(obj, prop); } function is
callable(v) { // nb: modify as necessary if other values than functions are
callable.
... 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 = desc.get; if (!is
callable(g) && typeof g !== 'undefined') throw new typeerror('bad get'); d.get = g; } if (hasproperty(desc, 'set')) { var s = desc.set; if (!is
callable(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 desc...
Object.freeze() - JavaScript
the result of
calling object.freeze(object) only applies to the immediate properties of object itself and will prevent future property addition, removal or value re-assignment operations only on object.
...an array) argument so you can suppress
calling deepfreeze() recursively when an object is in the process of being made immutable.
handler.construct() - JavaScript
newtarget the constructor that was originally
called, p above.
... const p = new proxy(function() {}, { construct: function(target, argumentslist, newtarget) { console.log('
called: ' + argumentslist.join(', ')); return { value: argumentslist[0] * 10 }; } }); console.log(new p(1).value); // "
called: 1" // 10 the following code violates the invariant.
handler.set() - JavaScript
but a set() handler can also be
called indirectly, via the prototype chain or various other ways.
...that proxy's set() handler will be
called, and obj will be passed as the receiver.
Proxy() constructor - JavaScript
handler functions are sometimes
called traps, because they trap
calls to the underlying target object.
... handler.apply() a trap for a function
call.
Proxy - JavaScript
handler functions are sometimes
called traps, presumably because they trap
calls to the target object.
...the object also supports an extra property
called latestbrowser both as a getter and a setter.
SharedArrayBuffer() constructor - JavaScript
calling a sharedarraybuffer constructor as a function without new will throw a typeerror.
... var sab = sharedarraybuffer(1024); // typeerror:
calling a builtin sharedarraybuffer constructor // without new is forbidden var sab = new sharedarraybuffer(1024); specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer constructor' in that specification.
SharedArrayBuffer - JavaScript
calling a sharedarraybuffer constructor as a function without new will throw a typeerror.
... var sab = sharedarraybuffer(1024); // typeerror:
calling a builtin sharedarraybuffer constructor // without new is forbidden var sab = new sharedarraybuffer(1024); constructor sharedarraybuffer() creates a new sharedarraybuffer object.
String.prototype.concat() - JavaScript
the concat() method concatenates the string arguments to the
calling string and returns a new string.
... description the concat() function concatenates the string arguments to the
calling string and returns a new string.
String.prototype.indexOf() - JavaScript
the indexof() method returns the index within the
calling string object of the first occurrence of the specified value, starting the search at fromindex.
...the index of the first character is 0, and the index of the last character of a string
called stringname is stringname.length - 1.
String.prototype.matchAll() - JavaScript
examples regexp.exec() and matchall() prior to the addition of matchall to javascript, it was possible to use
calls to regexp.exec (and regexes with the /g flag) in a loop to obtain all the matches: const regexp = regexp('foo[a-z]*','g'); const str = 'table football, foosball'; let match; while ((match = regexp.exec(str)) !== null) { console.log(`found ${match[0]} start=${match.index} end=${regexp.lastindex}.`); // expected output: "found football start=6 end=14." // expected output: "found foosball s...
...xp('foo[a-z]*','g'); const str = '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.
String.prototype.replace() - JavaScript
the pattern can be a string or a regexp, and the replacement can be a string or a function to be
called for each match.
... description this method does not change the
calling string object.
String.prototype.toLocaleLowerCase() - JavaScript
the tolocalelowercase() method returns the
calling string value converted to lower case, according to any locale-specific case mappings.
... return value a new string representing the
calling string converted to lower case, according to any locale-specific case mappings.
String.prototype.toLocaleUpperCase() - JavaScript
the tolocaleuppercase() method returns the
calling string value converted to upper case, according to any locale-specific case mappings.
... return value a new string representing the
calling string converted to upper case, according to any locale-specific case mappings.
String.prototype.toLowerCase() - JavaScript
the tolowercase() method returns the
calling string value converted to lower case.
... syntax str.tolowercase() return value a new string representing the
calling string converted to lower case.
String.prototype.toSource() - JavaScript
syntax string.tosource() str.tosource() return value a string representing the source code of the
calling object.
... this method is usually
called internally by javascript and not explicitly in web code.
Symbol.prototype[@@toPrimitive] - JavaScript
javascript
calls the [@@toprimitive]() method to convert an object to a primitive value.
... you rarely need to invoke the [@@toprimitive]() method yourself; javascript automati
cally invokes it when encountering an object where a primitive value is expected.
Symbol.for() - JavaScript
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.
... examples using symbol.for symbol.for('foo'); // create a new global symbol symbol.for('foo'); // retrieve the already created symbol // same global symbol, but not lo
cally symbol.for('bar') === symbol.for('bar'); // true symbol('bar') === symbol('bar'); // false // the key is also used as the description var sym = symbol.for('mario'); sym.tostring(); // "symbol(mario)" to avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols: symbol.for('mdn.foo'); symbol.for('mdn.bar'); specif...
Symbol.matchAll - JavaScript
this function is
called by the string.prototype.matchall() method.
... description this symbol is used for string.prototype.matchall() and specifi
cally in regexp.prototype[@@matchall]().
Symbol.toPrimitive - JavaScript
the symbol.toprimitive is a symbol that specifies a function valued property that is
called to convert an object to a corresponding primitive value.
...the function is
called with a string argument hint, which specifies the preferred type of the result primitive value.
Symbol.prototype.valueOf() - JavaScript
javascript
calls the valueof method to convert an object to a primitive value.
... you rarely need to invoke the valueof method yourself; javascript automati
cally invokes it when encountering an object where a primitive value is expected.
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 automati
cally 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.
Uint16Array - JavaScript
uint16array.prototype.foreach()
calls a function for each element in the array.
... uint16array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Uint32Array - JavaScript
uint32array.prototype.foreach()
calls a function for each element in the array.
... uint32array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Uint8Array - JavaScript
uint8array.prototype.foreach()
calls a function for each element in the array.
... uint8array.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
Uint8ClampedArray - JavaScript
uint8clampedarray.prototype.foreach()
calls a function for each element in the array.
... uint8clampedarray.prototype.map() creates a new array with the results of
calling a provided function on every element in this array.
WebAssembly.Instance - JavaScript
instance objects contain all the exported webassembly functions that allow
calling into webassembly code from javascript.
... examples 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.expor...
WebAssembly.Table() constructor - JavaScript
so after instantiation, the table still has length 2, but the elements now contain
callable exported webassembly functions which we can
call from js.
... this example shows that we're creating and accessing the table from javascript, but the same table is visible and
callable inside the wasm instance too.
WebAssembly.Table - JavaScript
so after instantiation, the table still has length 2, but the elements now contain
callable exported webassembly functions which we can
call from js.
... this example shows that we're creating and accessing the table from javascript, but the same table is visible and
callable inside the wasm instance too.
Standard built-in objects - JavaScript
infinity nan undefined globalthis function properties these global functions—functions which are
called globally, rather than on an object—directly return their results to the
caller.
... arraybuffer sharedarraybuffer atomics dataview json control abstraction objects control abstractions can help to structure code, especially async code (without using deeply nested
callbacks, for example).
Iteration protocols - JavaScript
whenever an object needs to be iterated (such as at the beginning of a for...of loop), its @@iterator method is
called with no arguments, and the returned iterator is used to obtain the values to be iterated.
... note that when this zero-argument function is
called, it is invoked as a method on the iterable object.
Lexical grammar - JavaScript
his can make your code harder to read so it should be used with caution: function comment(x) { console.log('hello ' + x /* insert the value of x */ + ' !'); } comment('world'); in addition, you can use it to disable code to prevent it from running, by wrapping code in a comment, like this: function comment() { /* console.log('hello world!'); */ } comment(); in this case, the console.log()
call is never issued, since it's inside a comment.
...identifiernames are used for memberexpression,
callexpression and so on.
Destructuring assignment - JavaScript
however, if you leave out the right-hand side assignment, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can simply
call drawchart() without supplying any parameters.
... the current design is useful if you want to be able to
call the function without supplying any parameters, the other can be useful when you want to ensure an object is passed to the function.
await - JavaScript
an await can split execution flow, allowing the
caller of the await's function to resume execution before the deferred continuation of the await's function.
... after the await defers the continuation of its function, if this is the first await executed by the function, immediate execution also continues by returning to the function's
caller a pending promise for the completion of the await's function and resuming execution of that
caller.
Function expression - JavaScript
this also avoids using the non-standard arguments.
callee property.
...the function returns the square of its argument: var x = function(y) { return y * y; }; using a function as a
callback more commonly it is used as a
callback: button.addeventlistener('click', function(event) { console.log('button is clicked!') }) using an immediately executed function expression an anonymous function is created and
called: (function() { console.log('code runs!') })(); specifications specification ecmascript (ecma-262)the definition of 'function definitio...
instanceof - JavaScript
components.interfaces.nsifile)
calls obj.queryinterface(xpcominterface) and returns true if queryinterface succeeded.
... a side effect of such
call is that you can use xpcominterface's properties on obj after a successful instanceof test.
export - JavaScript
bindings that are exported can still be modified lo
cally; when imported, although they can only be read by the importing module the value updates whenever it is updated by the exporting module.
... note: the following is syntacti
cally invalid despite its import equivalent: import defaultexport from 'bar.js'; // valid export defaultexport from 'bar.js'; // invalid the correct way of doing this is to rename the export: export { default as defaultexport } from 'bar.js'; examples using named exports in a module my-module.js, we could include the following code: // module "my-module.js" function cube(x) { return x * x...
for - JavaScript
typi
cally used to initialize a counter variable.
... var nleft = 0, ntop = 0; for ( var oitnode = document.getelementbyid(sid); /* initialization */ oitnode; /* condition */ nleft += oitnode.offsetleft, ntop += oitnode.offsettop, oitnode = oitnode.offsetparent /* final-expression */ ); /* semicolon */ console.log('offset position of \'' + sid + '\' element:\n left: ' + nleft + 'px;\n top: ' + ntop + 'px;'); } /* example
call: */ showoffsetpos('content'); // output: // "offset position of "content" element: // left: 0px; // top: 153px;" note: this is one of the few cases in javascript where the semicolon is mandatory.
let - JavaScript
description let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or lo
cally to an entire function regardless of block scope.
...hing.prototype.showprivate = function() { return privatescope.get(this).hidden; }; } console.log(typeof privatescope); // "undefined" var thing = new thing(); console.log(thing); // thing {someproperty: "foo"} thing.showpublic(); // "foo" thing.showprivate(); // 1 the same privacy pattern with closures over local variables can be created with var, but those need a function scope (typi
cally an iife in the module pattern) instead of just a block scope like in the example above.
throw - JavaScript
execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the
call stack.
... if no catch block exists among
caller functions, the program will terminate.
with - JavaScript
so given this example: function f(x, o) { with (o) { console.log(x); } } only when f is
called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument.
...consider this example: function f(foo, values) { with (foo) { console.log(values); } } if you
call f([1,2,3], obj) in an ecmascript 5 environment, then the values reference inside the with statement will resolve to obj.
Web app manifests
web app manifests are part of a collection of web technologies
called progressive web apps (pwas), which are websites that can be installed to a device’s homescreen without an app store.
...this splashscreen is auto-generated from properties in the web app manifest, specifi
cally: name background_color the icon in the icons array that is closest to 128dpi for the device.
<mo> - MathML
that is, although the names suggest the typographic style for the class, semanti
cally, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography.
... symmetric if stretchy is true, this attribute specifies whether the operator should be verti
cally symmetric around the imaginary math axis (centered fraction line).
Animation performance and frame rate - Web Performance
this operation is labeled "layout" but is also sometimes
called "reflow".
...one last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process
called "composition".
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
synthetic monitoring synthetic monitoring involves monitoring the performance of a page in a 'laboratory' environment, typi
cally with automation tooling in a consistent as possible environment.
...the traffic measured is not of your actual users, but rather syntheti
cally generated traffic collecting data on page performance.
Introduction to progressive web apps - Progressive web apps (PWAs)
a look and feel that is more integrated with the native platform—app icons on the home screen or app launcher, applications that automati
cally run in full screen mode, etc.
... modern web apps can have this native app feel via properties set inside the web app manifest, and via a feature available in modern smartphone browsers
called web app installation.
Responsive Navigation Patterns - Progressive web apps (PWAs)
pros: one button in header maximizes space for content on a small screen important items stay visiblein most screen sizes and you decide the item priorities legibility of navigation items is maintained with adequate spacing, by automati
cally hiding items that don't fit cons: navigation items might be less discoverable because some items are hidden in the drop-down or toggle menu users may not notice the button contains a navigation menu in the smallest screen size one more step is needed to access the hidden navigation items pattern 2: expandable bottom menu similar to the first pattern, the top navigation ite...
... pros: expandable menu is easy to discover important items are always visible and you decide the item priorities legibility of navigation items is maintained with adequate spacing, by automati
cally hiding items that don't fit cons: one more step is needed to access the navigation items that are hidden navigation items might be less discoverable because some items are hidden less space for content in the smallest screen size pattern 3: left hidden menu the main navigation is always on the left except in the smallest screen size, where the navigation menu is hidden in ...
Progressive web apps (PWAs)
in order to
call a web app a pwa, techni
cally speaking it should have the following features: secure contexts (https), one or more service workers, and a manifest file.
...but instead of relying only on user actions, we can do more, using push messages and notifications to automati
cally 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.
Web technology reference
html — structuring the web hypertext markup language is used to define and describe semanti
cally the content (markup) of a web page in a well-structured format.
... html provides a means to create structured documents made up of blocks
called html elements that are delineated by tags, written using angle brackets.
begin - SVG: Scalable Vector Graphics
indefinite the begin of the animation will be determined by a beginelement() method
call or a hyperlink targeted to the element.
...the behavior is the same as if node.removechild() were
called on the parent of the target element with the target element as parameter.
d - SVG: Scalable Vector Graphics
the center of the ellipse used to draw the arc is determined automati
cally based on the other parameters of the command: rx and ry are the two radii of the ellipse; angle represents a rotation (in degrees) of the ellipse relative to the x-axis; large-arc-flag and sweep-flag allows to chose which arc must be drawn as 4 possible arcs can be drawn out of the other parameters.
...the center of the ellipse used to draw the arc is determined automati
cally based on the other parameters of the command: rx and ry are the two radii of the ellipse; angle represents a rotation (in degrees) of the ellipse relative to the x-axis; large-arc-flag and sweep-flag allows to chose which arc must be drawn as 4 possible arcs can be drawn out of the other parameters.
kerning - SVG: Scalable Vector Graphics
the kerning attribute indicates whether the spacing between glyphs should be adjusted based on kerning tables that are included in the relevant font (i.e., enable auto-kerning) or instead disable auto-kerning and set the spacing between them to a specific length (typi
cally, zero).
...in css the property is
called font-kerning, though.
textLength - SVG: Scalable Vector Graphics
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.
vert-origin-x - SVG: Scalable Vector Graphics
the vert-origin-x attribute indicates the x-coordinate in the font coordinate system of the origin of a glyph to be used when drawing verti
cally oriented text.
... only one element is using this attribute: <font> usage notes value <number> default value half of horiz-adv-x value animatable no <number> this value indicates the x-coordinate of the origin of a glyph for verti
cally oriented text.
vert-origin-y - SVG: Scalable Vector Graphics
the vert-origin-y attribute indicates the y-coordinate in the font coordinate system of the origin of a glyph to be used when drawing verti
cally oriented text.
... only one element is using this attribute: <font> usage notes value <number> default value ascent value animatable no <number> this value indicates the y-coordinate of the origin of a glyph for verti
cally oriented text.
Content type - SVG: Scalable Vector Graphics
specifi
cally: anything ::= char* where char is the production for a character, as defined in xml 1.0 , section 2.2.
...for example, an svg file
called somedrawing.svg located at http://example.com might have the following iri: http://example.com/somedrawing.svg an iri can also address a particular element within an xml document by including an iri fragment identifier as part of the iri.
Example - SVG: Scalable Vector Graphics
// return this as a 2-tuple (x,y) in an array function dimensions() { // our rendering element var display = display(); var width = parseint( display.getattributens(null,'width') ); var height = parseint( display.getattributens(null,'height') ); return [width,height]; } // this is
called by mouse move events var mouse_x = 200, mouse_y = 150; function onmousemove(evt) { mouse_x = evt.clientx; mouse_y = evt.clienty; var widget = document.getelementbyid('cursor'); widget.setattributens(null,'cx',mouse_x); widget.setattributens(null,'cy',mouse_y); } document.onmousemove = onmousemove; // determine (x,y) of the cursor function cursor() { return [m...
...stroke','green'); this.elt.setattributens(null,'stroke-width','3'); this.elt.setattributens(null,'stroke-opacity','0.5'); display().appendchild( this.elt ); } this.elt.setattributens(null,'x1',old_x); this.elt.setattributens(null,'y1',old_y); this.elt.setattributens(null,'x2',this.x); this.elt.setattributens(null,'y2',this.y); } function update() { // first
call?
Namespaces crash course - SVG: Scalable Vector Graphics
however, instead of setting the default namespace, this namespace declaration sets the namespace for something
called a "namespace prefix".
...for example: elt.setattributens('http://www.w3.org/1999/xlink', 'xlink:href', 'otherdoc.svg'); as a final example, here's a demonstration of how you should dynami
cally create an <image> element using script: var svg_ns = 'http://www.w3.org/2000/svg'; var xlink_ns = 'http://www.w3.org/1999/xlink'; var image = document.createelementns(svg_ns, 'image'); image.setattributens(null, 'width', '100'); image.setattributens(null, 'height', '100'); image.setattributens(xlink_ns, 'xlink:href', 'flower.png'); conclusion make sure you always declare the namespaces you u...
Scripting - SVG: Scalable Vector Graphics
(null,"width",w) this.rect.setattributens(null,"height",h) document.documentelement.appendchild(this.rect) this.rect.addeventlistener("click",this,false) this.handleevent= function(evt){ switch (evt.type){ case "click": alert(this.message) break; } } } inter-document scripting: referencing embedded svg when using svg within html, adobe's svg viewer 3.0 automati
cally includes a window property
called svgdocument that points to the svg document.
... inter-document scripting:
calling javascript functions when
calling a javascript function that resides in the html file from an svg file that is embedded in an html document, you should use parent.functionname() to reference the function.
Specification Deviations - SVG: Scalable Vector Graphics
extending the 'style' attribute to apply to all svg elements should only really be visible to svg authors if they
call viewcss.getcomputedstyle on the element or one of its descendants.
... since these elements and their descendants are not displayed, it seems unlikely that anyone will either specify 'style' or
call getcomputedstyle on them.
Basic shapes - SVG: Scalable Vector Graphics
for polygons though, the path automati
cally connects the last point with the first, creating a closed shape.
...basi
cally any of the other types of shapes, bezier curves, quadratic curves, and many more.
Gradients in SVG - SVG: Scalable Vector Graphics
the second point is
called the focal point and is defined by the fx and fy attributes.
...it essentially scales the gradient to the size of your object, so you only have to specify coordinates in values from zero to one, and they're scaled to the size of your object automati
cally for you.
Positions - SVG: Scalable Vector Graphics
much like absolute and relative font sizes in css, svg defines absolute units (ones with a dimensional identifier like "pt" or "cm") and so-
called user units, that lack that identifier and are plain numbers.
... the current mapping (for a single element or the whole image) of user units to screen units is
called user coordinate system.
Secure contexts - Web security
a particular document is considered to be in a secure context when it is the active document of a top-level browsing context (basi
cally, a containing window or tab) that is a secure context.
... lo
cally-delivered resources such as those with http://127.0.0.1 urls, http://localhost urls (under certain conditions), and file:// urls are also considered to have been delivered securely.
XSLT elements reference - XSLT: Extensible Stylesheet Language Transformations
<xsl:apply-imports><xsl:apply-templates><xsl:attribute-set><xsl:attribute><xsl:
call-template><xsl:choose><xsl:comment><xsl:copy-of><xsl:copy><xsl:decimal-format><xsl:element><xsl:fallback><xsl:for-each><xsl:if><xsl:import><xsl:include><xsl:key><xsl:message><xsl:namespace-alias><xsl:number><xsl:otherwise><xsl:output><xsl:param><xsl:preserve-space><xsl:processing-instruction><xsl:sort><xsl:strip-space><xsl:stylesheet><xsl:template><xsl:text><xsl:transform><xsl:value-of><xsl:variab...
...le><xsl:when><xsl:with-param> <xsl:apply-imports> <xsl:apply-templates> <xsl:attribute> <xsl:attribute-set> <xsl:
call-template> <xsl:choose> <xsl:comment> <xsl:copy> <xsl:copy-of> <xsl:decimal-format> <xsl:element> <xsl:fallback> (not supported) <xsl:for-each> <xsl:if> <xsl:import> (mostly supported) <xsl:include> <xsl:key> <xsl:message> <xsl:namespace-alias> (not supported) <xsl:number> (partially supported) <xsl:otherwise> <xsl:output> (partially supported) <xsl:param> <xsl:preserve-space> <xsl:processing-instruction> <xsl:sort> <xsl:strip-space> <xsl:stylesheet> (partially supported) <xsl:template> <xsl:text> (partially supported) <xsl:transform> <xsl:value-of> (partially supported) <xsl:variable> <xsl:when> <xsl:with-param> ...
Index - XSLT: Extensible Stylesheet Language Transformations
the stylesheet has to be passed in as an xml document, which means that the .xsl file has to be loaded by the page before
calling xsltprocessor.importstylesheet().
... 24 <xsl:
call-template> element, reference, xslt,
call-template the <xsl:
call-template> element invokes a named template.
WebAssembly
exported webassembly functions exported webassembly functions are the javascript reflections of webassembly functions which allow
calling webassembly code from javascript.
... instance objects contain all the exported webassembly functions that allow
calling into webassembly code from javascript.
Navigator.mozNotification - Archive of obsolete content
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).
indexed-db - Archive of obsolete content
n(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 = idbkeyrange.lowerbound(0); var cursorrequest = store.opencursor(keyrange); cursorrequest.onsuccess = function(e) { var result = e.target.result...
url - Archive of obsolete content
this function will automati
cally attempt to resolve non-file protocols, such as the resource: protocol, to their place on the file system.
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.
package.json - Archive of obsolete content
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 alphabeti
cally 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 ...
Chrome Authority - Archive of obsolete content
for example, none of the following code will be matched by the manifest scanner, leading to exceptions at runtime, when the require()
call is prohibited from importing the named modules: // all of these will fail!
Forms related code snippets - Archive of obsolete content
this date-picker code snippet will automati
cally create an html code like the following: <table id="zdp-cal-1" class="zdp-calendar" style="z-index: 1026; position: absolute; left: 294px; top: 47px;"> <caption><span id="zdp-decr-year-1" class="zdp-decrease-year">«</span><span id="zdp-decr-month-1" class="zdp-decrease-month"><</span><span id="zdp-incr-year-1" class="zdp-increase-year">»</span><span id="zdp-incr-month-1" class=...
Post data to window - Archive of obsolete content
preprocessing post data the apostdata argument of the (global) loaduri(), opendialog(), and (tab)browser.loaduriwithflags() methods expects the post data in the form of an nsiinputstream (because they eventually
call nsiwebnavigation.loaduri()) while post data can be created using nsimimeinputstream.
QuerySelector - Archive of obsolete content
// if you'd like to convert it to a array for convenience, use this instead: // return array.prototype.slice.
call(el.queryselectorall(selector)); } alert($('#myid').id); (note that while using the firefox web console, the above functions are available automati
cally.) both xul and even xml can be easily made supportable (an alternative approach to the following would be to add chromewindow.prototype or window.prototype, accessing this.document.queryselector, or following the jquery style of chaining by retur...
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.
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
#define compare(str1, str2, comp) (str1).compare(str2, comp) #define last() endreading()[-1] #define setcharat(c, i) replace(i, 1, ch) #define ns_newisupportsarray(result)
callcreateinstance(ns_supportsarray_contractid, static_cast<nsisupportsarray**>(result)); ideally we would switch to nsimutablearray, but in the mean time there's no point changing the same code twice.
chargingchange - Archive of obsolete content
general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event
callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method.
chargingtimechange - Archive of obsolete content
general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event
callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method.
dischargingtimechange - Archive of obsolete content
general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event
callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method.
levelchange - Archive of obsolete content
general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event
callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method.
No Proxy For configuration - Archive of obsolete content
corollary- a no_proxies_on entry of netscape.com will be applicable to all hosts ending at netscape.com including foonetscape.com but an entry of .netscape.com will specifi
cally be applicable to all hosts in the domain of netscape.com.
Automated testing tips and tricks - Archive of obsolete content
ript 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 domcontentloaded event chromewindow.addeventlistener('domcontentloaded',
callbackfunction,false); ...
Specifying the appearance - Archive of obsolete content
://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 list-style-image property to define an image to appear when our sta...
Creating a Mozilla Extension - Archive of obsolete content
contents prerequisites tinderbox making a mozilla installation modifiable finding the file to modify finding the code to modify adding the structure specifying the appearance enabling the behavior - retrieving tinderbox status enabling the behavior - updating the status bar panel enabling the behavior - updating the status periodi
cally making it into a static overlay making it into a dynamic overlay and packaging it up for distribution conclusion next » original document information author(s): myk melez last updated date: september 19, 2006 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details.
Code snippets - Archive of obsolete content
.import("resource://services-sync/engines/bookmarks.js"); let bme = weave.service.enginemanager.get("bookmarks"); let ids = object.keys(bme._store.getallids()); for each (let id in ids) { let record = bme._store.createrecord(id, "bookmarks"); let len = record.tostring().length; if (len > 1000) { console.log("id: " + id + ", len = " + len + ", " + record.title); } } print an alphabeti
cally sorted list of members of a collection components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); let ids = json.parse(new resource(weave.service.storageurl + "bookmarks").get()); for each (let id in ids.sort()) { console.log(" " + id); } get a count of the number of members of a collection on the server let collection = "pa...
Content - Archive of obsolete content
execute
callbacks when certain pages are opened siteboost allows a jetpack to empower a domain with extended abilities beyond those native to web pages ...
slideBar - Archive of obsolete content
iconhref oficon to show in the slidebaruri htmlhtml content for the featurehtml/xml urlurl to load content for the featureuri widthwidth of the content area and the selected slide sizeint persistdefault slide behavior when being selectedbool autoreloadautomati
cally reload content on selectbool onclick
callback when the icon is clickedfunction onselect
callback when the feature is selectedfunction onready
callback when featured is loadedfunction an example: jetpack.slidebar.append({ url: "http://mozilla.com", width: 150, onclick: function(slide){ slide.icon.src = "chrome://branding/content/icon48.png"; }}); ...
UI - Archive of obsolete content
displaying jetpack content in a slide-out animated vertical column toolbar including entries and access elements into the toolbar panel a movable, expandable, and custom styled content element to display jetpack content tabs adding events and interacting with browser tabs and their contained documents statusbar low-level functions and basic
calls notifications a system for alerting users via provided ui mechanisms selection interacting with user-selected content window mitigates and eases interactions between different browser windows ...
Jetpack - Archive of obsolete content
get started visit the getting started tutorial download the add-on sdk (formerly
called the jetpack sdk) documentation check out the documentation, including tutorials, examples, guides, and api reference join the jetpack community follow jetpack on the mozilla add-ons blog report a bug check out the open bugs discuss jetpack grab the source code join us in #jetpack on irc.mozilla.org ...
Makefile.mozextension.2 - Archive of obsolete content
t ; so again it will be corrupt :( therefore, here is a direct link to this makefile: makefile.mozextension2 ## file: makefile.mozextension2 ## based on http://kb.mozillazine.org/makefile_for_packaging_an_extension ## "this makefile.mozextention is for the test extension" ## the original makefile.mozextention reconstructs http://kb.mozillazine.org/getting_started_with_extension_development #
call with: # make -f makefile.mozextension2 make_structure ## (without args for 'all') # note: @echo silent; without @ the command is written in stdout project=test project_name=testworld #~ project_id={xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} project_id=test@testworld.ext project_version=1.0 project_desc="a $(project_name) project with advanced features" project_author=author name # mkdir=$(shell...
Plug-n-Hack - Archive of obsolete content
for example, to configure a browser to use an intercepting proxy that can handle https traffic, the user must typi
cally: configure their browser to proxy via the tool configure the tool to proxy via their corporate proxy import the tool’s ssl certificate into their browser if any of these steps are carried out incorrectly then the browser will typi
cally fail to connect to any website – debugging such problems can be frustrating and time-consuming.
Bundles - Archive of obsolete content
how-to here is a simple way to build a basic web application bundle: create file
called webapp.ini that contains something like: [parameters] id=unique-app-id@unique-author-id.whatever name=webapp name uri=http://[the-url-what-you-want-to-connect-to]/ status=yes location=no sidebar=no navigation=no zip the file to [whatever].webapp double-click the webapp bundle or use prism -webapp [path-to-webapp] structure a bundle can contain the following files.
FAQ - Archive of obsolete content
prism is the codename for the project, and if the functionality provided by prism becomes a product or is integrated into other products (like firefox), then it won't necessarily continue to be
called by this codename.
Static Analysis for Windows Code under Linux - Archive of obsolete content
host_libidl_config=/usr/bin/libidl-config #config your moztools position glib_prefix=$home/moztools libidl_prefix=$home/moztools #disable xpcom std
call calling convention because of gcc 4.3.0 bug cppflags="-dmoz_disable_xpcom_std
call" #specify the cxx and static analysis #point cxx to the cross compile g++ with plugin support cxx=$home/mingw-install/bin/i686-mingw32-g++ ac_add_options --with-static-checking=$home/dehydra/dehydra-gcc/gcc_dehydra.so then, you can start building your mozilla.
Tamarin Acceptance Test Template - Archive of obsolete content
* * ***** end license block ***** */ var section = "test"; // provide a document reference (ie, actionscript section) var version = "as3"; // version of ecmascript or actionscript var title = "test"; // provide ecma section title or a description var bugnumber = ""; starttest(); // leave this alone /** *
calls to addtestcase here.
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.
ontextcommand - Archive of obsolete content
« xul reference home ontextcommand obsolete since gecko 1.9.1 type: script code note: applies to: thunderbird, seamonkeythis event handler is
called when a result is selected for the textbox.
ontextrevert - Archive of obsolete content
« xul reference home ontextrevert obsolete since gecko 1.9.1 type: script code note: applies to: thunderbird, seamonkey this event handler is
called when the user presses escape to revert the textbox to its original uncompleted value.
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.
orient - Archive of obsolete content
« xul reference home orient type: one of the values below used to specify whether the children of the element are oriented horizontally or verti
cally.
popupanchor - Archive of obsolete content
this point (either directly under the mouse or attached to one of the four corners) is
called the originating point.by default the popup content appears with its top left point located directly underneath the point at which the user's mouse goes down (on tooltips the content is displaced by the height of the mouse cursor).
rel - Archive of obsolete content
less the numeric value of the subject must be less than the value greater the numeric value of the subject must be greater than the value before the string value of subject must come before value alphabeti
cally after the string value of subject must come after value alphabeti
cally startswith the value of subject must start with the value endswith the value of subject must end with the value contains the value of subject must contain the value as a substring ...
suppressonselect - Archive of obsolete content
« xul reference home suppressonselect type: boolean if this attribute is not specified, a select event is fired whenever an item is selected, either by the user or by
calling one of the select methods.
wait-cursor - Archive of obsolete content
in order to revert to the normal cursor state
call the method removeattribute("wait-cursor") when the process effectively has ended otherwise the wait cursor might never disappear.
IO - Archive of obsolete content
specifi
cally, to create a directory, see creating directories and to retrieve a list of files or subdirectories within a directory, see iterating over the files in a directory.
How to Quit a XUL Application - Archive of obsolete content
components.interfaces.nsiappstartup.eforcequit : components.interfaces.nsiappstartup.eattemptquit; appstartup.quit(quitseverity); } </script>
calling this function if there is an uncaught exception, to force the application to quit: <script> try { dosomething(); } catch (e) { quit(true); } </script> the "quit" menuitem should typi
cally prompt the user if there is unsaved data: <menuitem label="quit" oncommand="quit(false);"/> ...
List of commands - Archive of obsolete content
/seamonkey/sou...oomoverlay.xul http://lxr.mozilla.org/seamonkey/sou...toroverlay.xul http://lxr.mozilla.org/seamonkey/sou...ark.properties http://lxr.mozilla.org/seamonkey/sou...kmarks-temp.js http://lxr.mozilla.org/seamonkey/sou.../bookmarks.xml http://lxr.mozilla.org/seamonkey/sou...rksoverlay.xul http://lxr.mozilla.org/seamonkey/sou...okmarkstree.js list of commands (listed alphabeti
cally) browser:addbookmark browser:addbookmarkas browser:addgroupmarkas browser:back browser:editpage browser: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 ...
stopEditing - Archive of obsolete content
if the shouldaccept parameter is true, the cell's label is changed to the edited value (the tree view's nsitreeview.setcelltext() method is
called to change the cell contents).
menuitem - Archive of obsolete content
a workaround is to set the autocheck attribute to false, then programmati
cally set the checked attribute when the user selects the item, and set it to false instead of removing the attribute (i.e.
resizer - Archive of obsolete content
as some platforms provide this resizing grip automati
cally, this type of resizer element will be hidden and ensure that the window does not get an extra resizer.
richlistbox - Archive of obsolete content
suppressonselect type: boolean if this attribute is not specified, a select event is fired whenever an item is selected, either by the user or by
calling one of the select methods.
where - Archive of obsolete content
less the numeric value of the subject must be less than the value greater the numeric value of the subject must be greater than the value before the string value of subject must come before value alphabeti
cally after the string value of subject must come after value alphabeti
cally startswith the value of subject must start with the value endswith the value of subject must end with the value contains the value of subject must contain the value as a substring subject type: string the variable or string to compare.
2006-10-27 - Archive of obsolete content
discussions evalinsandbox and xmlhttprequest a discussion about writing something that
calls a function defined by the page that the user is currently on chrome files and last modified date ways to retrieve the last modified date of a chrome file that may be in a jar or on the file system.
2006-11-10 - Archive of obsolete content
summary: mozilla.dev.tech.xpcom - oct 04-nov 10, 2006 announcements xpt
call changes in process - ports owners needed if you maintain an xpt
call port, you are needed to submit a patch to that bug 349002 with xpt
call updates.
External resources for plugin creation - Archive of obsolete content
project: nixysa project home page description (from the home page): nixysa is a framework written in python to automati
cally generate glue code for npapi plugins (plugins for browsers such as google chrome or firefox), letting you easily expose c++ classes to javascript from a simple idl representation.
NPFullPrint - Archive of obsolete content
if you want an embedded plug-in to simply render its area of the page, set pluginprinted to false and return immediately; the browser
calls npp_print again with the npembedprint substructure of npprint.
NPN_ForceRedraw - Archive of obsolete content
description once a region of a windowless plugin has been invalidated with npn_invalidaterect() or npn_invalidateregion(), a plug-in can
call npn_forceredraw() to force a paint message.
NPN_SetValueForURL - Archive of obsolete content
(while the api theoreti
cally allows the preferred proxy for a given url to be changed, doing so does not have much meaning given how proxies are configured, and is not supported.) syntax #include <npapi.h> typedef enum { npnurlvcookie = 501, npnurlvproxy } npnurlvariable; nperror npn_setvalueforurl(npp instance, npnurlvariable variable, const char *url, const char *value, uint32_t len); parameters this function has the following parameters: instance pointer to the current plug-in instance.
Vulnerabilities - Archive of obsolete content
the key difference is that for a misuse vulnerability, the configuration setting enables or disables the entire feature and does not specifi
cally alter just its security; for a security configuration issue vulnerability, the configuration setting alters only the software’s security.
Using the W3C DOM - Archive of obsolete content
for example, the following short sample dynami
cally sets the left margin of a <div> element with an id of "inset" to half an inch: // in the html: <div id="inset">sample text</div> document.getelementbyid("inset").style.marginleft = ".5in"; note: internet explorer 5 through 7 have a flawed implementation of getelementbyid(), which returns the first element with a matching name or id (id versus name when using getelementbyid, msdn: getelementby...
-moz-stack-sizing - Archive of obsolete content
/* keyword values */ -moz-stack-sizing: auto; -moz-stack-sizing: ignore; /* global values */ -moz-stack-sizing: inherit; -moz-stack-sizing: initial; -moz-stack-sizing: unset; if you wish to prevent the stack from resizing automati
cally to accommodate its children, you can set -moz-stack-sizing to ignore on the child element.
-ms-filter - Archive of obsolete content
code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_s.htm <body> <p>click the image to start the filter.</p> //
call the function.
-ms-scroll-snap-points-x - Archive of obsolete content
(the -ms-scroll-snap-points-x property behaves identi
cally to the -ms-scroll-snap-points-y property, but along the x-axis.) .container { overflow-x: auto; overflow-y: hidden; -ms-scroll-snap-type: mandatory; -ms-scroll-snap-points-x: snapinterval(0%, 100%); width: 480px; height: 270px; } .imagecontainer { -ms-scroll-chaining: chained; -ms-overflow-style: none; -ms-content-zooming: zoom; -ms-scroll-rails: none; -ms-scroll-limit-x-...
-ms-scroll-snap-points-y - Archive of obsolete content
(the -ms-scroll-snap-points-y property behaves identi
cally to the -ms-scroll-snap-points-x property, but along the y-axis.) .container { overflow-x: auto; overflow-y: hidden; -ms-scroll-snap-type: mandatory; -ms-scroll-snap-points-y: snapinterval(0%, 100%); width: 480px; height: 270px; } .imagecontainer { -ms-scroll-chaining: chained; -ms-overflow-style: none; -ms-content-zooming: zoom; -ms-scroll-rails: none; -ms-scroll-limit-y-...
-ms-scroll-translation - Archive of obsolete content
if your javascript is listening for scroll wheel document object model (dom) events, the events that occur when the user scrolls verti
cally will always be vertical scroll events, not horizontal scroll events.
CSS - Archive of obsolete content
typi
cally it is a triangle that points downward.::-ms-fillthe ::-ms-fill css pseudo-element is a microsoft extension that represents a progress bar displayed by <progress>.::-ms-fill-lowerthe ::-ms-fill-lower css pseudo-element represents the lower portion of the track of a slider control; that is, the portion corresponding to values less than the value currently selected by the thumb.
Displaying notifications (deprecated) - Archive of obsolete content
= document.createelement("p"); e.innerhtml = "<strong>the notification was clicked.</strong>"; document.body.appendchild(e); }; notification.onclose = function() { var e = document.createelement("p"); e.innerhtml = "<strong>the notification was closed.</strong>"; document.body.appendchild(e); }; displaying the notification once the notification is configured the way you want it to be,
call its show() method to display the notification: notification.show(); on android, for example, the resulting notification panel looks like this: when the user taps on the "hey, check this out!" notification here, the resulting changes to the document look like this: if you're using firefox mobile, you can see this example live by tapping the button below.
ActiveXObject - Archive of obsolete content
for example, for the local intranet zone, you typi
cally need to change a custom setting to "initialize and script activex controls not marked as safe for scripting." to identify members of an automation object that you can use in your code, you may need to use a com object browser, such as the ole/com object viewer, if no reference documentation is available for the automation object.
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 ...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
ybuffer get arraybuffer[@@species] (firefox 48) dataview int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array get %typedarray%[@@species] (firefox 48) expressions and operators new.target (firefox 41) spread operator for arrays (firefox 16) use symbol.iterator property (firefox 36) spread operator for function
calls (firefox 27) use symbol.iterator property (firefox 36) const (js 1.5, firefox 1.0) (es2015 compliance bug 950547 implemented in firefox 51) let (js 1.7, firefox 2) (es2015 compliance bug 950547 implemented in firefox 51) destructuring assignment (js 1.7, firefox 2) (es2015 compliance bug 1055984) statements for...of (firefox 13) works in terms of .iterator() and .next()...
Game monetization - Game development
remember that with this license the publisher can't redistribute it further — it's often
called a site-locked deal as they buy the right to publish the game on their own given portal.
Game promotion - Game development
if you make a good game for a competition and win some prizes in the process your game will automati
cally be promoted by the organizers and other attendees.
Building up a basic demo with PlayCanvas editor - Game development
as you can see, the file contains some boilerplate code already: pc.script.create('boxanimation', function (app) { // creates a new boxanimation instance var boxanimation = function (entity) { this.entity = entity; }; boxanimation.prototype = { //
called once after all resources are loaded and before the first update initialize: function () { }, //
called every frame, dt is time in seconds since last update update: function (dt) { } }; return boxanimation; }); the most interesting part is the update() function, which is where we can put any code that we want repeated on every frame.
WebVR — Virtual Reality for the Web - Game development
there's also a markup framework
called a-frame that offers simple building blocks for webvr, so you can rapidly build and experiment with vr websites and games: read the building up a basic demo with a-frame tutorial for more details.
3D games on the Web - Game development
webgl is basi
cally an opengl es 2.0 for the web — it's a javascript api providing tools to build rich interactive animations and of course, also games.
Desktop gamepad controls - Game development
} if(gamepadapi.buttons.pressed('y','hold')) { if(!this.screengamepadhelp.visible) { this.screengamepadhelp.visible = true; } } else { if(this.screengamepadhelp.visible) { this.screengamepadhelp.visible = false; } } } } when pressing the start button the relevant function will be
called to begin the game, and the same approach is used for turning the audio on and off.
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 automati
cally 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.
Square tilemaps implementation: Static maps - Game development
we need to supply the atlas image, the coordinates and dimensions of the tile inside the atlas, and the target coordinates and size (a different tile size in here would scale the tile.) so, for instance, to draw the tree tile, which is the third in the atlas, at the screen coordinates (128, 320), we would
call drawimage() with these values: context.drawimage(atlasimage, 192, 0, 64, 64, 128, 320, 64, 64); in order to support atlases with multiple rows and columns, you would need to know how many rows and columns there are to be able to compute the source x and y.
Game over - Game development
first, replace where you initially
called setinterval() setinterval(draw, 10); with: var interval = setinterval(draw, 10); then replace the second if statement with the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game } letting the paddle hit the ball the ...
Track the score and win - Game development
ndetection() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; 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?
Bounce off the walls - Game development
add this line right after the existing game.physics.enable() method
call: ball.body.collideworldbounds = true; now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce.
Buttons - Game development
add the following lines to the bottom of your create() function: startbutton = game.add.button(game.world.width*0.5, game.world.height*0.5, 'button', startgame, this, 1, 0, 2); startbutton.anchor.set(0.5); the button() method's parameters are as follows: the button's x and y coordinates the name of the graphic asset to be displayed for the button a
callback function that will be executed when the button is pressed a reference to this to specify the execution context the frames that will be used for the over, out and down events.
Load the assets and print them on screen - Game development
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.
Physics - Game development
final code check the latest code should look like this: var ball; function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally = true; game.scale.pagealignverti
cally = true; game.stage.backgroundcolor = '#eee'; game.load.image('ball', 'img/ball.png'); } function create() { game.physics.startsystem(phaser.physics.arcade); ball = game.add.sprite(50, 50, 'ball'); game.physics.enable(ball, phaser.physics.arcade); ball.body.velocity.set(150, 150); } function update() { } try reloading index.html again — the ball should now be moving ...
Visual typescript game engine - Game development
-run services database server (lo
cally and leave it alive to develop process): npm run dataserver looks like this : mongod --dbpath ./server/database/data fix: "failed: address already in use" : netstat -ano | findstr :27017 taskkill /pid typeyourpidhere /f also important "run visual studio code as administrator".
API - MDN Web Docs Glossary: Definitions of Web-related terms
for example: the getusermedia api can be used to grab audio and video from a user's webcam, which can then be used in any way the developer likes, for example, recording video and audio, broadcasting it to another user in a conference
call, or capturing image stills from the video.
Breadcrumb - MDN Web Docs Glossary: Definitions of Web-related terms
a breadcrumb, or breadcrumb trail, is a navigational aid that is typi
cally placed between a site's header and the main content, displaying either a hierarchy of the current page in relation to the the site's structure, from top level to current page, or a list of the links the user followed to get to the current page, in the order visited.
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.
Doctype - MDN Web Docs Glossary: Definitions of Web-related terms
its sole purpose is to prevent a browser from switching into so-
called “quirks mode” when rendering a document; that is, the "<!doctype html>" doctype ensures that the browser makes a best-effort attempt at following the relevant specifications, rather than using a different rendering mode that is incompatible with some specifications.
Attribute selectors - Learn web development
(aside: it may help to note that ^ and $ have long been used as anchors in so-
called regular expressions to mean begins with and ends with.) the next example shows usage of these selectors: li[class^="a"] matches any attribute value which starts with a, so matches the first two list items.
CSS building blocks - Learn web development
handling different text directions in recent years, css has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as japanese) — these different directionalities are
called writing modes.
Grids - Learn web development
a grid will typi
cally have columns, rows, and then gaps between each row and column — commonly referred to as gutters.
Styling lists - Learn web development
handling list spacing when styling lists, you need to adjust their styles so they keep the same vertical spacing as their surrounding elements (such as paragraphs and images; sometimes
called vertical rhythm), and the same horizontal spacing as each other (you can see the finished styled example on github, and find the source code too.) the css used for the text styling and spacing is as follows: /* general styles */ html { font-family: helvetica, arial, sans-serif; font-size: 10px; } h2 { font-size: 2rem; } ul,ol,dl,p { font-size: 1.5rem; } li, p { line-height: 1.5;...
What is accessibility? - Learn web development
accessibility champions since 1999, the w3c has operated a working group
called the web accessibility initiative (wai) promoting accessibility through guidelines, support material, and international resources.
Common questions - Learn web development
this set of articles shows you how to use the developer tools in firefox to debug and improve performance of your website, using the tools to check memory usage, the javascript
call tree, the number of dom nodes being rendered, and more.
The HTML5 input types - Learn web development
another feature worth noting is that the values of a search field can be automati
cally saved and re-used to offer auto-completion across multiple pages of the same website; this tends to happen automati
cally in most modern browsers.
Example 3 - Learn web development
hadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (
callback) { array.prototype.foreach.
call(this,
callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { ...
Example 4 - Learn web development
hadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (
callback) { array.prototype.foreach.
call(this,
callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { ...
Example 5 - Learn web development
hadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (
callback) { array.prototype.foreach.
call(this,
callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { ...
UI pseudo-classes - Learn web development
lock; content: " "; width: 10px; height: 10px; border-radius: 6px; background-color: red; font-size: 1.2em; transform: translate(3px, 3px) scale(0); transform-origin: center; transition: all 0.3s ease-in; } input[type="radio"]:checked::before { transform: translate(3px, 3px) scale(1); transition: all 0.3s cubic-bezier(0.25, 0.25, 0.56, 2); } you can try it out here: basi
cally, we build the styling for the radio button "inner circle" using the ::before pseudo element, but set a scale(0) transform on it.
Example - Learn web development
to harmonize the look & feel of text field border */ border: 1px solid #999; } input:focus, textarea:focus { /* to give a little highligh on active elements */ border-color: #000; } textarea { /* to properly align multiline text field with their label */ vertical-align: top; /* to give enough room to type some text */ height: 5em; /* to allow users to resize any textarea verti
cally it works only on chrome, firefox and safari */ resize: vertical; } .button { /* to position the buttons to the same position of the text fields */ padding-left: 90px; /* same size as the label elements */ } button { /* this extra magin represent the same space as the space between the labels and their text fields */ margin-left: .5em; } result ...
Define terms with HTML - Learn web development
a simple example here's a simple example describing kinds of food and drink: <dl> <dt>jambalaya</dt> <dd> rice-based entree typi
cally containing chicken, sausage, seafood, and spices </dd> <dt>sukiyaki</dt> <dd> japanese specialty consisting of thinly sliced meat, vegetables, and noodles, cooked in sake and soy sauce </dd> <dt>chianti</dt> <dd> dry italian red wine originating in tuscany </dd> </dl> the basic pattern, as you can see, is to alternate <dt> terms with <dd> desc...
Structuring the web with HTML - Learn web development
and how to use it to style html (for example alter your text size and fonts used, add borders and drop shadows, layout your page with multiple columns, add animations and other visual effects.) javascript, and how to use it to add dynamic functionality to web pages (for example find your location and plot it on a map, make ui elements appear/disappear when you toggle a button, save users' data lo
cally on their computers, and much much more.) modules this topic contains the following modules, in a suggested order for working through them.
Test your skills: Functions - Learn web development
the three improvements we want you to make are: refactor the code that generates the random number into a separate function
called random(), which takes as parameters two generic bounds that the random number should be between, and returns the result.
JavaScript building blocks - Learn web development
functions allow you to store a piece of code that does a single task inside a defined block, and then
call that code whenever you need it using a single short command — rather than having to type out the same code multiple times.
Cross browser testing - Learn web development
handling common html and css problems with the scene set, we'll now look specifi
cally at the common cross-browser problems you will come across in html and css code, and what tools can be used to prevent problems from happening, or fix problems that occur.
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.
Learn web development
to copy the learning area repo to a folder
called learning-area in the current location your command prompt/terminal is pointing to, use the following command: git clone https://github.com/mdn/learning-area you can now enter the directory and find the files you are after (either using your finder/file explorer or the cd command).
Accessibility/LiveRegionDevGuide
in at-spi, the object changed event are
called object:children-changed events because the event is triggered on the parent of the object.
Index
add-ons hosted on amo automati
cally receive updates to new versions posted there.
Benchmarking
profiling tools currently the gecko profiler has limitations in the ui for inverted
call stack top function analysis which is very useful for finding heavy functions that
call into a whole bunch of code.
Building SpiderMonkey with UBSan
the stack trace should show a function such as __ubsan_handle_load_invalid_value or __ubsan_handle_type_mismatch being
called by the buggy c++ code.
Creating a Language Pack
each time you want to generate a new binary (often
called a "repack"), you need to run these two commands.
Creating a Login Manager storage module
onsoleservice); return this.__logservice; }, log: function (message) { dump("sampleloginmanager: " + message + "\n"); this._logservice.logstringmessage("sampleloginmanager: " + message); }, // logs function name and arguments for debugging stub: function(arguments) { var args = []; for (let i = 0; i < arguments.length; i++) args.push(arguments[i]) this.log("
called " + arguments.
callee.name + "(" + 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: ...
Capturing a minidump
capturing a minidump: application crash to capture a full minidump for an application crash, you can use a tool
called windbg.
Debugging Internet Explorer
to run internet explorer in a single process add a dword registry value to hkey_current_user\software\microsoft\internet explorer\main
called tabprocgrowth and set it to 0.
Adding APIs to the navigator object
programmati
cally 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.
OS TARGET
os_target is typi
cally the output of the 'uname -s' command on the target platform.
Simple Sunbird build
(for some mac os x versions, you will find it in a directory
called "optional installs".) install macports.
ESLint
in order to help people write standard-compliant code from the start and avoid wasting time during code reviews, a set of eslint configuration files have been added to the code base so that javascript can be analyzed automati
cally.
Gecko Logging
rust we're gradually adding more rust code to gecko, and rust crates typi
cally use a different approach to logging.
Inner and outer windows
these don't techni
cally refer to windows as the user sees them, but rather a perspective on what the user is looking at.
Commenting IDL for better documentation
but by following the guidelines here, you can help make sure that our tools can generate a "good start" version of the documentation for your interfaces, and that the writers will be able to easily figure out what the tools are not able to do automati
cally.
Obsolete Build Caveats and Tips
if you do not specify a moz_objdir it will be automati
cally set to @topsrcdir@/obj-@config_guess@ alternatively, you can run client.mk directly from your objdir, using make -f <path_to_srcdir>/client.mk.
Reviewer Checklist
compatibility version files, databases, messages tag messages with ids to disambiguate
callers.
Developer guide
callgraph a tool to help perform static analysis of the mozilla code by generating
callgraphs automati
cally.
Communicating with frame scripts
where absolutely necessary, frame scripts can pass wrappers
called cross process object wrappers (also known as cpows) to chrome, and chrome can use these wrappers to get synchronous access to content objects.
Limitations of frame scripts
in the content process, the root tree item is an nsitabchild, that cannot be converted to an nsidomwindow, so the second getinterface
call here will fail.
HTMLIFrameElement.goBack()
by
calling this method, the browser <iframe> changes its location for the previous location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart, and so on.
HTMLIFrameElement.goForward()
by
calling this method, the browser <iframe> changes its location to the next location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart and so on.
mozbrowseractivitydone
postresult and posterror
calls made on such an activity will be ignored and have no effect.
mozbrowserclose
the mozbrowserclose event is fired when the content of a browser <iframe>
calls the window.close() method.
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.
mozbrowservisibilitychange
the mozbrowservisibilitychange event is fired when the visibility state of the current browser iframe <iframe> changes, for example due to a
call to setvisible().
Gecko SDK
building the sdk to build the sdk, you should build xulrunner (the gecko sdk is built as part of the xulrunner build process, which is why it's sometimes
called the xulrunner sdk).
Hacking with Bonsai
the process everyone who checks into the tree, joins a group
called "the hook" at 8:00 am pst every weekday morning, the source tree is closed.
How test harnesses work
mozilla test harnesses are typi
cally composed of a python runner that invokes firefox, utilizes the browser to run tests, and reports the results.
How to add a build-time test
standalone executables to add a test that is written in c or c++ and which is
called as a standalone executable, a few things must be done.
Infallible memory allocation
p = moz_xmalloc(); p = moz_x
calloc(); p = moz_xrealloc(); p = moz_xstrdup(); f = new foo(); farray = new foo[]; n = ::operator new(...); narray = ::operator new[](...); explicitly fallible memory allocators these memory allocators are explicitly fallible, and will remain so.
AddonInstall
the process will continue in the background until it fails, completes, one of the registered installlisteners pauses it, or the process is canceled by a
call to the cancel() method.
API-provided widgets
showinprivatebrowsing whether to show the widget in private browsing mode (optional, default: true) event handlers you can also define several event handlers which will be
called at various stages in a widget's lifetime: event handler name description onbuild(adoc) only useful for custom widgets (and required there); a function that will be invoked with the document in which to build a widget.
OS.File.Info
instances of os.file.info may be obtained by:
calling global method os.file.stat() either from the main thread or from a worker thread;
calling instance method stat() of os.file either from the main thread or from a worker thread.
PerfMeasurement.jsm
note: these values are all zeroed (or set to -1, for events not being measured) when you initialize the perfmeasurement object, then they are not zeroed again unless you explicitly
call the reset() method.
Timer.jsm
to use timer.jsm, first import it: components.utils.import("resource://gre/modules/timer.jsm"); then
call settimeout and cleartimeout just as you would in a dom window, for example: let timeoutid = settimeout(function() { console.log("hello!"); }, 500); cleartimeout(timeoutid); similarly, you can use setinterval and clearinterval like so: let intervalid = setinterval(function() { console.log("happening every 500ms!"); }, 500); clearinterval(intervalid); ...
Webapps.jsm
p, 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) getnotinstalled: function(adata, amm) geticon: function(adata, amm) getall: function(a
callback) isreceipt: function(data) addreceipt: function(adata, amm) removereceipt: function(adata, amm) replacereceipt: function(adata, amm) setenabled: function(adata) getmanifestfor: function(amanifesturl, aentrypoint) getappbymanifesturl: function(amanifesturl) getfullappbymanifesturl: function(amanifesturl, aentrypoint, alang) getmanifestcspbylocalid: function(alocalid) getdefaultcspbyl...
Localizing with Mozilla Translator
most of the strings will be automati
cally filled, although if you do this you should review them, because for en-us strings with several possible translations, mt will choose one of them, which could not be the one you want.
Translation phase
add-ons l10n for add-ons is handled by at least two other organizations/services
called babelzilla and adofex.
Localization sign-off reviews
your review request symboli
cally represents that you have worked on your localization, tested it successfully, and found it to represent the best of your work.
Setting up the infrastructure
by default the script looks for gettext
calls in *thtml or *.php files, so you may need to adjust that to your code.
Fonts for Mozilla's MathML engine
typi
cally, use a fontconfig configuration /etc/fonts/conf.avail/09-texlive-fonts.conf that points to the opentype directory of texlive, such as: <?xml version="1.0"?> <!doctype fontconfig system "fonts.dtd"> <fontconfig> <dir>/your/path/to/texmf-dist/fonts/opentype</dir> </fontconfig> finally, add this configuration file to the system font location list and regenerate the fontconfig cache: ln -sf /e...
mozilla::MonitorAutoEnter
the mozilla::monitorautoenter constructor will enter() the underlying mozilla::monitor automati
cally.
mozilla::MutexAutoLock
the mozilla::mutexautolock constructor will lock() the underlying mozilla::mutex automati
cally.
mozilla::MutexAutoUnlock
the mozilla::mutexautounlock constructor will unlock() the underlying mozilla::mutex automati
cally.
Are We Slim Yet
the results are posted to perfherder where we can track regressions automati
cally.
Leak Gauge
nspr_log_modules=domleak:5,documentleak:5,nsdocshellleak:5,nodeinfomanagerleak:5 nspr_log_file=nspr.log # or any other filename of your choice this will overwrite any existing file
called nspr.log.
Scroll-linked effects
call to action if you have thoughts or opinions on: any of the above proposals in the context of scroll-linked effects.
tools/power/rapl
tools/power/rapl (or rapl for short) is a command-line utility in the mozilla tree that periodi
cally reads and prints all available intel rapl power estimates.
Performance
profiling and performance tools profiling with the developer tools profiler the profiler built into the developer tools has a high-level waterfall, detailed
call tree, allocations and gc profiling, and flame graphs.
javascript.options.showInConsole
note: since the web console was introduced in firefox 4 specifi
cally for debugging content, the default value for this preference has changed to true as of gecko 2.0.
Preference reference
set it to true to enable it, or false to disable it.browser.dom.window.dump.filebrowser.dom.window.dump.file redirects the ouput of window.dump()
calls to a file whose address is specified in this preference if browser.dom.window.dump.enabled is set to true.
Preferences system
usage in xulrunner applications when
calling opendialog() to open a preferences dialog, "toolbar" should be included in the features string.
Research and prep
ensure that your suggestions follow these parameters: search there are typi
cally five search plug-ins listed for firefox desktop (only four for firefox mobile): generic search the default option should expose the quickest path to the best result on the world wide web for the user (indexing a large portion of the global www).
Emscripten
practi
cally any portable c or c++ codebase can be compiled into javascript using emscripten, ranging from high performance games that need to render graphics, play sounds, and load and process files, through to application frameworks like qt.
Leak And Bloat Tests
results printed on tinderbox output, these consist of: mail rlk reference count leaks mail lk total bytes malloc'ed and not free'd mail mh maximum heap size mail a allocations - number of
calls to malloc and friends.
NSPR Contributor Guide
your proposed api should encapsulate a relatively low level capability as would be found in a system
call or libc.
Cached Monitors
the system automati
cally enlarges the hash table as needed.
Linked Lists
the
caller must provide for mutually-exclusive access to the list, and for the nodes being added and removed from the list.
NSPR Error Handling
pr_no_access_rights_error
calling thread does not have privilege to perform the operation requested.
Network Addresses
typi
cally, the only numeric declarations required are the well-known port numbers that are part of the prnetaddr structure.
PLHashEnumerator
syntax #include <plhash.h> typedef printn (pr_
callback *plhashenumerator)(plhashentry *he, printn index, void *arg); /* return value */ #define ht_enumerate_next 0 /* continue enumerating entries */ #define ht_enumerate_stop 1 /* stop enumerating entries */ #define ht_enumerate_remove 2 /* remove and free the current entry */ #define ht_enumerate_unhash 4 /* just unhash the current entry */ description plhashenumerator is a function type used in the enumerating a hash table.
PLHashFunction
syntax #include <plhash.h> typedef plhashnumber (pr_
callback *plhashfunction)(const void *key); description plhashnumber is a function type that maps the key of a hash table entry to a hash number.
PRAddrInfo
typi
cally, a praddrinfo object will be found via pr_getaddrinfobyname, iterated through using pr_enumerateaddrinfo, and finally freed with pr_freeaddrinfo.
PRErrorCode
if nspr's error handling is adopted by
calling clients, then some sort of partitioning of the namespace will have to be employed.
PRFileMap
before actually mapping a file to memory, you must create a memory-mapped file object by
calling pr_createfilemap, which returns a pointer to prfilemap.
PRHostEnt
all addresses are passed in host order and returned in network order (suitable for use in system
calls).
PRIOMethods
if a layer provides no functionality, it should
call the next lower (higher) function of the same name (for example, the "close" method would return fd->lower->method->close(fd->lower)).
PRIntervalTime
a platform-dependent type that represents a monotoni
cally increasing integer--the nspr runtime clock.
PRJobFn
syntax #include <prtpool.h> typedef void (pr_
callback *prjobfn)(void *arg); ...
PR_NewUDPSocket
when the socket is no longer needed, it should be closed with a
call to pr_close.
PR_Notify
the monitor object referenced must be one for which the
calling thread currently holds the lock.
PR_OpenSemaphore
the created semaphore needs to be removed from the system with a pr_deletesemaphore
call.
PR_OpenSharedMemory
retrieve the reason for the failure by
calling pr_geterror and pr_getoserror.
PR OpenUDPSocket
when the socket is no longer needed, it should be closed with a
call to pr_close.
PR_PopIOLayer
if the object to be removed is found, pr_popiolayer returns a pointer to the removed object the object then becomes the responsibility of the
caller.
PR_PostSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_postsemaphore(prsem *sem); parameter the function has the following parameter: sem a pointer to a prsem structure returned from a
call to pr_opensemaphore.
PR_QueueJob
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob( prthreadpool *tpool, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a
call to pr_createthreadpool.
PR_QueueJob_Accept
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_accept( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a
call to pr_createthreadpool.
PR_QueueJob_Connect
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_connect( prthreadpool *tpool, prjobiodesc *iod, const prnetaddr *addr, prjobfn fn, void * arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a
call to pr_createthreadpool.
PR_QueueJob_Read
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_read( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a
call to pr_createthreadpool.
PR_QueueJob_Timer
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_timer( prthreadpool *tpool, printervaltime timeout, prjobfn fn, void * arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a
call to pr_createthreadpool.
PR_QueueJob_Write
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_write( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a
call to pr_createthreadpool.
PR_Realloc
call pr_geterror() to retrieve the error returned by the libc function realloc().
NSS CERTVerify Log
certverifylog all the nss verify functions except, the *verifynow() functions, take a parameter
called 'certverifylog'.
Deprecated SSL functions
applications that want to use the ssl shared libraries must convert to
calling the new replacement functions listed below.
NSS FAQ
you can use nspr throughout your application or only in the portion that
calls into nss.
Introduction to Network Security Services
platform for 32-bit cpus for 64-bit cpus solaris/sparc libfreebl_pure32_3.so libfreebl_hybrid_3.so hpux/parisc libfreebl_pure32_3.sl libfreebl_hybrid_3.sl aix (planned for a future release) libfreebl_pure32_3_shr.a libfreebl_hybrid_3_shr.a an application should not link against these libraries, because they are dynami
cally loaded by nss at run time.
JSS
java provides a jce provider
called sunpkcs11 (see java pkcs#11 reference guide.) sunpkcs11 can be configured to use the nss module as the crytographic provider.
NSS_3.12.2_release_notes.html
rtchain 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.
NSS 3.12.4 release notes
evoked cert bug 485745: modify fipstest.c to support cavs 7.1 drbg testing bug 486304: cert7.db/cert8.db corruption when importing a large certificate (>64k) bug 486405: allocator mismatches in pk12util.c bug 486537: disable execstack in freebl x86_64 builds on linux bug 486698: facilitate the building of major components independently and in a chain manner by downstream distributions bug 486999:
calling ssl_setsockpeerid a second time leaks the previous value bug 487007: make lib/jar conform to nss coding style bug 487162: ckfw/capi build failure on windows bug 487239: nssutil.rc doesn't compile on wince bug 487254: sftkmod.c uses posix file io functions on wince bug 487255: sdb.c uses posix file io functions on wince bug 487487: cert_nametoascii reports !invalid ava!
NSS 3.12.6 release notes
the behavior of nss for renegotiation can be changed through api function
calls, or with the following environment variables: nss_ssl_enable_renegotiation values: [0|n|n]: ssl_renegotiate_never never allow renegotiation - that was the default for 3.12.5 release.
NSS 3.15.1 release notes
bug 882829 - on windows, nss initialization fails if nss cannot
call the rtlgenrandom function.
NSS 3.16.2 release notes
new macros in sslerr.h ssl_error_next_protocol_no_
callback - an ssl error code that means the next protcol negotiation extension was enabled, but the
callback was cleared prior to being needed.
NSS 3.16 release notes
the atob utility has been improved to automati
cally ignore lines of text that aren't in base64 format.
NSS 3.20 release notes
each time this api is
called for the first time in a process, a fresh set of weak dhe parameters will be randomly created, which may take a long amount of time.
NSS 3.23 release notes
clients that perform a version downgrade (which is a dangerous practice)
call this with the highest version number that they possibly support.
NSS 3.28.5 release notes
trust root ca 3 2013 sha-256 fingerprint: a1:a8:6d:04:12:1e:b8:7f:02:7c:66:f5:33:03:c2:8e:57:39:f9:43:fc:84:b3:8a:d6:af:00:90:35:dd:94:57 trust flags: email cn = tubitak kamu sm ssl kok sertifikasi - surum 1 sha-256 fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16 trust flags: websites techni
cally constrained to: gov.tr, k12.tr, pol.tr, mil.tr, tsk.tr, kep.tr, bel.tr, edu.tr, org.tr the version number of the updated root ca list has been set to 2.14.
NSS 3.30.2 release notes
trust root ca 3 2013 sha-256 fingerprint: a1:a8:6d:04:12:1e:b8:7f:02:7c:66:f5:33:03:c2:8e:57:39:f9:43:fc:84:b3:8a:d6:af:00:90:35:dd:94:57 trust flags: email cn = tubitak kamu sm ssl kok sertifikasi - surum 1 sha-256 fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16 trust flags: websites techni
cally constrained to: gov.tr, k12.tr, pol.tr, mil.tr, tsk.tr, kep.tr, bel.tr, edu.tr, org.tr the version number of the updated root ca list has been set to 2.14 (the version numbers 2.12 and 2.13 for the root ca list have been skipped.) bugs fixed in nss 3.30.2 bug 1350859 - march 2017 batch of root ca changes bug 1349705 - implemented domain name constraints for ca: tubitak kam...
NSS 3.31 release notes
an application may
call ssl_versionrangeget and ssl_versionrangegetdefault to query the tls version range that was effectively activated.
NSS 3.38 release notes
nss automati
cally enables caching for sql database storage on linux, if it is located on a network filesystem that's known to benefit from caching.
NSS 3.43 release notes
0988446c7636183df9846e17101a447fb8efd6 the following ca certificates were removed: none bugs fixed in nss 3.43 bug 1528669 and bug 1529308 - improve gyp build system handling bug 1529950 and bug 1521174 - improve nss s/mime tests for thunderbird bug 1530134 - if docker isn't installed, try running a local clang-format as a fallback bug 1531267 - enable fips mode automati
cally if the system fips mode flag is set bug 1528262 - add a -j option to the strsclnt command to specify sigschemes bug 1513909 - add manual for nss-policy-check bug 1531074 - fix a deref after a null check in seckey_setpublicvalue bug 1517714 - properly handle esni with hrr bug 1529813 - expose hkdf-expand-label with mechanism bug 1535122 - align tls 1.3 hkdf trace levels bug 1530102 - use g...
NSS 3.44 release notes
on fault 1546925 - allow preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variables passed to nspr 1543545 - allow to build nss as a static library 1487597 - early data that arrives before the handshake completes can be read afterwards 1548398 - freebl_gtest not building on linux/mac 1548722 - fix some coverity warnings 1540652 - softoken/sdb.c: logi
cally dead code 1549413 - android log lib is not included in build 1537927 - ipsec usage is too restrictive for existing deployments 1549608 - signature fails with dbm disabled 1549848 - allow building nss for ios using gyp 1549847 - nss's sqlite compilation warnings make the build fail on ios 1550041 - freebl not building on ios simulator 1542950 - macos cipher test timeouts this bugzilla qu...
NSS 3.45 release notes
send session ticket only after handshake is marked as finished bug 1550708 - fix gyp scripts on solaris sparc so that libfreebl_64fpu_3.so builds bug 1554336 - optimize away unneeded loop in mpi.c bug 1559906 - fipstest: use ckm_tls12_master_key_derive instead of vendor specific mechanism bug 1558126 - tls_aes_256_gcm_sha384 should be marked as fips compatible bug 1555207 - helloretryrequest
callback return code for rejecting 0-rtt bug 1556591 - eliminate races in uses of pk11_setwrapkey bug 1558681 - stop using a global for anti-replay of tls 1.3 early data bug 1561510 - fix a bug where removing -arch xxx args from cc didn't work bug 1561523 - add a string for the new-ish error ssl_error_missing_post_handshake_auth_extension this bugzilla query returns all the bugs fixed in nss 3.4...
NSS 3.51 release notes
bug 1538980 - secu_readderfromfile
calls strstr on a string that isn't guaranteed to be null-terminated bug 1561337 - correct a warning for comparison of integers of different signs: 'int' and 'unsigned long' in security/nss/lib/freebl/ecl/ecp_25519.c:88 bug 1609751 - add test for mp_int clamping bug 1582169 - don't attempt to read the fips_enabled flag on the machine unless nss was built with fips enabled bug 1431940 - fix a null ...
NSS Config Options
policy-lock: turn off the ability for applications to change policy with the
call nss_setalgorithmpolicy.
NSS Developer Tutorial
opaque structs give us complete freedom to change them, but require applications to
call nss functions, to allocate and free them.
NSS Sample Code sample2
for * des ops, internal slot is typi
cally the best slot */ if (slot == null) { fprintf(stderr, "unable to find security device (err %d)\n", pr_geterror()); goto out; } /* nss passes blobs around as secitems.
NSS Sample Code sample4
*/ #include "nss.h" #include "pk11pub.h" /* this
callback is responsible for returning the password to the nss * key database.
NSS Sample Code sample6
this example happens to use an * integer */ void genkey(int id); /* this
callback is responsible for returning the password to the nss * key database.
FC_SignRecover
a user must log into the token (to assume the nss user role) before
calling fc_signrecover.
FC_SignRecoverInit
a user must log into the token (to assume the nss user role) before
calling fc_signrecoverinit.
FC_Verify
a user must log into the token (to assume the nss user role) before
calling fc_verify.
FC_VerifyFinal
a user must log into the token (to assume the nss user role) before
calling fc_verifyfinal.
FC_VerifyInit
a user must log into the token (to assume the nss user role) before
calling fc_verifyinit.
FC_VerifyRecover
a user must log into the token (to assume the nss user role) before
calling fc_verifyrecover.
FC_VerifyRecoverInit
a user must log into the token (to assume the nss user role) before
calling fc_verifyrecoverinit.
NSS Key Functions
when you
call cert_destroycertificate or seckey_destroyprivatekey, the function decrements the reference count and, if the reference count reaches zero as a result, both frees the memory and sets all the bits to zero.
NSS environment variables
nss_memory_allocation 3.4 nss_disable_unload string (any non-empty value) disable unloading of dynami
cally loaded nss shared libraries during shutdown.
NSS tools : cmsutil
for information specifi
cally about nss, the nss project wiki is located at [2]http://www.mozilla.org/projects/security/pki/nss/.
sslkey.html
when you
call cert_destroycertificate or seckey_destroyprivatekey, the function decrements the reference count and, if the reference count reaches zero as a result, both frees the memory and sets all the bits to zero.
SSL functions
cehandshakewithtimeout mxr 3.11.4 and later ssl_getchannelinfo mxr 3.4 and later ssl_getciphersuiteinfo mxr 3.4 and later ssl_getclientauthdatahook mxr 3.2 and later ssl_getmaxservercachelocks mxr 3.4 and later ssl_getsessionid mxr 3.2 and later ssl_getstatistics mxr 3.2 and later ssl_handshake
callback mxr 3.2 and later ssl_importfd mxr 3.2 and later ssl_inheritmpserversidcache mxr 3.2 and later ssl_invalidatesession mxr 3.2 and later ssl_localcertificate mxr 3.4 and later ssl_optionget mxr 3.2 and later ssl_optiongetdefault mxr 3.2 and later ssl_optionset mxr 3.2 and later ...
TLS Cipher Suite Discovery
ssl_getciphersuiteinfo fills that
caller-supplied memory with information from the sslciphersuiteinfo structure for that cipher suite.
NSS Tools
eliminate use of getopt() and replace with nspr
calls to get command options (to eliminate platform dependencies with getopt()).
NSS Tools certutil-tasks
(bugfix) certificate entries require a serial number; one should be generated automati
cally if not provided.
NSS tools : cmsutil
for information specifi
cally about nss, the nss project wiki is located at [2]http://www.mozilla.org/projects/security/pki/nss/.
Proxies in Necko
this means that
callers can just create an nsichannel, not needing to worry about whether the channel will use a proxy or not the basic interfaces for proxies are: nsiproxyinfo, nsiprotocolproxyservice, and nsiproxiedprotocolhandler nsiproxyinfo is a simple helper which stores information about the type of the proxy, its host and its port.
Pork
this information allows c++ to be automati
cally rewritten in a precise way.
Rhino Examples
primitivewrapfactory primitivewrapfactory.java is an example of a wrapfactory that can be used to control the wrapping behavior of the rhino engine on
calls to java methods.
Rhino shell
deserialize(filename) restore from the specified file an object previously written by a
call to serialize.
Rhino
it is typi
cally embedded into java applications to provide scripting to end users.
Shumway
it can be run lo
cally through a web server or you can use the version hosted on mozilla's github.
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 any library using the gobject introspection mechanism) objective caml http://alain.frisch.fr/soft.html#spider - bindings to embed spidermonkey in ocaml applications perl http://jspl.msg.mx/ - bindings to cross-embed spidermonkey and perl.
INT_FITS_IN_JSVAL
if so, int_fits_in_jsval returns true, and i can be cast to jsval by
calling int_to_jsval(i).
JS::Compile
in a js_threadsafe build, the
caller must be in a request on this jscontext.
JS::CompileFunction
in a js_threadsafe build, the
caller must be in a request on this jscontext.
JS::CreateError
in a js_threadsafe build, the
caller must be in a request on this jscontext.
JS_SetRegExpInput
in a js_threadsafe build, the
caller must be in a request on this jscontext.
JS_SetThreadStackLimit
in a js_threadsafe build, after passing a jscontext from one thread to another,
call js_setthreadstacklimit(cx, 0) after
calling js_setcontextthread.
JS_StrictlyEqual
in a js_threadsafe build, the
caller must be in a request on this jscontext.
JS_StringHasLatin1Chars
clients can use js_stringhaslatin1chars and can then
call either the latin1* or twobyte* functions.
JS_TypeOfValue
in a js_threadsafe build, the
caller must be in a request on this jscontext.
JS_ValueToBoolean
in a js_threadsafe build, the
caller must be in a request on this jscontext.
JS_ValueToSource
in a js_threadsafe build, the
caller must be in a request on this jscontext.
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.
Profiling SpiderMonkey
we're working to add support for other profilers, such as oprofile, intel vtune, and
callgrind.
Thread Sanitizer
# note: the use of this flag causes clang to automati
cally link the tsan runtime :) export ldflags="-fsanitize=thread -fpic -pie" # these three are required by tsan ac_add_options --disable-jemalloc ac_add_options --disable-crashreporter ac_add_options --disable-elf-hack # keep symbols to symbolize tsan traces export moz_debug_symbols=1 ac_add_options --enable-debug-symbols ac_add_options --disable-install-strip # settings for an opt build ac_add_opt...
Mozinfo
mozinfo.py is the only file contained is this package, so if you need a single-file solution, you can just download or
call this file through the web.
Security and the jar protocol
however, if a site allows file uploads, zip files are typi
cally treated as relatively innocuous by web sites in that situation, since they're not executable.
Task graph
all of this is controlled from within the gecko source code, through a process
called task-graph generation.
Animated PNG graphics
it must appear before the 'idat' or 'fdat' chunks of the frame to which it applies, specifi
cally: for the default image, if a 'fctl' chunk is present it must appear before the first 'idat' chunk.
ROLE_ALERT
assistive technologies typi
cally respond to the role by reading the entire onscreen contents of containers advertising this role.
Places Developer Guide
newuri(spec, null, null); } var browserhistory = histsvc.queryinterface(ci.nsibrowserhistory); var oururi = uri("http://www.mozilla.com"); // remove all visits for a single url from history browserhistory.removepage(oururi); // remove all visits for multiple urls from history var uristodelete = [oururi]; // will
call nsinavhistoryobserver.onbeginupdatebatch/onendupdatebatch var donotify = false; browserhistory.removepages(uristodelete, uristodelete.length, donotify); // remove all visits within a given time period var enddate = date.now() * 1000; // now, in microseconds var startdate = enddate - (7 * 86400 * 1000 * 1000); // one week ago, in microseconds browserhistory.removepagesbytimeframe(startdate, endda...
Places Expiration
algorithm expiration is based on hardware specs, specifi
cally on memory size and available disk space.
Using the Places favicon service
the annotation service's "moz-anno:" protocol handler notices annotations
called "favicon" and forwards these to the favicon service.
Using the Places keywords API
note that fetch() always resolves to a single entry, to fetch all of the entries it's necessary to provide a
callback function.
Places
the places "frecency" algorithm the algorithm behind the places location bar (sometimes
called the "awesomebar").
extIPreferenceBranch
reset() parameters return value examples var myext = application.extensions.get('myapplicationid'); function myfunc (event) { application.console.log('change!'); }; myext.prefs.get("myprefname").events.addlistener("change", myfunc); see also fuel (firefox), steel (thunderbird) and smile (seamonkey) known issues bug 488587 - function registered as fuel preference listener not always
called ...
XML Extras
file new bugs for additional documentation contributions, either specifi
cally aimed at javascript developers or to complete & clarify the javadoc-style comments in the idl files.
Generating GUIDs
guids are used in mozilla programming for identifying several types of entities, including xpcom interfaces (this type of guids is
callled iid), components (cid), and legacy add-ons—like extensions and themes—that were created prior to firefox 1.5.
Preface
organization of the tutorial the following list provides an overview of the steps that we will take to build an xpcom component
called weblock, which provides site blocking functionality to gecko-based browsers.
Creating XPCOM components
registration process the registration methods creating an instance of your component weblock1.cpp using xpcom utilities to make things easier xpcom macros generic xpcom module macros common implementation macros declaration macros weblock2.cpp string classes in xpcom using strings nsembedstring and nsembedcstring smart pointers starting weblock getting
called at startup registering for notifications getting access to the category manager providing access to weblock creating the weblock programming interface defining the weblock interface in xpidl the xpidl syntax scriptable interfaces subclassing nsisupports the web locking interface implementing weblock declaration macros representing return values in xpcom xpid...
XPCOM hashtable guide
good hashtable implementations will automati
cally resize the hashtable in memory if extra space is needed, or if too much space has been allocated.
mozilla::services namespace
the services 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.
How To Pass an XPCOM Object to a New Window
a more useful example is available in the source code: toolkit/components/help/content/contexthelp.js#61 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.
Components.interfaces
this includes nsisupports.queryinterface(), the optional parameter accepted by nsijscid.getservice(), nsijscid.createinstance() when
called from javascript, and nsiclassinfo.getinterfaces().
Components.isSuccessCode
to determine the success or failure of the complex task, you would
call components.issuccesscode() upon the status code included in the notification.
Components.manager
the scriptable methods on the nsicomponentmanager interface can be
called directly on this object.
Components.stack
components.stack is a read only property of type nsistackframe (idl definition) that represents a snapshot of the current javascript
callstack.
Components.utils.createObjectIn
create a new object in the scope of a specified dom window, you can simply do: function genpropdesc(value) { return { enumerable: true, configurable: true, writable: true, value: value }; } var myobject = components.utils.createobjectin(mywindow); var proplist = { name: genpropdesc("name"), date: genpropdesc("date"), id: genpropdesc("id"), func: genpropdesc(function() { alert("
called func!"); }) }; object.defineproperties(myobject, proplist); components.utils.makeobjectpropsnormal(myobject); this sets up the new object in the scope of the object mywindow, then adds properties by
calling object.defineproperties(), then normalizes them by
calling components.utils.makeobjectpropsnormal().
Components.utils.forceGC
the mozilla javascript engine will perform garbage collection automati
cally when the javascript heap grows beyond a certain size.
Components.utils.import
example components.utils.import("resource://gre/modules/xpcomutils.jsm", this); difference from mozijssubscriptloader the differences from mozijssubscriptloader: the behavior when importing/loading the same code from different locations: the subscript loader evaluates the specified code each time it is invoked, with the
caller's global object.
Components.utils.setGCZeal
this method
calls through to that thusly: js_setgczeal(<current context>, zeal, js_default_zeal_freq, false); syntax components.utils.setgczeal(zeal); where zeal is the zeal value you wish to use.
Using components
} interfacesbyid=[object nsxpccomponents_interfacesbyid] classesbyid=[object nsxpccomponents_classesbyid] stack=js frame :: scratchpad/4 :: cdump :: line 8 manager=[xpconnect wrapped nsicomponentmanager] id=[object nsxpccomponents_id] exception=[object nsxpccomponents_exception] reporterror=function reporterror() { [native code] } cancreatewrapper=function cancreatewrapper() { [native code] } can
callmethod=function can
callmethod() { [native code] } cangetproperty=function cangetproperty() { [native code] } cansetproperty=function cansetproperty() { [native code] } ...
Realloc
the result must be freed with a
call to nsmemory::free when it is no longer needed.
RefPtr
this is done using the functions addref() and release(), which respectively modify a variable of type nsautorefcnt, which basi
cally is a wrapper around a count of the number of references refering to the class.
IAccessibleHyperlink
this interface could also be applied to other kinds of objects with multiple actions such as "smart tags" which are objects, typi
cally strings, which have multiple actions such as "activate uri", "bookmark uri", end so on.
IAccessibleHypertext
1.0 66 introduced gecko 1.9 inherits from: iaccessibletext last changed in gecko 1.9 (firefox 3) the iaccessiblehypertext interface is the main interface to expose hyperlinks in a document, typi
cally a text document, that are used to reference other documents.
IAccessibleImage
some examples are: the accessible name and description() are not enough to fully describe the image, for example when the accessible description() is used to define the behavior of an actionable image and the image itself conveys semanti
cally significant information.
amIWebInstallPrompt
toolkit/mozapps/extensions/amiwebinstalllistener.idlscriptable
called when installation by websites is currently disabled.
imgIContainerObserver
methods native code only!framechanged
called when the frame for an image container has changed.
imgIEncoder
the alternative is to use startimageencode(),
call addimageframe() one or more times, and then finish initialization with endimageencode().
mozIPersonalDictionary
; void getcorrection(in wstring word, [array, size_is(count)] out wstring words, out pruint32 count); void ignoreword(in wstring word); void load(); void removecorrection(in wstring word,in wstring correction, in wstring lang); void removeword(in wstring word, in wstring lang); void save(); attributes attribute type description wordlist nsistringenumerator get the (lexicographi
cally sorted) list of words.
mozIStorageStatementRow
for example, say you create a statement like so: var statement = dbconn.createstatement("select id, name from table_name"); the object would have two properties, id and name, that can be used to get the value of the column after you have
called mozistoragestatement.executestep() like so: while (statement.executestep()) { let id = statement.row.id; let name = statement.row.name; } see also storage mozistoragestatement ...
TakeFocus
it is the
callers responsibility to determine whether this node is focusable.acctakefocus on a node that is not normally focusable (such as a table), will still set focus on that node, although normally that will not be visually indicated in most style sheets.
nsIAccessibleHyperText
accessible/public/nsiaccessiblehypertext.idlscriptable this interface is the main interface to expose hyperlinks in a document, typi
cally a text document, that are used to reference other documents.
nsIAutoCompleteSearch
inherits from: nsisupports last changed in gecko 1.7 users
call startsearch() and pass in an nsiautocompleteobserver when the search starts.
nsIBadCertListener2
method overview boolean notifycertproblem(in nsiinterfacerequestor socketinfo, in nsisslstatus status, in autf8string targetsite); methods notifycertproblem()
called in case of a broken ssl status.
nsICacheMetaDataVisitor
inherits from: nsisupports last changed in gecko 1.7 method overview boolean visitmetadataelement(in string key, in string value); methods visitmetadataelement() this method is
called for each key/value pair in the meta data for a cache entry.
nsICancelable
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void cancel(in nsresult areason); methods cancel()
call this method to request that this object abort whatever operation it may be performing.
nsICategoryManager
xpcom/components/nsicategorymanager.idlscriptable this interface provides access to a data structure that holds a list of name-value pairs,
called categories, where each value is a list of strings.
nsIClipboard
it does not actually retrieve the data and should be a very inexpensive
call.
nsIConsoleListener
inherits from: nsisupports last changed in gecko 1.7 method overview void observe(in nsiconsolemessage amessage); methods observe()
called by the nsiconsoleservice when a message is posted to the console.
nsIContentPref
see also nsicontentprefservice2 nsicontentpref
callback2 ...
nsIContentViewManager
once you have the view manager, you can
call getcontentviewsin() to get a list of the content views for a given portion of the browser display, then use those nsicontentview objects to manipulate the content views.
nsIController
inherits from: nsisupports last changed in gecko 1.7 method overview void docommand(in string command); boolean iscommandenabled(in string command); void onevent(in string eventname); boolean supportscommand(in string command); methods docommand() when this method is
called, your implementation should execute the command with the specified name.
nsIConverterInputStream
this allows reading unicode strings from a stream, automati
cally converting the bytes from a selected character encoding.
nsICookieService
this typi
cally happens because they have either expired or because the cookie list has grown too large.
nsIDNSListener
inherits from: nsisupports last changed in gecko 1.7 method overview void onlookupcomplete(in nsicancelable arequest, in nsidnsrecord arecord, in nsresult astatus); methods onlookupcomplete()
called when an asynchronous host lookup completes.
nsIDNSRecord
since a dns query may return more than one resolved ip address, the record acts like an enumerator, allowing the
caller to easily step through the list of ip addresses.
nsIDNSRequest
inherits from: nsisupports last changed in gecko 1.7 method overview void cancel(); methods cancel()
called to cancel a pending asynchronous dns request.
nsIDOMFileException
the nsidomfileexception interface represents exceptions that can be raised by
calls to the methods in the nsidomfile interface.
nsIDOMHTMLAudioElement
exceptions thrown ns_error_dom_invalid_state_err the stream has not been initialized for writing by a
call to mozsetup().
nsIDOMHTMLSourceElement
note that dynami
cally manipulating this value after the page has loaded has no effect on the containing element; instead, change the src attribute of that element (audio or video) instead.
nsIDOMHTMLTimeRanges
each time range represented by an nsidomhtmltimeranges object has an index number; you
call the start() and end() methods to obtain the start and end times of each range, specifying the index number of the range to look up.
nsIDOMStorageList
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview nsidomstorage nameditem(in domstring domain); methods nameditem()
called when the list of available access points changes.
nsIDOMWindow
yscrolldif the number of pixels by which to scroll verti
cally.
nsIDOMXPathEvaluator
note: prior to gecko 1.9, you could
call this method on documents other than the one you planned to run the xpath against; starting with gecko 1.9, however, you must
call it on the same document.
nsIDOMXULElement
click() unless the element is disabled, sends mouse events that simulate the effect of clicking the mouse on the element, then
calls the docommand() method.
nsIDebug2
this is normally zero in release builds, but does include
calls to nsidebug.assertion().
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.
getFiles
« xpcom api reference summary this method is
called by the directory service to query an enumeration of file or directory locations.
nsIDirectoryServiceProvider2
inherits from: nsidirectoryserviceprovider last changed in gecko 0.9.6 method overview nsisimpleenumerator getfiles(in string prop); methods getfiles() the directory service
calls this when it gets a request for a prop and the requested type is nsisimpleenumerator.
nsIDownload
mimeinfo nsimimeinfo provides the targets relevant mime information, including its mime type, helper application, and whether or not the helper should be executed automati
cally once the download is complete.
nsIDownloadHistory
there is a separate interface specifi
cally for downloads in case embedders choose to track downloads differently from other types of history.
nsIDownloadObserver
inherits from: nsisupports last changed in gecko 1.7 method overview void ondownloadcomplete(in nsidownloader downloader, in nsirequest request, in nsisupports ctxt, in nsresult status, in nsifile result); methods ondownloadcomplete()
called to signal a download that has completed.
nsIDownloader
if an explicit download location is specified then the resulting file will not be deleted, and it will be the
callers responsibility to keep track of the file, and so on.
nsIDragDropHandler
hookupto() attaches drag handlers to a specified receiver, setting up
callbacks to let built-in behaviors be overridden.
nsIDragSession
can be
called while the drag is in process or after the drop has completed.
nsIEditorObserver
66 introduced gecko 1.0 obsolete gecko 18 inherits from: nsisupports last changed in gecko 1.7 method overview void editaction(); methods editaction()
called after the editor completes a user action.
nsIErrorService
if no key is registered for the specified nsresult, then the
caller should use the nsresult's code (obtained with ns_error_get_code) instead.
nsIEventListenerService
system-group eventlisteners are
called after all eventlisteners in default-group handle the events.
nsIExternalProtocolService
specifi
cally, this looks to see whether there are any known possible application handlers in either the nsihandlerservice datastore or registered with the os.
nsIFTPChannel
you can determine if a channel is an ftp channel by checking to see if it implements this interface, by
calling nsisupports.queryinterface() on it.
nsIFTPEventSink
it can be used as a notification
callback on an ftp channel.
nsIFactory
unlike getservice, this returns a new instance each time it is
called.
nsIFeedEntry
this is generated automati
cally using the entry's description, subtitle, summary, content, and appropriate extensions.
nsIFeedResultListener
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void handleresult(in nsifeedresult result); methods handleresult()
called when feed processing is complete.
nsIFileStreams
close_on_eof 1<<2 if this is set, the file will close automati
cally when the end of the file is reached.
nsIFrameLoader
behaves identi
cally to loadframe(), except that this method lets you specify the uri to load.
nsIHapticFeedback
o 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/widget/hapticfeedback;1 as a service: var hapticfeedback = components.classes["@mozilla.org/widget/hapticfeedback;1"] .getservice(components.interfaces.nsihapticfeedback); once you have the service, you can initiate haptic feedback (that is, cause the device to vibrate, if it's supported) by
calling performsimpleaction(): hapticfeedback.performsimpleaction(components.interfaces.nsihapticfeedback.longpress); method overview void performsimpleaction(in long islongpress); constants press length constants constant value description shortpress 0 specify as the action type to perform a short vibration.
nsIHttpActivityDistributor
void addobserver( in nsihttpactivityobserver aobserver ); parameters aobserver the nsihttpactivityobserver that should receive notifications of http transport activity; this object's nsihttpactivityobserver.observeactivity() method will be
called each time activity occurs.
nsIHttpHeaderVisitor
inherits from: nsisupports last changed in gecko 1.7 method overview void visitheader(in acstring aheader, in acstring avalue); methods visitheader()
called by the nsihttpchannel implementation when visiting request and response headers.
nsIInstallLocation
note: this is a clone of the actual location which the
caller can modify freely.
nsILivemarkService
note: the
caller is responsible for reloading the livemark after changing its feed uri (since the contents are likely to be different given a different feed).
nsILocaleService
calls to its getcategory method return the values originally passed to the locale definition's addcategory method.
nsILoginMetaInfo
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) you can specifi
cally modify these values by passing changes into nsiloginmanager.modifylogin() using an nsipropertybag2 object as the input.
nsIMacDockSupport
the application should
call this to activate itself when one of its dock menu items are selected, since doing so does not automati
cally activate the application.
nsIMemoryReporterManager
ultireporter reporter); 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).
nsIMessageListener
when the listener is
called, 'this' value is the target of the message.
nsIMicrosummary
if you want know when a microsummary finishes updating, add an observer before
calling this method.
nsIMicrosummaryGenerator
for generators installed via some other mechanism (for example an extension that dynami
cally creates generators), this uri is a urn in a form of the extension's own choosing, with the only restriction being that the uri be globally unique.
nsIMimeConverter
set, in long fieldnamelen, in long encodedwordsize); string decodemimeheadertocharptr(in string header, in string default_charset, in boolean override_charset, in boolean eatcontinuations); astring decodemimeheader(in string header, in string default_charset, in boolean override_charset, in boolean eatcontinuations); mimeencoderdata *b64encoderinit(in mimeconverteroutput
callback output_fn, in void *closure); mimeencoderdata *qpencoderinit(in mimeconverteroutput
callback output_fn, in void *closure); void encoderdestroy(in mimeencoderdata *data, in boolean abort_p); long encoderwrite(in mimeencoderdata *data, in string buffer, in long size); methods encodemimepartiistr() an variant of encodemimepartiistr_utf8() which treats the hea...
nsIMsgAccount
exceptions thrown ns_error_already_opened if it is
called more then once removeidentity() removes an identity from this account.
nsIMsgCustomColumnHandler
) { }, getsortstringforrow: function(ahdr) { return ""; }, isstring: function() {return true;}, getcellproperties: function(arow, acol, aprops) { }, getrowproperties: function(arow, aprops) { }, getimagesrc: function(arow, acol) {return null;}, getsortlongforrow: function(ahdr) {return 0;} } to attach it use the nsimsgdbview.addcolumnhandler() method (re
call 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 getsortstringforro...
nsIMsgDBHdr
headers are backed by the database: a
call to these functions directly modifies the state of the database, although it is not saved until the database is committed.
nsIMsgIncomingServer
this destroys all pref values do not
call this unless you know what you're doing!
nsIMsgSearchNotify
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(); }; ...
nsINavHistoryQuery
when
called as a getter, this returns an array of strings sorted in ascending lexicographical (alphabetical) order.
nsIPlacesView
this may be modified dynami
cally to update the view.
nsIProcess2
ents.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess2); method overview void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); methods runasync() asynchronously runs the process with which the object was initialized, optionally
calling an observer when the process finishes running.
nsIProtocolProxyFilter
method overview nsiproxyinfo applyfilter(in nsiprotocolproxyservice aproxyservice, in nsiuri auri, in nsiproxyinfo aproxy); methods applyfilter() this method is
called to apply proxy filter rules for the given uri and proxy object (or list of proxy objects).
nsIPushMessage
when
called from javascript, nsipushmessage.binary() returns data.
nsIPushSubscription
when
called from javascript, nsipushsubscription.getkey() only takes name as a parameter, and returns key.
nsISSLErrorListener
method overview boolean notifysslerror(in nsiinterfacerequestor socketinfo, in print32 error, in autf8string targetsite); methods notifysslerror()
called in case of an ssl error.
nsISSLSocketControl
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void proxystartssl(); void starttls(); attributes attribute type description forcehandshake boolean obsolete since gecko 1.9 notification
callbacks nsiinterfacerequestor methods proxystartssl() starts an ssl proxy connection.
nsIScreenManager
this pointer's definition is specific to the platform's native widget implementation, and is typi
cally of the same type as ns_native_window.
nsIStructuredCloneContainer
once you've initialized the container, you can get a copy of the object it stores by
calling deserializetovariant().
nsISupports
note: the interface pointer, aresult, returned by queryinterface must be released by a
call to release() when it is no longer needed.
nsISupportsPriority
typi
cally this attribute is initialized to priority_normal, but implementations may choose to assign a different initial value.
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.
nsITaskbarPreviewController
the specified context is attached to a surface with the controller's width and height, the values of which are obtained immediately prior to
calling this method.
nsITelemetry
void capturestack(in acstring name); jsval snapshotcapturedstacks([optional] in boolean clear); nsisupports getloadedmodules(); jsval snapshotkeyedhistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); void sethistogramrecordingenabled(in acstring id, in boolean enabled); void asyncfetchtelemetrydata(in nsifetchtelemetrydata
callback a
callback); double mssinceprocessstart(); void scalaradd(in acstring aname, in jsval avalue); void scalarset(in acstring aname, in jsval avalue); void scalarsetmaximum(in acstring aname, in jsval avalue); jsval snapshotscalars(in uint32_t adataset, [optional] in boolean aclear); void keyedscalaradd(in acstring aname, in astring akey, in js...
nsIToolkitProfileService
profiles nsisimpleenumerator an enumerator providing access to the list of profiles; each profile is an nsitoolkitprofile object (though you must first
call aprofile.queryinterface(components.interfaces.nsitoolkitprofile) to get access to its attributes and methods).
nsITreeColumns
invalidatecolumns() this method is
called whenever a treecol is added or removed and the column cache needs to be rebuilt.
nsIXPCException
the
call signature of the constructor is: components.exception(message, result, stack, data, inner) all parameters are optional and the appropriate placeholder is 'unknown'.
nsIZipReaderCache
note: if nsizipreader.close has been
called on the shared nsizipreader, this method will return the closed nsizipreader nsizipreader getzip( in nsifile zipfile ); parameters zipfile the zip file.
NS_StringGetData
« xpcom api reference summary the ns_stringgetdata function gives the
caller access to the string's internal buffer.
nsGetModuleProc
#include "nsxpcom.h" typedef nsresult (pr_
callback *nsgetmoduleproc)( nsicomponentmanager *acompmgr, nsifile* alocation, nsimodule** aresult ); parameters acompmgr [in] the xpcom component manager.
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.
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.
Troubleshooting XPCOM components registration
registration failure if the module is loading correctly but doesn't register its components, try adding
calls to components.utils.reporterror("debug me!"); in nsgetmodule() and other functions to try and find any errors.
Using the Gecko SDK
the abi of the component interfaces depends on the c++ abi of the host compiler (i.e., the vtable format and
calling conventions of the virtual methods may vary from compiler to compiler).
nsCOMPtr versus RefPtr
the downside of this inheritance is that do_queryobject requires an extra virtual
call to operator() in the helper method.
XPIDL Syntax
lexi
cally, tokens are delimited by whitespace (defined here as spaces, tabs, vertical tabs, form feeds, line feeds, and carriage returns, or [ \t\v\f\r\n] in regular expression form).
pyxpidl
-o outputfile (this isn't just the base name, but needs to include the extension; for example -o /tmp/nsifoo.idl) -e specify an explicit output file name (-e /tmp/nsifoo.idl for example) n/a (this is subsumed by -o now) -d write dependencies (requires -e) -d (unchanged) -m specify output mode n/a (feature removed; use header.py or typelib.py specifi
cally) it's worth noting that the old output mode options for generating documentation and java interfaces (-m doc and -m java) have no equivalents in pyxpidl.
xpidl
it generates: c++ header files (.h), with a commented template for full c++ implementation of the interface xpconnect typelib files (.xpt), with runtime type information to dynami
cally
call xpcom objects through xpconnect note: starting in gecko 9.0, xpidl has been replaced with pyxpidl in the gecko sdk.
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 automati
cally when visiting a page with the appropriate xslt processing instruction (and which isn't processed by firefox's own xslt 1.0 processor).
Spam filtering
the user can configure junk mail can be automati
cally purged from the "junk" folder.
Thunderbird Binaries
additionally, ad-hoc packages
called try builds are made available on an as-needed basis to allow for testing of certain patches, and are typi
cally announced in related bug reports.
Building a Thunderbird extension 1: introduction
the extension filesystem (setting up your local system) install manifest (the install.rdf file that contains meta-information about the extension) chrome manifest (list of packages and overlays) xul (the xml user interface language that is used to modify the thunderbird user interface) adding javascript (explains how to add some simple javascript to your thunderbird extension) installing lo
cally (enabling the extension on your local thunderbird instance) packaging (making a distribution package that contains the extension) distributing (from your own site or from http://addons.mozilla.org/) this tutorial is compatible with thunderbird versions 2,3 and 5.
Building a Thunderbird extension 3: install manifest
open the file
called install.rdf that you created at the top of your extension's directory hierarchy and paste the following text into the 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:id>myfirstext@jen.zed</em:id> <em:name>my first extension</em:name> <em:version>1.0</em:version> <em:creator>jenzed</em:creator> <em:targetapplication> <description> <em:id>{3550f7...
Access Window
register a timer window.setinterval( function() { alert('foobar'); }, 60000); //execute the function once very minute if you periodi
cally need to perform a certain action then you can use the setinterval function, it will then
call this function every x milliseconds, in this case every 60000ms or one minute.
Use SQLite
this will create an sqlite db named tbird.sqlite inside your profile directory with a table
called attachments.
Styling the Folder Pane
treeview row/cell properties css property equivalent
call explanation foldernamecol -- a property for indicating that a column is the folder name column.
Tips and Tricks from the newsgroups
extensions load an extension in its own tab run shell scripts from an extension (for example, to create a symlink) get extension metadata
call java from thunderbird extensions (also an example here, written for firefox but compatible with thunderbird 3.x) define a custom protocol handler to
call an external program save attachment and send it repeat image display using css sprites messages use reminderfox to open a message in the default thunderbird message window (when messageuri, folderuri and gdbview are un...
Using tab-modal prompts
an alert!"]; prompt.alert.apply(null, promptargs); nsiprompt will automati
cally fall back to window-modal prompts when necessary (such as in situations in which tab-modal prompts aren't supported, or for prompts displayed outside the context of a tab).le to use other forms of the prompts of nsipromptservice interface see the example code.
Virtualenv
the mozilla build system mostly uses .pth files instead of the more typi
cally used python setup.py develop or python setup.py install to install python modules in to the virtualenv's python path due to performance concerns (although such functionality is available via the setup.py keyword in a packages.txt file).
Examples
lightweight bridge for
calling cocoa frameworks from javascript, js-macosx transparently handles definition of cocoa api, both c and objective-c, and provides automatic declarations for framework functions, structures, constants and enumerations, as well as allows creating and subclassing cocoa classes.
Memory Management
closures you also need to be sure to retain references to any javascript code that native code may
call back into.
Type conversion
implicit convert in js-ctypes, data could be converted implicitly when passing to or returning from a functiontype
call, or setting pointer content, an array element or a struct field.
Working with ArrayBuffers
method 3: transfer byte array by
calling memcpy this is the recommended method, as it only takes a couple of milliseconds, even for large arrays.
CData
methods available on string objects these methods must be
called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by a null character.
FunctionType
this is the result of
calling ctypes.pointertype(the_type).
PointerType
this is the result of
calling ctypes.pointertype(the_type).
Preferences System
usage in xulrunner applications when
calling opendialog() to open a preferences dialog, "toolbar" should be included in the features string.
Color vision simulation - Firefox Developer Tools
in the simulate menu, you can choose one option at a time from the following list: none — choose this to return to normal display protanomaly (low red) deuteranomaly (low green) tritanomaly (low blue) protanopia (no red) deuteranopia (no green) tritanopia (no blue) contrast loss these simulations are not completely medi
cally accurate.
Browser Console - Firefox Developer Tools
m"); var hudservice = devtools.require("devtools/client/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); var clearbtn = hud.chromewindow.document.queryselector('.webconsole-clear-console-button'); clearbtn.addeventlistener('mouseover', function() { hud.jsterm.clearoutput(true); }, false); bonus features available for add-on sdk add-ons, the console api is available automati
cally.
Debug worker threads - Firefox Developer Tools
you can set a breakpoint (or logpoint) on any active worker thread: when execution is paused in a worker thread, the context of the debugger is updated to show the correct breakpoints,
call stack, etc., just as you'd expect.
Access debugging in add-ons - Firefox Developer Tools
the following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.addeventlistener("debugger:editorloaded") -
called when the read-only script panel loaded.
Step through code - Firefox Developer Tools
step in: advance to the next line in the function, unless on a function
call, in which case enter the function being
called step out: run to the end of the current function, in which case, the debugger will skip the return value from a function, returning execution to the
caller split console when paused, you can press the esc key to open and close the split console to gain more insight into errors and variables: pause on breakpoints overlay since firefox 70, when your code is paused on a breakpoint an overlay appears on the viewport of the tab you are deb...
Using the Debugger map scopes feature - Firefox Developer Tools
when you click the increment button on the page and hit the breakpoint, an additional section is added to the right-hand panel below the
call stack to display variables mapped from the original scope, like this: as useful as this is, it would be even nicer if you could view the original code (before it was packages into the "bundle.js" file.
Deprecated tools - Firefox Developer Tools
canvas debugger bugzilla issue: bug 1403938 removed as of firefox 67 description canvas debugger allowed users to inspect the canvas element and see how frequently a given function is
called.
DOM allocation example - Firefox Developer Tools
.appendchild(toolbarbutton); } return toolbar; } function createtoolbars() { var container = document.getelementbyid("container"); for (var i = 0; i < toolbarcount; i++) { var toolbar = createtoolbar(); container.appendchild(toolbar); } } createtoolbars(); a simple pseudocode representation of how this code operates looks like this: createtoolbars() -> createtoolbar() //
called 200 times, creates 1 div element each time -> createtoolbarbutton() //
called 20 times per toolbar, creates 1 span element each time in total, then, it creates 200 htmldivelement objects, and 4000 htmlspanelement objects.
Monster example - Firefox Developer Tools
specifi
cally: the code creates an object with three properties, each an array: one for fierce monsters one for friendly monsters one for monsters who haven't decided yet.
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.
Frame rate - Firefox Developer Tools
switch to the flame chart to see the
call stack at that point: the offending function is
called dopointlesscomputations(), and it's defined in "main.js".
How to - Firefox Developer Tools
select a tool to switch between the waterfall,
call tree, and flame chart tools, use the buttons in the toolbar: configure markers displayed to control which markers are shown in the waterfall, use the button in the toolbar: zoom in to zoom into a slice of the recording, select that slice in the recording overview: ...
Settings - Firefox Developer Tools
note that this option was
called "disable cache" in firefox versions previous to 49, but it was renamed to make it clearer that this affects the http cache, and not service workers/the cache api.
Shader Editor - Firefox Developer Tools
with webgl you provide 2 programs
called shaders which are
called at the appropriate stages of the opengl rendering pipeline: a vertex shader, which computes the clip space coordinates of each vertex to be drawn, and a fragment shader, which determines the color for each pixel to be drawn.
Web Console - Firefox Developer Tools
the toolbox appear at the bottom, left, or right of the browser window (depending on your docking settings), with the web console activated (it's just
called console in the devtools toolbar).
AbsoluteOrientationSensor - Web APIs
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.onerror - Web APIs
the abstractworker.onerror property of the abstractworker interface represents an eventhandler, that is a function to be
called when the error event occurs and bubbles through the worker.
Accelerometer.Accelerometer() - Web APIs
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.
AmbientLightSensor.AmbientLightSensor() - Web APIs
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.
AnalyserNode.maxDecibels - Web APIs
the maxdecibels property of the analysernode interface is a double value representing the maximum power value in the scaling range for the fft analysis data, for conversion to unsigned byte/float values — basi
cally, this specifies the maximum value for the range of results when using getfloatfrequencydata() or getbytefrequencydata().
AnalyserNode.minDecibels - Web APIs
the mindecibels property of the analysernode interface is a double value representing the minimum power value in the scaling range for the fft analysis data, for conversion to unsigned byte/float values — basi
cally, this specifies the minimum value for the range of results when using getfloatfrequencydata() or getbytefrequencydata().
Animation.ready - Web APIs
you'll typi
cally use a construct similar to this when using the ready promise: animation.ready.then(function() { // do whatever needs to be done when // the animation is ready to run }); example in the following example, the state of the animation will be running when the current ready promise is resolved because the animation does not leave the pending play state in between the
calls to pause and play an...
Attr.localName - Web APIs
qualified names are typi
cally used in xml as part of the namespace(s) of the particular xml documents.
AudioBuffer - Web APIs
objects of these types are designed to hold small audio snippets, typi
cally less than 45 s.
AudioBufferSourceNode.loopEnd - Web APIs
then the current play position will loop back to the 20 second mark and continue playing until the 25 second mark, ad infinitum (or at least until stop() is
called).
AudioConfiguration - Web APIs
the audioconfiguration dictionary of the media capabilities api defines the audio file being tested when
calling mediacapabilities.encodinginfo() or mediacapabilities.decodinginfo() to query whether a specific audio configuration is supported, smooth, and/or power efficient.
AudioContext.createMediaElementSource() - Web APIs
document.documentelement.scrolltop : document.body.scrolltop); gainnode.gain.value = cury/height; } // 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(gainnode); gainnode.connect(audioctx.destination); note: as a consequence of
calling createmediaelementsource(), audio playback from the htmlmediaelement will be re-routed into the processing graph of the audiocontext.
AudioContext.createMediaStreamSource() - Web APIs
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.
AudioContextOptions.sampleRate - Web APIs
this value should typi
cally be between 8,000 hz and 96,000 hz; the default will vary depending on the output device, but the sample rate 44,100 hz is the most common.
AudioListener.dopplerFactor - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.forwardX - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.forwardY - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.forwardZ - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.positionX - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.positionY - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.positionZ - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.setOrientation() - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.setPosition() - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.upX - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.upY - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener.upZ - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioListener - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
AudioNode - Web APIs
slightly better performance: in both chrome and firefox, the factory methods
call the constructors internally.
AudioTrack.id - Web APIs
syntax var trackid = audiotrack.id; value a domstring which identifies the track, suitable for use when
calling gettrackbyid() on an audiotracklist such as the one specified by a media element's audiotracks property.
AudioTrack - Web APIs
this id can be used to locate a specific track within an audio track list by
calling audiotracklist.gettrackbyid().
AudioTrackList.getTrackById() - Web APIs
function disablecharacter(videoelem, charactername) { videoelem.audiotracks.gettrackbyid(charactername).enabled = false; } this short function gets the audiotracklist containing the video's audio tracks using htmlmediaelement.audiotracks, then
calls gettrackbyid() on it, specifying the character's name.
AudioTrackList.onremovetrack - Web APIs
the audiotracklist onremovetrack event handler is
called when the removetrack event occurs, indicating that an audio track has been removed from the media element, and therefore also from the audiotracklist.
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.
AuthenticatorAssertionResponse - Web APIs
the assertion signature is created with the private key of keypair that was created during the navigator.credentials.create()
call and verified using the public key of that same keypair.
BaseAudioContext.createConvolver() - Web APIs
the basic premise is that you create an audiobuffer containing a sound sample to be used as an ambience to shape the convolution (
called the impulse response,) and apply that to the convolver.
BaseAudioContext.createGain() - Web APIs
iv> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success
callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error
callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
BaseAudioContext.createPanner() - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
BaseAudioContext.onstatechange - Web APIs
the onstatechange property of the baseaudiocontext interface defines an event handler function to be
called when the statechange event fires: this occurs when the audio context's state changes.
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.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.
BatteryManager.chargingTime - Web APIs
even if the time returned is precise to the second, browsers round them to a higher interval (typi
cally to the closest 15 minutes) for privacy reasons.
BatteryManager.onlevelchange - Web APIs
syntax navigator.battery.onlevelchange = funcref where battery is a batterymanager object, and funcref is a function to be
called when the levelchange event occurs.
BeforeInstallPromptEvent.prompt() - Web APIs
example var istoosoon = true; window.addeventlistener("beforeinstallprompt", function(e) { if (istoosoon) { e.preventdefault(); // prevents prompt display // prompt later instead: settimeout(function() { istoosoon = false; e.prompt(); // throws if
called more than once or default not prevented }, 10000); } // the event was re-dispatched in response to our request // ...
Bluetooth.getDevices() - Web APIs
the program can detect when a device comes online or into range by watching for bluetooth advertisements by
calling bluetoothdevice.watchadvertisements() on that device.
Bluetooth - Web APIs
bluetooth.getdevices() returns a promise that resolved to an array of bluetoothdevices which the origin already obtained permission for via a
call to bluetooth.requestdevice().
Body.bodyUsed - Web APIs
notice that we log response.bodyused to the console once before the response.blob()
call and once after.
Body.formData() - Web APIs
if a user submits a form and a service worker intercepts the request, you could for example
call formdata() on it to obtain a key-value map, modify some fields, then send the form onwards to the server (or use it lo
cally).
Body - Web APIs
examples the example below uses a simple fetch
call to grab an image and display it in an <img> tag.
BroadcastChannel.onmessageerror - Web APIs
the onmessageerror event handler of the broadcastchannel interface is an eventlistener,
called whenever an messageevent of type messageerror is fired on the broadcastchannel instance — that is, when it receives a message that cannot be deserialized.
BroadcastChannel - Web APIs
broadcastchannel.onmessageerror an eventhandler
called when a messageevent of type messageerror is fired—that is, when it receives a message that cannot be deserialized.
CSS.paintWorklet (Static property) - Web APIs
paintworklet is a static, read-only property of the css interface that provides access to the paintworklet, which programmati
cally generates an image where a css property expects a file.
CSSMathProduct - Web APIs
the cssmathproduct interface of the css typed object model api represents the result obtained by
calling add(), sub(), or tosum() on cssnumericvalue.
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.
CSSMathSum - Web APIs
the cssmathsum interface of the css typed object model api represents the result obtained by
calling add(), sub(), or tosum() on cssnumericvalue.
CSSStyleDeclaration.setProperty() - Web APIs
if priority can be omitted, javascript has a special simpler syntax for setting a css property on a style declaration object: style.csspropertyname = 'value'; examples in this example we have three buttons, which can be pressed to dynami
cally alter our box paragraph's border, background color, and text color to random values (see the live example at the end of this section).
CSSStyleSheet - Web APIs
a cssstylesheet object is created and inserted into the document's document.stylesheets list automati
cally by the browser, when a stylesheet is loaded for a document.
Using dynamic styling information - Web APIs
in many cases, and where possible, it really is best practice to dynami
cally manipulate classes via the classname property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet.
Cache.addAll() - Web APIs
this consists of
calling cachestorage.open to create a new cache, then using addall() to add a series of assets to it.
Cache.matchAll() - Web APIs
note: cache.match() is basi
cally identical to cache.matchall(), except that rather than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]).
CacheStorage.match() - Web APIs
equivalent functionality is to
call cache.match() on each cache (in the order returned by caches.keys()) until a response is returned.
CacheStorage.open() - Web APIs
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
this consists of
calling cachestorage.open to create a new cache, then using cache.addall to add a series of assets to it.
CanvasRenderingContext2D.drawImage() - Web APIs
the specification permits any canvas image source (canvasimagesource), specifi
cally, a cssimagevalue, an htmlimageelement, an svgimageelement, an htmlvideoelement, an htmlcanvaselement, an imagebitmap, or an offscreencanvas.
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) automati
cally adds to the current sub-path, which means that all the lines will all be stroked or filled together.
CanvasRenderingContext2D.resetTransform() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw a rotated rectangle ctx.rotate(45 * math.pi / 180); ctx.fillrect(60, 0, 100, 30); // reset transformation matrix to the identity matrix ctx.resettransform(); result continuing with a regular matrix whenever you're done drawing transformed shapes, you should
call resettransform() before rendering anything else.
ChannelMergerNode - Web APIs
if channelmergernode has one single output, but as many inputs as there are channels to merge; the number of inputs is defined as a parameter of its constructor and the
call to audiocontext.createchannelmerger.
ChannelSplitterNode - Web APIs
if your channelsplitternode always has one single input, the amount of outputs is defined by a parameter on its constructor and the
call to audiocontext.createchannelsplitter().
ChildNode.after() - Web APIs
wing code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('after')) { return; } object.defineproperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argarr = array.prototype.slice.
call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
ChildNode.before() - Web APIs
code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('before')) { return; } object.defineproperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argarr = array.prototype.slice.
call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
ClipboardEvent.clipboardData - Web APIs
the clipboardevent.clipboarddata property holds a datatransfer object, which can be used: to specify what data should be put into the clipboard from the cut and copy event handlers, typi
cally with a setdata(format, data)
call; to obtain the data to be pasted from the paste event handler, typi
cally with a getdata(format)
call.
ClipboardItem - Web APIs
access to the contents of the clipboard is gated behind the permissions api: the clipboard-write permission is granted automati
cally to pages when they are in the active tab.
Clipboard API - Web APIs
access to the contents of the clipboard is gated behind the permissions api: the clipboard-write permission is granted automati
cally to pages when they are in the active tab.
Console.countReset() - Web APIs
examples for example, given code like this: let user = ""; function greet() { console.count(); return "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count(); console.countreset(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" "default: 0" note that the
call to console.counterreset() resets the value of the default counter to zero.
Console API - Web APIs
find out about these at: google chrome devtools implementation safari devtools implementation usage is very simple — the console object — available via window.console, or workerglobalscope.console in workers; accessible using just console — contains many methods that you can
call to perform rudimentary debugging tasks, generally focused around logging various values to the browser's web console.
ConstrainBoolean - Web APIs
candidate recommendation initial definition techni
cally, constrainboolean is actually based on an intermediary dictionary named constrainbooleanparameters, which adds exact and ideal to the simple boolean type.
ConstrainDOMString - Web APIs
candidate recommendation initial definition techni
cally, constraindomstring is actually based on an intermediary dictionary named constraindomstringparameters, which adds exact and ideal to domstring.
ConstrainDouble - Web APIs
candidate recommendation initial definition techni
cally, constraindouble is actually based on an intermediary dictionary named constraindoublerange, which adds exact and ideal to doublerange, with constraindouble being a type that can be either a long integer or a doublerange.
ConstrainULong - Web APIs
candidate recommendation initial definition techni
cally, constrainulong is actually based on an intermediary dictionary named constrainulongrange, which adds exact and ideal to ulongrange, with constrainulong being a type that can be either a long integer or a ulongrange.
CustomElementRegistry - Web APIs
// create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always
call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent return text.split(/\s+/g).length; } var count = 'words: ' + countwords(wcparent); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // creat...
DOMHighResTimeStamp - Web APIs
usage notes you can get the current timestamp value—the time that has elapsed since the context was created—by
calling the performance method now().
DOMMatrix() - Web APIs
example this example creates a dommatrix to use as an argument for
calling point.matrixtransform().
DOMPointInit.x - Web APIs
dompointinit is used as an input when
calling either dompointreadonly.frompoint() or dompoint.frompoint(), and is returned by the dompointreadonly.tojson() and dompoint.tojson() methods.
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.
DOMRectReadOnly - Web APIs
note that this constructor cannot be
called by 3rd party javascript; doing so returns an "illegal constructor" typeerror.
DOMString - Web APIs
passing null to a method or parameter accepting a domstring typi
cally stringifies to "null".
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.
DedicatedWorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can
call the following: close(); close() and self.close() are effectively equivalent — both represent close() being
called from inside the worker's inner scope.
DedicatedWorkerGlobalScope.onmessageerror - Web APIs
the onmessageerror event handler of the dedicatedworkerglobalscope interface is an eventlistener,
called whenever an messageevent of type messageerror is fired on the worker—that is, when it receives a message that cannot be deserialized.
DedicatedWorkerGlobalScope.postMessage() - Web APIs
ation is done from which a result message is created; this is then sent back to the main thread using postmessage(workerresult); onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); console.log('posting message back to main script'); postmessage(workerresult); } in the main script, onmessage would have to be
called on a worker object, whereas inside the worker script you just need onmessage because the worker is effectively the global scope (dedicatedworkerglobalscope).
DeviceMotionEvent.accelerationIncludingGravity - Web APIs
this value is not typi
cally as useful as devicemotionevent.acceleration, but may be the only value available on devices that aren't able of removing gravity from the acceleration data, such as on devices that don't have a gyroscope.
DisplayMediaStreamConstraints.video - Web APIs
this value may simply be a boolean, where true specifies that a default selection of input source be made (typi
cally the entire display area of the device in use, spanning every screen in a multiple screen configuration).
Document.createElementNS() - Web APIs
rg/1999/xhtml" title="||working with elements||" onload="init()"> <script type="application/javascript"><![cdata[ let container; let newdiv; let txtnode; function init(){ container = document.getelementbyid("containerbox"); newdiv = document.createelementns("http://www.w3.org/1999/xhtml", "div"); txtnode = document.createtextnode("this is text that was constructed dynami
cally with createelementns and createtextnode then inserted into the document using appendchild."); newdiv.appendchild(txtnode); container.appendchild(newdiv); } ]]></script> <vbox id="containerbox" flex="1"> <html:div> the script on this page will add dynamic content below: </html:div> </vbox> </page> the example given above uses inline script which is not recommended in xhtml d...
Document.createNSResolver() - Web APIs
this adapter works like the dom level 3 method lookupnamespaceuri on nodes in resolving the namespaceuri from a given prefix using the current information available in the node's hierarchy at the time lookupnamespaceuri is
called.
Document.createNodeIterator() - Web APIs
its acceptnode() method will be
called for each node in the subtree based at root which is accepted as included by the whattoshow flag to determine whether or not to include it in the list of iterable nodes (a simple
callback function may also be used instead).
Document.currentScript - Web APIs
(for modules use import.meta instead.) it's important to note that this will not reference the <script> element if the code in the script is being
called as a
callback or event handler; it will only reference the element while it's initially being processed.
Document.fullscreenEnabled - Web APIs
syntax var isfullscreenavailable = document.fullscreenenabled; value a boolean value which is true if the document and the elements within can be placed into full-screen mode by
calling element.requestfullscreen().
Document.getAnimations() - Web APIs
return value an array of animation objects, each representing one animation currently associated with elements which are descendants of the document on which it's
called.
Document.getElementsByName() - Web APIs
syntax var elements = document.getelementsbyname(name); elements is a live nodelist collection, meaning it automati
cally updates as new elements with the same name are added to/removed from the document.
Document.getElementsByTagNameNS() - Web APIs
(to accommodate explorer, one could
call an xpath wrapper instead of the xpath in the function below (as explorer supports xpath with a different api), such as this wrapper class.) function getelementsbytagnamenswrapper (ns, elname, doc, context) { if (!doc) { doc = document; } if (!context) { context = doc; } var result = doc.evaluate('//*[local-name()="'+elname+'" and namespace-uri() = "'+ns+'"]', context, null, xpathresult...
Document.importNode() - Web APIs
to include it, you need to
call an insertion method such as appendchild() or insertbefore() with a node that is currently in the document tree.
Document.onoffline - Web APIs
the document.onoffline event handler is
called when an offline is fired on the <body> element and bubbles up, when navigator.online property changes and becomes false.
Document.queryCommandSupported() - Web APIs
notes the 'paste' command return false not only if the feature is unavailable, but also if the script
calling it has insufficient privileges to perform the action [1] example var flg = document.querycommandsupported("selectall"); if(flg) { // ...do something } specifications specification status comment execcommand ...
Document.selectedStyleSheetSet - Web APIs
setting the value of this property is equivalent to
calling document.enablestylesheetsforset() with the value of currentstylesheetset, then setting the value of laststylesheetset to that value as well.
DocumentTimeline.DocumentTimeline() - Web APIs
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 specifi...
Events and the DOM - Web APIs
function print(evt) { // the evt parameter is automati
cally assigned the event object // take care of the differences between console.log & alert console.log('print:', evt) alert(evt) } // any function should have an appropriate name, that's what
called semantic table_el.onclick = print ...
DragEvent.dataTransfer - Web APIs
} dragtarget.addeventlistener("dragend", function(ev) { //
call the drag and drop data processor if (ev.datatransfer !== null) processdata(ev.datatransfer); }, false); specifications specification status comment html living standardthe definition of 'dragevent.datatransfer' in that specification.
EffectTiming - Web APIs
although this is techni
cally optional, keep in mind that your animation will not run if this value is 0.
Element.attachShadow() - Web APIs
// create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always
call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent return text.trim().split(/\s+/g).length; } var count = 'words: ' + countwords(wcparent); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); /...
Element.closest() - Web APIs
but carry support for element.matches() (or a prefixed equivalent, meaning ie9+), a polyfill exists: if (!element.prototype.matches) { element.prototype.matches = element.prototype.msmatchesselector || element.prototype.webkitmatchesselector; } if (!element.prototype.closest) { element.prototype.closest = function(s) { var el = this; do { if (element.prototype.matches.
call(el, s)) return el; el = el.parentelement || el.parentnode; } while (el !== null && el.nodetype === 1); return null; }; } however, if you really do require ie 8 support, then the following polyfill will do the job very slowly, but eventually.
Element: copy event - Web APIs
a handler for this event can modify the clipboard contents by
calling setdata(format, data) on the event's clipboardevent.clipboarddata property, and cancelling the event's default action using event.preventdefault().
Element.currentStyle - Web APIs
polyfill this polyfill returns the values in pixels and is likely to be rather slow, as it has to
call window.getcomputedstyle() every time its value is read.
Element: cut event - Web APIs
a handler for this event can modify the clipboard contents by
calling setdata(format, data) on the event's clipboardevent.clipboarddata property, and cancelling the default action using event.preventdefault().
Element.getAnimations() - Web APIs
return value an array of animation objects, each representing an animation currently targetting the element on which this method is
called, or one of its descendant elements if { subtree: true } is specified.
Element.getAttributeNode() - Web APIs
example // html: <div id="top" /> let t = document.getelementbyid("top"); let idattr = t.getattributenode("id"); alert(idattr.value == "top") notes when
called on an html element in a dom flagged as an html document, getattributenode lower-cases its argument before proceeding.
Element: mouseup event - Web APIs
if isdrawing is true, the event handler
calls the drawline function to draw a line from the stored x and y values to the current location.
Element: mousewheel event - Web APIs
if the device does not support continuous scroll (typi
cally, old mouse wheel which cannot be turned smoothly), the value is computed from non-accelerated scroll amount (120 per notch).
Element.querySelectorAll() - Web APIs
the element method queryselectorall() returns a static (not live) nodelist representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was
called.
Element.scrollHeight - Web APIs
var otoberead = document.getelementbyid("rules"); checkreading.noticebox = document.createelement("span"); document.registration.accept.checked = false; checkreading.noticebox.id = "notice"; otoberead.parentnode.insertbefore(checkreading.noticebox, otoberead); otoberead.parentnode.insertbefore(document.createelement("br"), otoberead); otoberead.onscroll = checkreading; checkreading.
call(otoberead); } specifications specification status comment css object model (cssom) view modulethe definition of 'element.scrollheight' in that specification.
Element.scrollIntoView() - Web APIs
the element interface's scrollintoview() method scrolls the element's parent container such that the element on which scrollintoview() is
called is visible to the user syntax element.scrollintoview(); element.scrollintoview(aligntotop); // boolean parameter element.scrollintoview(scrollintoviewoptions); // object parameter parameters aligntotop optional is a boolean value: if true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor.
Element.scrollTop - Web APIs
the element.scrolltop property gets or sets the number of pixels that an element's content is scrolled verti
cally.
Element.setCapture() - Web APIs
call this method during the handling of a mousedown event to retarget all mouse events to this element until the mouse button is released or document.releasecapture() is
called.
Element.slot - Web APIs
examples in our simple-template example (see it live), we create a trivial custom element example
called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
Comparison of Event Targets - Web APIs
there are five targets to consider: property defined in purpose event.target dom event interface the dom element on the lefthand side of the
call that triggered this event, eg: element.dispatchevent(event) event.currenttarget dom event interface the eventtarget whose eventlisteners are currently being processed.
Event.composed - Web APIs
you can determine the path the event will follow through the shadow root to the dom root by
calling composedpath().
Event.defaultPrevented - Web APIs
the defaultprevented read-only property of the event interface returns a boolean indicating whether or not the
call to event.preventdefault() canceled the event.
Event.target - Web APIs
it is different from event.currenttarget when the event handler is
called during the bubbling or capturing phase of the event.
EventListener.handleEvent() - Web APIs
the eventlistener method handleevent() method is
called by the user agent when an event is sent to the eventlistener, in order to handle events that occur on an observed eventtarget.
EventSource.onerror - Web APIs
the onerror property of the eventsource interface is an eventhandler
called when an error occurs and the error event is dispatched on an eventsource object.
EventSource.onmessage - Web APIs
the onmessage property of the eventsource interface is an eventhandler
called when a message event is received, that is when a message is coming from the source.
EventSource.onopen - Web APIs
the onopen property of the eventsource interface is an eventhandler
called when an open event is received, that is when the connection was just opened.
ExtendableEvent.waitUntil() - Web APIs
the waituntil() method must be initially
called within the event
callback, but after that it can be
called multiple times, until all the promises passed to it settle.
ExtendableMessageEvent - Web APIs
examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then
calls its postmessage() function.
FetchEvent() - Web APIs
typi
cally, pressing the refresh button in a browser is a reload, while clicking a link and pressing the back button is not.
File.lastModified - Web APIs
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: dynami
cally created files if a file is created dynami
cally, the last modified time can be supplied in the new file() constructor function.
FileList - Web APIs
cript> var pullfiles=function(){ // love the query selector var fileinput = document.queryselector("#myfiles"); var files = fileinput.files; // cache files.length var fl = files.length; var i = 0; while ( i < fl) { // localize file var in the loop var file = files[i]; alert(file.name); i++; } } // set the input element onchange to
call pullfiles document.queryselector("#myfiles").onchange=pullfiles; //a.t </script> </html> specifications specification status comment file apithe definition of 'filelist' in that specification.
FileReader.abort() - Web APIs
syntax instanceoffilereader.abort(); exceptions dom_file_abort_err thrown when abort is
called while no read operation is in progress (that is, the state isn't loading).
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
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.readAsDataURL() - Web APIs
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.
FileRequest - Web APIs
filerequest.onprogress a
callback handler
called repeatedly while the operation represented by the filerequest is in progress.
FileSystemEntry.fullPath - Web APIs
example this example shows a function which is
called with a file system; it then gets a filesystemfileentry for a file named data.json and returns its full path.
FileSystemEntry.name - Web APIs
example this example shows a function
called isfilewithextension() which returns true if the specified filesystementry is both a file and the file's name ends with a given extension.
FileSystemEntrySync - Web APIs
for example, if you wanted to display an image and have its fileentry,
calling tourl() gives you the image file's file system url.
FormData.append() - Web APIs
if the sent value is different than string or blob it will be automati
cally converted to string: formdata.append('name', true); formdata.append('name', 74); formdata.append('name', 'john'); formdata.getall('name'); // ["true", "74", "john"] specifications specification status comment xmlhttprequestthe definition of 'append()' in that specification.
FormData.set() - Web APIs
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 automati
cally converted to string: formdata.set('name', 72); formdata.get('name'); // "72" specifications specification status comment xmlhttprequestthe definition of 'set()' in that specification.
FullscreenOptions - Web APIs
the fullscreenoptions dictionary is used to provide configuration options when
calling requestfullscreen() on an element to place that element into full-screen mode.
GainNode.gain - Web APIs
iv> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success
callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error
callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
GainNode - Web APIs
iv> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success
callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error
callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } source.connect(gainnode); gainnode.connect(audioctx.destination); ...
Gamepad.buttons - Web APIs
each entry in the array is 0 if the button is not pressed, and non-zero (typi
cally 1.0) if the button is pressed.
Gamepad.timestamp - Web APIs
values are monotoni
cally 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.gamepad - Web APIs
syntax readonly attribute gamepad gamepad; example the gamepad property being
called on a fired window.gamepadconnected event.
GlobalEventHandlers.onabort - Web APIs
while the standard for aborting a document load is defined, html issue #3525 suggests that browsers should not currently fire the abort event on a window that would trigger onabort to be
called.
GlobalEventHandlers.onanimationend - Web APIs
syntax var animendhandler = target.onanimationend; target.onanimationend = function value a function to be
called when an animationend event occurs indicating that a css animation has begun on the target, where the target object is an html element (htmlelement), document (document), or window (window).
GlobalEventHandlers.onanimationstart - Web APIs
syntax var animstarthandler = target.onanimationstart; target.onanimationstart = function value a function to be
called when an animationstart event occurs indicating that a css animation has begun on the target, where the target object is an html element (htmlelement), document (document), or window (window).
GlobalEventHandlers.onemptied - Web APIs
the emptied event is fired when the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is
called to reload it.
GlobalEventHandlers.oninvalid - Web APIs
the validity of submittable elements is checked before submitting their owner form, or after the checkvalidity() method of the element or its owner form is
called.
GlobalEventHandlers.onloadend - Web APIs
the onloadend property of the globaleventhandlers mixin is an eventhandler representing the code to be
called when the loadend event is raised (when progress has stopped on the loading of a resource.) syntax img.onloadend = funcref; value funcref is the handler function to be
called when the resource's loadend event fires.
GlobalEventHandlers.onloadstart - Web APIs
the onloadstart property of the globaleventhandlers mixin is an eventhandler representing the code to be
called when the loadstart event is raised (when progress has begun on the loading of a resource.) syntax img.onloadstart = funcref; value funcref is the handler function to be
called when the resource's loadstart event fires.
GlobalEventHandlers.ontransitioncancel - Web APIs
syntax var transitioncancelhandler = target.ontransitioncancel; target.ontransitioncancel = function value a function to be
called when a transitioncancel event occurs indicating that a css transition has been cancelled on the target, where the target object is an html element (htmlelement), document (document), or window (window).
GlobalEventHandlers.ontransitionend - Web APIs
syntax var transitionendhandler = target.ontransitionend; target.ontransitionend = function value a function to be
called when a transitionend event occurs indicating that a css transition has completed on the target, where the target object is an html element (htmlelement), document (document), or window (window).
Gyroscope.Gyroscope() - Web APIs
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
example the gyroscope is typi
cally read in the sensor.onreading event
callback.
HTMLAnchorElement - Web APIs
techni
cally, the url-related properties, media, host, hostname, pathname, port, protocol, search, and hash, have been moved to the htmlhyperlinkelementutils mixin, and htmlanchorelement implements this mixin.
Audio() - Web APIs
instead, the audio will keep playing and the object will remain in memory until playback ends or is paused (such as by
calling pause()).
HTMLAudioElement - Web APIs
mozcurrentsampleoffset() returns the number of samples form the beginning of the stream that have been written so far into the audio stream created by
calling mozwriteaudio().
HTMLBaseFontElement - Web APIs
if no font listed is installed on the local system, the browser typi
cally defaults to the proportional or fixed-width font for that system.
HTMLButtonElement - Web APIs
this is the default value if the attribute is not specified, html5 or if it is dynami
cally changed to an empty or invalid value.
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 automati
cally; instead, they will only be captured when the returned track's requestframe() method is
called.
HTMLCanvasElement.toDataURL() - Web APIs
base64,ivborw0kggoaaaansuheugaaaauaaaafcayaaacnby // blaaaadeleqvqimwngobmaaabpaafei8araaaaaelftksuqmcc" setting image quality with jpegs var fullquality = canvas.todataurl('image/jpeg', 1.0); // data:image/jpeg;base64,/9j/4aaqskzjrgabaq...9oadambaairaxeapwd/ad/6ap/z" var mediumquality = canvas.todataurl('image/jpeg', 0.5); var lowquality = canvas.todataurl('image/jpeg', 0.1); example: dynami
cally change images you can use this technique in coordination with mouse events in order to dynami
cally change images (gray-scale vs.
HTMLElement.offsetWidth - Web APIs
typi
cally, offsetwidth is a measurement in pixels of the element's css width, including any borders, padding, and vertical scrollbars (if rendered).
HTMLFontElement.face - Web APIs
if no font listed is installed on the local system, the browser typi
cally defaults to the proportional or fixed-width font for that system.
HTMLImageElement.border - Web APIs
the width, specifi
cally, is controlled using the writing-mode aware border-block-start-width, border-block-end-width, border-inline-start-width, and border-inline-end-width properties.
HTMLImageElement.complete - Web APIs
so the fixredeyecommand() function, which is
called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work.
HTMLImageElement.lowSrc - Web APIs
it was never techni
cally part of the html specification (it was a mozilla extension to html); however, html 5 does list it among the obsolete attributes.
HTMLImageElement.src - Web APIs
this can be set either within the html itself using the src content attribute, or programmati
cally by setting the element's src property.
HTMLImageElement.x - Web APIs
from there, we can get the <img> element itself from the cell by
calling queryselector() on the htmltablecellelement representing that cell.
HTMLImageElement.y - Web APIs
from there, we can get the <img> element itself from the cell by
calling queryselector() on the htmltablecellelement representing that cell.
HTMLInputElement: invalid event - Web APIs
the validity of submittable elements is checked before submitting their owner <form>, or after the checkvalidity() method of the element or its owner <form> is
called.
HTMLInputElement.stepDown() - Web APIs
a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="decrementer" min="-2" max="15"> </label> </p> <input type="button" value="decrement" id="thebutton"> javascript /* make the button
call the function */ let button = document.getelementbyid('thebutton'); button.addeventlistener('click', function() { stepondown();} ); function stepondown() { let input = document.getelementbyid('thenumber'); let val = document.getelementbyid('decrementer').value; if (val) { /* increment with a parameter */ input.stepdown(val); } else { /* or without a parameter.
HTMLInputElement.stepUp() - Web APIs
a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="incrementer" min="0" max="25"> </label> </p> <input type="button" value="increment" id="thebutton"> javascript /* make the button
call the function */ let button = document.getelementbyid('thebutton') button.addeventlistener('click', function() { steponup() }) function steponup() { let input = document.getelementbyid('thenumber') let val = document.getelementbyid('incrementer').value if (val) { /* increment with a parameter */ input.stepup(val) } else { /* or without a parameter.
HTMLMediaElement.currentTime - Web APIs
if the media is not yet playing, the value of currenttime indicates the time position within the media at which playback will begin once the play() method is
called.
HTMLMediaElement.textTracks - Web APIs
instead, they're sent to the track list object of the htmlmediaelement that corresponds to the type of track that was added to the element the returned list is live; that is, as tracks are added to and removed from the media element, the list's contents change dynami
cally.
HTMLObjectElement - Web APIs
recommendation the w3c specification is a latest of a previous version of html living standard techni
cally, the property tabindex is now defined on htmlelement.
HTMLElement.focus() - Web APIs
obsolete notes if you
call htmlelement.focus() from a mousedown event handler, you must
call event.preventdefault() to keep the focus from leaving the htmlelement behaviour of the focus in relation to different html features like tabindex or shadow dom, which previously remained under-specified, were recently updated (as october of 2019).
HTMLSelectElement.form - Web APIs
syntax edit aform = aselectelement.form.selectname; example html <form action="http://www.google.com/search" method="get"> <label>google: <input type="search" name="q"></label> <input type="submit" value="search..."> </form> javascript a property available on all form elements, "type" returns the type of the
calling form element.
HTMLSourceElement - Web APIs
note: if the src property is updated (along with any siblings), the parent htmlmediaelement's load method should be
called when done, since <source> elements are not re-scanned automati
cally.
HTMLTableCellElement - Web APIs
htmltablecellelement.valign a domstring representing an enumerated value indicating how the content of the cell must be verti
cally aligned.
HTMLTableElement.insertRow() - Web APIs
addrow(tableid) { // get a reference to the table let tableref = document.getelementbyid(tableid); // insert a row at the end of the table let newrow = tableref.insertrow(-1); // insert a cell in the row at index 0 let newcell = newrow.insertcell(0); // append a text node to the cell let newtext = document.createtextnode('new bottom row'); newcell.appendchild(newtext); } //
call addrow() with the table's id addrow('my-table'); result specifications specification status comment html living standardthe definition of 'htmltableelement.insertrow()' in that specification.
HTMLTableRowElement.insertCell() - Web APIs
addrow(tableid) { // get a reference to the table let tableref = document.getelementbyid(tableid); // insert a row at the end of the table let newrow = tableref.insertrow(-1); // insert a cell in the row at index 0 let newcell = newrow.insertcell(0); // append a text node to the cell let newtext = document.createtextnode('new bottom row'); newcell.appendchild(newtext); } //
call addrow() with the table's id addrow('my-table'); result specifications specification status comment html living standardthe definition of 'htmltablerowelement.insertcell()' in that specification.
Headers - Web APIs
note: when header values are iterated over, they are automati
cally sorted in lexicographical order, and values from duplicate header names are combined.
History API - Web APIs
(the current page's relative position is 0.) to move back one page (the equivalent of
calling back()): window.history.go(-1) to move forward a page, just like
calling forward(): window.history.go(1) similarly, you can move forward 2 pages by passing 2, and so forth.
HmacImportParams - Web APIs
warning: although you can techni
cally pass sha-1 here, this is strongly discouraged as it is considered vulnerable.
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.
databases - Web APIs
exceptions this method may raise a domexception of the following types: attribute description securityerror the method is
called from an opaque origin.
IDBFactory.open() - Web APIs
example example of
calling open with the current specification's version parameter: var request = window.indexeddb.open("todolist", 4); in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
IDBIndex.count() - Web APIs
myindex.count() is then used to count the number of records in the index, and the result of that request is logged to the console when its success
callback returns.
IDBIndex.get() - Web APIs
myindex.get('bungle') is then used to retrieve the record with an lname of bungle, and the result of that request is logged to the console when its success
callback returns.
IDBIndex.getKey() - Web APIs
myindex.getkey('bungle') is then used to retrieve the primary key of the record with an lname of bungle, and the result of that request is logged to the console when its success
callback returns.
FileHandle.onabort - Web APIs
syntax instanceoffilehandle.onabort = funcref; where funcref is a function to be
called when the abort event occurs.
FileHandle.onerror - Web APIs
syntax instanceoffilehandle.onerror = funcref; where funcref is a function to be
called when the error event occurs.
IDBMutableFile - Web APIs
note: this interface used to be
called filehandle , but it was changed to this (bug 1006485.) as idbmutablefile objects are bound to a fake file system built on top of indexeddb, such an object is created using the idbdatabase.createmutablefile method.
IDBObjectStore.getAll() - Web APIs
this method produces the same result for: a record that doesn't exist in the database a record that has an undefined value to tell these situations apart, you either
call the opencursor() method with the same key.
IDBObjectStore.getAllKeys() - Web APIs
this method produces the same result for: a record that doesn't exist in the database a record that has an undefined value to tell these situations apart, you need to
call the opencursor() method with the same key.
IDBObjectStore.put() - Web APIs
in such cases,
calling put(item) will always insert a new record, because it doesn't know what existing record you might want to modify.
IDBTransaction: abort event - Web APIs
bubbles yes cancelable no interface event event handler property onabort this can happen for any of the following reasons: bad requests, (for example, trying to add the same key twice, or put the same index key when the key has a uniqueness constraint), an explicit abort()
call an uncaught exception in the request's success/error handler, an i/o error (an actual failure to write to disk, for example disk detached, or other os/hardware failure) quota exceeded.
IIRFilterNode.getFrequencyResponse() - Web APIs
the two output arrays, magresponseoutput and phaseresponseoutput, must be created before
calling this method; they must be the same size as the array of input frequency values (frequencyarray).
ImageCapture() constructor - Web APIs
example the following example shows how to use a
call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor.
InstallEvent - Web APIs
examples this code snippet is from the service worker prefetch sample (see prefetch running live.) the code
calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall and delays treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully.
IntersectionObserverEntry - Web APIs
instances of intersectionobserverentry are delivered to an intersectionobserver
callback in its entries parameter; otherwise, these objects can only be obtained by
calling intersectionobserver.takerecords().
InterventionReportBody - Web APIs
this typi
cally matches the message a browser will display in its devtools console when an intervention is imposed, if one is available.
KeyboardEvent.getModifierState() - Web APIs
pported "hyper" not supported "meta" not supported meta key pressed ⌘ command key pressed not supported ⊞ windows logo key or command key pressed "numlock" during led for num lock turned on a key on numpad pressed not supported while numlock is locked "os" ⊞ windows logo key pressed super key or hyper key pressed (typi
cally, mapped to ⊞ windows logo key) not supported "scrolllock" during led for scroll lock turned on during led for scroll lock turned on, but typi
cally this isn't supported by platform not supported while scrolllock is locked "shift" ⇧ shift key pressed "super" not supported "symbol" not supported "symbollock" not supported ...
KeyboardEvent.key - Web APIs
for a given key press, the sequence of keyboardevents fired is as follows assuming that event.preventdefault is not
called: a keydown event is first fired.
KeyboardEvent.repeat - Web APIs
the repeat read-only property of the keyboardevent interface returns a boolean that is true if the given key is being held down such that it is automati
cally repeating.
KeyframeEffect - Web APIs
the keyframeeffect interface of the web animations api lets us create sets of animatable properties and values,
called keyframes.
LargestContentfulPaint - Web APIs
this example also demonstrates how to include buffered entries (those that ocurred before observer() was
called), which is done by setting the buffered option to true.
LinearAccelerationSensor.LinearAccelerationSensor() - Web APIs
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.
Location: reload() - Web APIs
this happens if the origin of the script
calling location.reload() differs from the origin of the page that owns the location object.
Location: replace() - Web APIs
this happens if the origin of the script
calling the method is different from the origin of the page originally described by the location object, mostly when the script is hosted on a different domain.
Location: search - Web APIs
the search property of the location interface is a search string, also
called a query string; that is, a usvstring containing a '?' followed by the parameters of the url.
Location - Web APIs
ion:absolute; top:100%; width:100%; left:50%; margin-left:-50%; font-size:40%; line-height:1.5; background:black;} [title]:hover:before, :target:before {background:black; color:yellow;} [title] [title]:before {margin-top:1.5em;} [title] [title] [title]:before {margin-top:3em;} [title]:hover, :target {position:relative; z-index:1; outline:50em solid rgba(255,255,255,.8);} javascript [].foreach.
call(document.queryselectorall('[title][id]'), function (node) { node.addeventlistener("click", function(e) { e.preventdefault(); e.stoppropagation(); window.location.hash = '#' + $(this).attr('id'); }); }); [].foreach.
call(document.queryselectorall('[title]'), function (node) { node.addeventlistener("click", function(e) { e.preventdefault(); e.stoppropagation(); window.l...
Locks.mode - Web APIs
example the following examples show how the mode property is passed in the
call to lockmanager.request().
Locks.name - Web APIs
example the following examples show how the name property passed in the
call to lockmanager.request().
LockedFile.active - Web APIs
typi
cally, a lockedfile object becomes inactive when the lockedfile.abort() method is
called or if an error occurs.
LockedFile.onabort - Web APIs
syntax instanceoflockedfile.onabort = funcref; where funcref is a function to be
called when the abort event occurs.
LockedFile.onerror - Web APIs
syntax instanceoflockedfile.onerror = funcref; where funcref is a function to be
called when the error event occurs.
LockedFile - Web APIs
lockedfile.onabort the abort event is triggered each time the abort() method is
called.
MIDIAccess - Web APIs
event handlers midiaccess.onstatechange
called whenever a new midi port is added or an existing port changes state.
MIDIInput - Web APIs
event handlers midiinput.onmidimessage when the current port receives a midimessage it triggers a
call to this event handler.
MSCandidateWindowShow - Web APIs
example in ie11, developers can detect the opening of the ime candidate window by listening to mscandidatewindowshow event, then
call getcandidatewindowclientrect() function to find out where the candidate window is and position the suggestion ui away from it: var context = document.getelementbyid("mysearchbox").msgetinputcontext(); context.addeventlistener("mscandidatewindowshow", candidatewindowshowhandler); function candidatewindowshowhandler(e) { var imerect = context.getcandidatewindowclientrect(); var suggestionre...
MSManipulationEvent - Web APIs
methods msmanipulationevent.initmsmanipulationevent(): used to create a manipulation event that can be
called from javascript.
Magnetometer.Magnetometer() - Web APIs
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.
MediaDecodingConfiguration - Web APIs
the mediadecodingconfiguration dictionary of the media capabilities api is used to define the type of media being tested when
calling mediacapabilities.decodinginfo() to query whether a specific media configuration is supported, smooth, and/or power efficient.
MediaElementAudioSourceNode - Web APIs
document.documentelement.scrolltop : document.body.scrolltop); gainnode.gain.value = cury/height; } // 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(gainnode); gainnode.connect(audioctx.destination); note: as a consequence of
calling createmediaelementsource(), audio playback from the htmlmediaelement will be re-routed into the processing graph of the audiocontext.
MediaEncodingConfiguration - Web APIs
the mediaencodingconfiguration dictionary of the media capabilities api is used to define the type of media being tested when
calling mediacapabilities.encodinginfo() to query whether a specific media configuration is supported, smooth, and/or power efficient.
MediaError - Web APIs
mediaerror.message a domstring object containing a human-readable string which provides specific diagnostic information to help the reader understand the error condition which occurred; specifi
cally, it isn't simply a summary of what the error code means, but actual diagnostic information to help in understanding what exactly went wrong.
MediaQueryList.matches - Web APIs
examples this example detects viewport orientation changes by creating a media query using the orientation media feature: function addmqlistener(mq,
callback) { if (mq.addeventlistener) { mq.addeventlistener("change",
callback); } else { mq.addlistener(
callback); } } addmqlistener(window.matchmedia("(orientation:landscape)"), event => { if (event.matches) { /* now in landscape orientation */ } else { /* now in portrait orientation */ } } ); specifications specification status comment ...
MediaQueryListEvent - Web APIs
the mediaquerylistevent object stores information on the changes that have happened to a mediaquerylist object — instances are available as the event object on a function referenced by a mediaquerylist.onchange property or mediaquerylist.addlistener()
call.
MediaRecorder() - Web APIs
applications can check in advance if a mimetype is supported by the user agent by
calling mediarecorder.istypesupported().
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.resume() - Web APIs
syntax mediarecorder.resume() errors an invalidstate error is raised if the resume() method is
called while the mediarecorder object’s mediarecorder.state is "inactive" — the recording cannot be resumed if it is not already paused; if mediarecorder.state is already "recording", resume() has no effect.
MediaRecorder.stop() - Web APIs
syntax mediarecorder.stop() errors an invalidstate error is raised if the stop() method is
called while the mediarecorder object’s mediarecorder.state is "inactive" — it makes no sense to stop media capture if it is already stopped.
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
the error's name property's value may be any exception that makes sense during the handling of media recording, including these specifi
cally identified by the specification.
MediaSession - Web APIs
a browser on that device might deliver the metadata provided by
calling mediasession to the device in order to be controllable using the global user interface.
Media Session action types - Web APIs
to support an action on a media session, such as seeking, pausing, or changing tracks, you need to
call the mediasession interface's setactionhandler() method to establish a handler for that action.
MediaSessionActionDetails - Web APIs
the media session api's mediasessionactiondetails dictionary is the type used by the sole input parameter into the
callback which is executed when a media session action occurs.
MediaSource.endOfStream() - Web APIs
when you make an xmlhttprequest
call for a media chunk, and onabort or onerror triggers, you might want to
call endofstream('network'), display a descriptive message in the ui, and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.) decode: terminates playback and signals that a decoding error has occured.
MediaSource - Web APIs
mediasource.clearliveseekablerange() clears a seekable range previously set with a
call to setliveseekablerange().
MediaStream() - Web APIs
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 automati
cally.
MediaStreamAudioSourceNode() - Web APIs
note: another way to create a mediastreamaudiosourcenode is to
call theaudiocontext.createmediastreamsource() method, specifying the stream from which you want to obtain audio.
MediaStreamConstraints - Web APIs
the mediastreamconstraints dictionary is used when
calling getusermedia() to specify what kinds of tracks should be included in the returned mediastream, and, optionally, to establish constraints for those tracks' settings.
MediaStreamTrack.clone() - Web APIs
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.
MediaStreamTrack.onended - Web APIs
the mediastreamtrack.onended event handler is used to specify a function which serves as an eventhandler to be
called when the ended event occurs on the track.
MerchantValidationEvent() - Web APIs
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().
MessagePort.onmessage - Web APIs
the onmessage event handler of the messageport interface is an eventlistener,
called whenever an messageevent of type message is fired on the port — that is, when the port receives a message.
MessagePort.onmessageerror - Web APIs
the onmessageerror event handler of the messageport interface is an eventlistener,
called whenever an messageevent of type messageerror is fired on the port—that is, when it receives a message that cannot be deserialized.
MessagePort.start() - Web APIs
example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using onmessage: channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } another option would be to do this using eventtarget.addeventlistener, however, when this method is used, you need to explicitly
call start() to begin the flow of messages to this document: channel.port1.addeventlistener('message', handlemessage, false); function handlemessage(e) { para.innerhtml = e.data; textinput.value = ''; } channel.port1.start(); specifications specification status comment html living standardthe definition of 'start()' in that specification.
Microsoft API extensions - Web APIs
completed onmsvideooptimallayoutchanged msfirstpaint pinned sites apis mssitemodeevent mssitemodejumplistitemremoved msthumbnailclick other apis x-ms-aria-flowfrom x-ms-acceleratorkey x-ms-format-detection mscaching mscachingenabled mscapslockwarningoff event.msconverturl() mselementresize document.mselementsfromrect() msisstatichtml navigator.mslaunchuri() mslaunchuri
callback element.msmatchesselector() msprotocols msputpropertyenabled mswriteprofilermark ...
MouseEvent.buttons - Web APIs
0 : no button or un-initialized 1 : primary button (usually the left button) 2 : secondary button (usually the right button) 4 : auxiliary button (usually the mouse wheel button or middle button) 8 : 4th button (typi
cally the "browser back" button) 16 : 5th button (typi
cally the "browser forward" button) example this example logs the buttons property when you trigger a mousedown event.
MouseEvent.clientY - Web APIs
for example, clicking on the top edge of the client area will always result in a mouse event with a clienty value of 0, regardless of whether the page is scrolled verti
cally.
NDEFReader.onerror - Web APIs
the onerror property of ndefreader interface of the web nfc api is
called whenever an error occurs during reading of nfc tags, e.g.
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.
NDEFWriter - Web APIs
methods ndefwriter.write()
called to write ndef message to a tag (after ensuring hardware and ua compatibility and obtaining permission from the user) or get an error explaining why feature is not available.
NamedNodeMap - Web APIs
although
called namednodemap, this interface doesn't deal with node objects but with attr objects, which were originally a specialized class of node, and still are in some implementations.
Navigation Timing API - Web APIs
unlike javascript-based libraries that have histori
cally been used to collect similar information, the navigation timing api can be much more accurate and reliable.
Navigator.clipboard - Web APIs
perhaps this code is being used in a browser extension that displays the current clipboard contents, automati
cally updating periodi
cally or when specific events fire.
msSaveBlob - Web APIs
notes when a site
calls this method, the behavior is the same as when windows internet explorer downloads a file with the following in the header, where x-download-options removes the file open button from the browser file download dialog: content-length: <blob.size> content-type: <blob.type> content-disposition: attachment;filename=<defaultname> x-download-options: noopen specifications not part of any specificati...
msSaveOrOpenBlob - Web APIs
notes when a site
calls this method, the behavior is the same as when windows internet explorer downloads a file with the following in the header: content-length: <blob.size> content-type: <blob.type> content-disposition: attachment;filename=<defaultname> specifications not part of any specifications.
Navigator.vibrate() - Web APIs
if a vibration pattern is already in progress when this method is
called, the previous pattern is halted and the new one begins instead.
Node.baseURI - Web APIs
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 dynami
cally) see the base urls section of the html living standard for details.
Node.baseURIObject - Web APIs
the node.baseuriobject property returns the nsiuri representing the node's (typi
cally a document or an element) base url.
Node.localName - Web APIs
qualified names are typi
cally used in xml as part of the namespace(s) of the particular xml documents.
Node.lookupPrefix() - Web APIs
due to bug 312019, this method does not work with dynami
cally assigned namespaces, that is, those set with the node.prefix property.
Node.replaceChild() - Web APIs
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.
NodeIterator.filter - Web APIs
when creating the nodeiterator, the filter object is passed in as the third parameter, and the object method acceptnode(node) is
called on every single node to determine whether or not to accept it.
NodeIterator.previousNode() - Web APIs
in old browsers, as specified in old versions of the specifications, the method may throws the invalid_state_err domexception if this method is
called after the nodeiterator.detach()method.
Notification.requireInteraction - Web APIs
the requireinteraction read-only property of the notification interface returns a boolean indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automati
cally.
Notification.tag - Web APIs
one notification can then be programmati
cally replaced with another to avoid the users' screen being filled up with a huge number of similar notifications.
OVR_multiview2 - Web APIs
calling checkframebufferstatus for a framebuffer in this state returns framebuffer_incomplete_view_targets_ovr.
OfflineAudioContext.oncomplete - Web APIs
the oncomplete event handler of the offlineaudiocontext interface is
called when the audio processing is terminated, that is when the complete event (of type offlineaudiocompletionevent) is raised.
OfflineAudioContext.startRendering() - Web APIs
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 startrendering is
called a second time on an offlineaudiocontext }); }); } request.send(); } // run getdata to start the process off getdata(); specifications specification status comment web audio apithe definition of 'startrendering()' in that specification.
PannerNode.distanceModel - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
PannerNode.maxDistance - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
PannerNode.panningModel - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
PannerNode.setOrientation() - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
PannerNode.setPosition() - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
PannerNode.setVelocity() - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
PannerNode - Web APIs
you might be moving a character around inside a game world for example, and wanting delivery of audio to change realisti
cally as your character moves closer to or further away from a music player such as a stereo.
ParentNode.append() - Web APIs
e: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('append')) { return; } object.defineproperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argarr = array.prototype.slice.
call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
ParentNode.children - Web APIs
the parentnode property children is a read-only property that returns a live htmlcollection which contains all of the child elements of the node upon which it was
called.
ParentNode.prepend() - Web APIs
/ source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/prepend()/prepend().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('prepend')) { return; } object.defineproperty(item, 'prepend', { configurable: true, enumerable: true, writable: true, value: function prepend() { var argarr = array.prototype.slice.
call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
ParentNode.querySelector() - Web APIs
the parentnode mixin defines the queryselector() method as returning an element representing the first element matching the specified group of selectors which are descendants of the object on which the method was
called.
ParentNode.querySelectorAll() - Web APIs
the parentnode mixin defines the queryselectorall() method as returning a nodelist representing a list of elements matching the specified group of selectors which are descendants of the object on which the method was
called.
PaymentAddress.country - Web APIs
var paymentcountry = paymentaddress.country; value a domstring which contains the iso3166-1 alpha-2 code identifying the country in which the address is located, or an empty string if no country is available, which frequently can be assumed to mean "same country as the site owner." usage notes if the payment handler validates the address and determines that the value of country is invalid, a
call to paymentrequestupdateevent.updatewith() will be made with a details object containing a shippingaddresserrors field.
PaymentMethodChangeEvent.methodDetails - Web APIs
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.
PaymentRequest.onmerchantvalidation - Web APIs
syntax paymentrequest.onmerchantvalidation = eventhandlerfunction; value an event handler function which is to be
called whenever the merchantvalidation event is fired at the paymentrequest, indicating that the payment handler requires the merchant to validate themselves as allowed to use this payment handler.
PaymentRequest.onshippingaddresschange - Web APIs
to make sure an updated address is included when sending payment information to the server, you should add event listeners for a paymentrequest object after instantiation, but before the
call to show().
PaymentRequest.onshippingoptionchange - Web APIs
to make sure an updated option is included when sending payment information to the server, you should add event listeners for a paymentrequest object after instantiation, but before the
call to show().
PaymentRequestEvent - Web APIs
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
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.
Payment Request API - Web APIs
the browser can automati
cally suggest which card to use based on past usage patterns or restrictions from the merchant (e.g, "we only accept visa or mastercard"), or allow the user to say which is their default/favorite card.
performance.clearMarks() - Web APIs
if the method is
called with no arguments, all performance entries with an entry type of "mark" will be removed from the performance entry buffer.
performance.getEntries() - Web APIs
the list's members (entries) can be created by making performance marks or measures (for example by
calling the mark() method) at explicit points in time.
performance.measure() - Web APIs
duration - set to a domhighrestimestamp that is the duration of the measure (typi
cally, the end mark timestamp minus the start mark timestamp).
Performance - Web APIs
an object of this type can be obtained by
calling the window.performance read-only attribute.
PerformanceEntry - Web APIs
a performance entry can be directly created by making a performance mark or measure (for example by
calling the mark() method) at an explicit point in an application.
PerformanceObserver - Web APIs
the performance observer's
callback function will be invoked when a performance entry is recorded for one of the specified entrytypes performanceobserver.disconnect() stops the performance observer
callback from receiving performance entries.
PerformancePaintTiming - Web APIs
the performancepainttiming interface of the paint timing provides timing information about "paint" (also
called "render") operations during web page construction.
PeriodicWave - Web APIs
periodicwave has no inputs or outputs; it is used to define custom oscillators when
calling oscillatornode.setperiodicwave().
PointerEvent.pressure - Web APIs
example in this snippet, when a pointerdown event is fired, different functions are
called depending on the value of the event's pressure property.
PointerEvent.twist - Web APIs
example when a pointerdown event is fired, different functions are
called depending on the value of the event's twist property.
Proximity Events - Web APIs
these events make it possible to react to such a change, for example by shutting down the screen of a smartphone when the user is having a phone
call with the device close to their ear.
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
the value of the strings may be: "usb": the authenticator can be contacted via a removable usb link "nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifi
cally bound to the client device (cannot be removed).
PublicKeyCredentialCreationOptions - Web APIs
publickeycredentialcreationoptions.timeout optional a numerical hint, in milliseconds, which indicates the time the
caller is willing to wait for the creation operation to complete.
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
the value of the strings may be: "usb": the authenticator can be contacted via a removable usb link "nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifi
cally bound to the client device (cannot be removed).
PublicKeyCredentialRequestOptions - Web APIs
publickeycredentialrequestoptions.timeout optional a numerical hint, in milliseconds, which indicates the time the
caller is willing to wait for the retrieval operation to complete.
PushManager.subscribe() - Web APIs
console.log(error); } ); }); responding to user gestures subscribe()
calls should be done in response to a user gesture, such as clicking a button, for example: btn.addeventlistener('click', function() { serviceworkerregistration.pushmanager.subscribe(options) .then(function(pushsubscription) { // handle subscription }); }) this is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward brows...
PushManager - Web APIs
in the updated api, a subscription is unregistered by
calling the pushsubscription.unsubscribe() method.
RTCConfiguration.iceServers - Web APIs
if the list of servers is changed while a connection is already active by
calling the the rtcpeerconnection method setconfiguration(), no immediate effect occurs.
RTCDTMFSender.insertDTMF() - Web APIs
calling insertdtmf() will append the specified tones to the end of the current tone buffer, so that those tones play after the previously-enqueued tones.
RTCDTMFSender.ontonechange - Web APIs
syntax rtcdtmfsender.ontonechange = tonechangehandlerfunction; value a function which is
called when a tonechange event is sent to the rtcdtmfsender, indicating that a dtmf tone has either started playing, or if all tones have finished playing.
RTCDTMFSender: tonechange event - Web APIs
the tonechange event is sent to an rtcdtmfsender by the webrtc api to indicate when dtmf tones previously queued for sending (by
calling rtcdtmfsender.insertdtmf()) begin and end.
RTCDataChannel: bufferedamountlow event - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("sendfile"); let source = /* source data object */ dc.bufferedamountlowthreshold = 65536; pc.addeventlistener("bufferedamountlow", ev => { if (source.position <= source.length) { dc.send(source.readfile(65536)); } }, false); after creating the rtcpeerconnection, this
calls rtcpeerconnection.createdatachannel() to create the data channel.
RTCDataChannel: error event - Web APIs
receivedalert); } if (err.sentalert) { console.error(" sent dlts failure alert: ", err.receivedalert); } break; } // add source file name and line information console.error(" error in file ", err.filename, " at line ", err.linenumber, ", column ", err.columnnumber); }, false); the received event provides details in an rtcerror object
called error; rtcerror is an extension of the domexception interface.
RTCDataChannel.negotiated - Web APIs
example the code snippet below checks the value of negotiated; if it's true, a function
called shutdownremotechannel() is
called with the channel's id; presumably this would be implemented to transmit a shutdown signal to the remote peer prior to terminating the connection.
RTCDataChannelEvent.channel - Web APIs
example the first line of code in the datachannel event handler shown below takes the channel from the event object and saves it lo
cally for use by the code handling data traffic.
RTCDtlsTransport.state - Web APIs
closed the transport has been closed intentionally as the result of receipt of a close_notify alert, or
calling rtcpeerconnection.close().
RTCDtlsTransport - Web APIs
description allocation of dtls transports rtcdtlstransport objects are created when an app
calls either setlocaldescription() or setremotedescription().
RTCIceCandidate.address - Web APIs
you can't specify the address in the options object, but the address is automati
cally extracted from the candidate a-line, if it's formatted properly.
RTCIceCandidate.relatedAddress - Web APIs
you can't specify the value of relatedaddress in the options object, but the address is automati
cally extracted from the candidate a-line, if it's formatted properly, being taken from its rel-address field.
RTCIceCandidate.relatedPort - Web APIs
you can't specify the value of relatedport in the options object, but the address is automati
cally extracted from the candidate a-line, if it's formatted properly, being taken from its rel-port field.
RTCIceCandidate.sdpMid - Web APIs
if you
call the constructor with an m-line string instead of an rtcicecandidateinit object, the value of sdpmid is extracted from the specified candidate m-line string.
RTCIceCandidate.type - Web APIs
you can't specify the value of type in the options object, but the address is automati
cally extracted from the candidate a-line, if it's formatted properly, being taken from its cand-type field.
RTCIceCandidateStats.networkType - Web APIs
note: the networktype property is only included in rtcicecandidatestats objects for local candidates (that is, candidates generated lo
cally and included in an sdp offer or answer that has been sent to the remote peer).
RTCIceParameters - Web APIs
during ice negotiation, each peer's username fragment and password are recorded in an rtciceparameters object, which can be obtained from the rtcicetransport by
calling its getlocalparameters() or getremoteparameters() method, depending on which end interests you.
RTCIceTransport: gatheringstatechange event - Web APIs
here, the addeventlistener() method is
called to add a listener for gatheringstatechange events: pc.getsenders().foreach(sender => { sender.transport.icetransport.addeventlistener("gatheringstatechange", ev => { let transport = ev.target; if (transport.gatheringstate === "complete") { /* this transport has finished gathering candidates, but others may still be working on it */ } }, false); likewise, you can use the on...
RTCIceTransport: selectedcandidatepairchange event - Web APIs
bubbles no cancelable no interface event event handler property onselectedcandidatepairchange examples this example creates an event handler for selectedcandidatepairchange that updates a display providing the user information about the progress of the ice negotiation for an rtcpeerconnection
called pc.
RTCIceTransport.state - Web APIs
a value of "disconnected" means that a transient issue has occurred that has broken the connection, but that should resolve itself automati
cally without your code having to take any action.
RTCIceTransport: statechange event - Web APIs
bubbles no cancelable no interface event event handler property rtcicetransport.onstatechange examples given an rtcpeerconnection, pc, the following code creates an event handler that
calls a function named handlefailure() if the ice transport enters a failure state.
RTCPeerConnection: addstream event - Web APIs
if (pc.addtrack !== undefined) { pc.ontrack = ev => { ev.streams.foreach(stream => doaddstream(stream)); } } else { pc.onaddstream = ev => { doaddstream(ev.stream); } } this
calls a function doaddstream() once for each stream being added to the rtcpeerconnection, regardless of whether the browser sends addstream or track.
RTCPeerConnection: datachannel event - Web APIs
a datachannel event is sent to an rtcpeerconnection instance when an rtcdatachannel has been added to the connection, as a result of the remote peer
calling rtcpeerconnection.createdatachannel().
RTCPeerConnection.onicecandidateerror - Web APIs
the rtcpeerconnection.onicecandidateerror property is an eventhandler which specifies a function which is
called to handle the icecandidateerror event when it occurs on an rtcpeerconnection instance.
RTCPeerConnection.remoteDescription - Web APIs
the returned value typi
cally reflects a remote description which has been received over the signaling server (as either an offer or an answer) and then put into effect by your code
calling rtcpeerconnection.setremotedescription() in response.
RTCRtpCapabilities - Web APIs
the rtcrtpcapabilities dictionary is a data type used to describe the capabilities of an rtcrtpsender or rtcrtpreceiver in response to a
call to the rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities() static functions, both of which return an array of rtcrtpcapabilities objects.
RTCRtpCodecCapability - Web APIs
an array of objects of this type is returned in the codecs property of the rtcrtpcapabilities object returned in response to a
call to either of the static functions rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities().
RTCRtpCodecParameters - Web APIs
in addition to being the type of the rtcrtpparameters.codecs property, it's used when
calling rtcrtptransceiver.setcodecpreferences() to configure a transceiver's codecs before beginning the offer/answer process to establish a webrtc peer connection.
RTCRtpParameters - Web APIs
to obtain the parameters of a sender or receiver,
call its getparameters() method: getparameters() getparameters() properties codecs an array of rtcrtpcodecparameters objects describing the set of codecs from which the sender or receiver will choose.
RTCRtpReceiver.getStats() - Web APIs
the rtcrtpreceiver method getstats() asynchronously requests an rtcstatsreport object which provides statistics about incoming traffic on the owning rtcpeerconnection, returning a promise whose fulfillment handler will be
called once the results are available.
RTCRtpSender.dtmf - Web APIs
only audio tracks can support dtmf, and typi
cally only one audio track per rtcpeerconnection will have an associated rtcdtmfsender example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.dtmf' in that specification.
RTCRtpSender.getParameters() - Web APIs
examples this example gets the sender's current transaction id; the transaction id uniquely identifies the current set of parameters, to ensure that
calls to setparameters() are always handled in the correct order, avoiding inadvertently overwriting parameters with older parameters.
RTCRtpSender.setParameters() - Web APIs
transactionid a string containing a unique id for the last set of parameters applied; this value is used to ensure that setparameters() can only be
called to alter changes made by a specific previous
call to getparameters().
RTCRtpStreamStats.nackCount - Web APIs
a nack (negative acknowledgement, also
called "generic nack") packet tells the sender that one or more of the rtp packets it sent were lost in transport.
RTCRtpTransceiver.stop() - Web APIs
usage notes when you
call stop() on a transceiver, the sender immediately stops sending media and each of its rtp streams are closed using the rtcp "bye" message.
RTCRtpTransceiver.stopped - Web APIs
the transceiver is stopped if the stop() method has been
called or if a change to either the local or the remote description has caused the transceiver to be stopped for some reason.
RTCRtpTransceiver - Web APIs
stopped indicates whether or not sending and receiving using the paired rtcrtpsender and rtcrtpreceiver has been permanently disabled, either due to sdp offer/answer, or due to a
call to stop().
RTCRtpTransceiverInit - Web APIs
the rtcrtptransceiverinit dictionary is used when
calling the webrtc function rtcpeerconnection.addtransceiver() to provide configuration options for the new transceiver.
Range.toString() - Web APIs
alerting the contents of a range makes an implicit tostring()
call, so comparing range and text through an alert dialog is ineffective.
ReadableStream.getReader() - Web APIs
current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and
call this function again return reader.read().then(processtext); }); } specifications specification status comment streamsthe definition of 'getreader()' in that specification.
ReadableStream.tee() - Web APIs
current chunk = ' + chunk; list.appendchild(listitem); // read some more, and
call this function again return reader.read().then(processtext); }); } specifications specification status comment streamsthe definition of 'tee()' in that specification.
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and
call this function again return reader.read().then(processtext); }); } specifications specification status comment streamsthe definition of 'readablestreamdefaultreader()' in that specification.
ReadableStreamDefaultReader.read() - Web APIs
current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and
call this function again return reader.read().then(processtext); }); } example 2 - handling text line by line this example shows how you might fetch a text file and handle it as a stream of text lines.
RelativeOrientationSensor.RelativeOrientationSensor() - Web APIs
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.
Request.destination - Web APIs
others are script-based, in which case the received data is delivered to a script by
calling it and passing the data along.
Request.mode - Web APIs
however, for requests created other than by the request.request constructor, no-cors is typi
cally used as the mode; for example, for embedded resources where the request is initiated from markup, unless the crossorigin attribute is present, the request is in most cases made using the no-cors mode — that is, for the <link> or <script> elements (except when used with modules), or <img>, <audio>, <video>, <object>, <embed>, or <iframe> elements.
ResizeObserver.observe() - Web APIs
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); an observe()
call with an options object would look like so: resizeobserver.observe(divelem, { box : 'border-box' }); specifications specification status comment resize observerthe definition of 'observe()' in that specification.
ResizeObserver - Web APIs
resizeobserver avoids infinite
callback loops and cyclic dependencies that are often created when resizing via a
callback function.
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.
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.
Response.clone() - Web APIs
when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob
calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements.
RsaHashedKeyGenParams - Web APIs
warning: although you can techni
cally pass sha-1 as a value here, this is strongly discouraged as sha-1 is considered vulnerable.
RsaOaepParams - Web APIs
unless your application
calls for a label, you can just omit this argument and it will not affect the security of the encryption operation.
SVGAnimatedPoints - Web APIs
additionally, the points attribute on the original element accessed via the xml dom (e.g., using the getattribute() method
call) will reflect any changes made to the svganimatedpoints.points attribut.
SVGCircleElement - Web APIs
example svg content <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickcircle();"/> </svg> javascript content this function clickcircle() is
called when the circle is clicked.
SVGGraphicsElement: copy event - Web APIs
a handler for this event can modify the clipboard contents by
calling setdata(format, data) on the event's clipboardevent.clipboarddata property, and cancelling the event's default action using event.preventdefault().
SVGGraphicsElement: cut event - Web APIs
a handler for this event can modify the clipboard contents by
calling setdata(format, data) on the event's clipboardevent.clipboarddata property, and cancelling the default action using event.preventdefault().
getBBox() - Web APIs
note: getbbox() must return the actual bounding box at the time the method was
called—even in case the element has not yet been rendered.
SVGViewElement - Web APIs
each of the domstring values can be associated with the corresponding element using the getelementbyid() method
call.
Screen.availHeight - Web APIs
on a windows system, this would function similarly, by opening the window and sizing it verti
cally so it uses all available vertical space, leaving room for the taskbar and any other interface elements that reserve space.
Screen Capture API - Web APIs
to start capturing video from the screen, you
call getdisplaymedia() on the instance of media navigator.mediadevices: capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); the promise returned by getdisplaymedia() resolves to a mediastream which streams the captured media.
ScriptProcessorNode.onaudioprocess - Web APIs
the onaudioprocess event handler of the scriptprocessornode interface represents the eventhandler to be
called for the audioprocess event that is dispatched to scriptprocessornode node types.
ScriptProcessorNode - Web APIs
the size of the input and output buffer are defined at the creation time, when the audiocontext.createscriptprocessor() method is
called (both are defined by audiocontext.createscriptprocessor()'s buffersize parameter).
Selection.toString() - Web APIs
in javascript, this method is
called automati
cally when a function the selection object is passed to requires a string: alert(window.getselection()) // what is
called alert(window.getselection().tostring()) // what is actually being effectively
called.
Sensor.onerror - Web APIs
the onerror eventhandler is
called when an error occurs on one of the child interfaces of the sensor interface.
Sensor.onreading - Web APIs
the onreading eventhandler is
called when a reading is taken on one of the child interfaces of the sensor interface.
ServiceWorker - Web APIs
event handlers serviceworker.onstatechange read only an eventlistener property
called whenever an event of type statechange is fired; it is basi
cally fired anytime the serviceworker.state changes.
ServiceWorkerContainer.onmessage - Web APIs
the onmessage property of the serviceworkercontainer interface is an event handler fired whenever a message event occurs — when incoming messages are received to the serviceworkercontainer object (e.g., via a client.postmessage()
call).
ServiceWorkerContainer.ready - Web APIs
example if ('serviceworker' in navigator) { navigator.serviceworker.ready .then(function(registration) { console.log('a service worker is active:', registration.active); // at this point, you can
call methods that require an active // service worker, like registration.pushmanager.subscribe() }); } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkerregistration.ready' in that specification.
ServiceWorkerGlobalScope: message event - Web APIs
bubbles no cancelable no interface extendablemessageevent event handler property onmessage examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then
calls its postmessage() function.
ServiceWorkerGlobalScope.onfetch - Web APIs
the onfetch property of the serviceworkerglobalscope interface is an event handler fired whenever a fetch event occurs (usually when the windoworworkerglobalscope.fetch() method is
called.) syntax serviceworkerglobalscope.onfetch = function(fetchevent) { ...
ServiceWorkerGlobalScope.onnotificationclick - Web APIs
the serviceworkerglobalscope.onnotificationclick property is an event handler
called whenever the notificationclick event is dispatched on the serviceworkerglobalscope object, that is when a user clicks on a displayed notification spawned by serviceworkerregistration.shownotification().
onnotificationclose - Web APIs
the serviceworkerglobalscope.onnotificationclose property is an event handler
called whenever the notificationclose event is dispatched on the serviceworkerglobalscope object, that is when a user closes a displayed notification spawned by serviceworkerregistration.shownotification().
ServiceWorkerRegistration.active - Web APIs
an active worker controls a serviceworkerclient if the client's url falls within the scope of the registration (the scope option set when serviceworkercontainer.register is first
called.) note: this feature is available in web workers.
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.unregister() - Web APIs
the promise will resolve to false if no registration was found, otherwise it resolves to true irrespective of whether unregistration happened or not (it may not unregister if someone else just
called serviceworkercontainer.register() with the same scope.) the service worker will finish any ongoing operations before it is unregistered.
SharedWorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can
call the following: close(); close() and self.close() are effectively equivalent — both represent close() being
called from inside the worker's inner scope.
SharedWorkerGlobalScope.onconnect - Web APIs
the onconnect property of the sharedworkerglobalscope interface is an event handler representing the code to be
called when the connect event is raised — that is, when a messageport connection is opened between the associated sharedworker and the main thread.
Slottable: assignedSlot - Web APIs
examples in our simple-template example (see it live), we create a trivial custom element example
called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
Storage.key() - Web APIs
examples the following function iterates over the local storage keys: function foreachkey(
callback) { for (var i = 0; i < localstorage.length; i++) {
callback(localstorage.key(i)); } } the following function iterates over the local storage keys and gets the value set for each key: for(var i =0; i < localstorage.length; i++){ console.log(localstorage.getitem(localstorage.key(i))); } note: for a real world example, see our web storage demo.
StorageEstimate.quota - Web APIs
the storageestimate dictionary's quota property is a conservative approximation of how much storage is allotted to the origin or web app that
called storagemanager.estimate(); there may be more space available, but there will not be less.
StorageEstimate.usage - Web APIs
the storageestimate dictionary's usage property is a conservative approximation of how much storage is allotted to the origin or web app that
called storagemanager.estimate(); there may be more space available, but there will not be less.
Streams API - Web APIs
the streams api allows javascript to programmati
cally access streams of data received over the network and process them as desired by the developer.
SubmitEvent - Web APIs
with that in hand, we can
call a processorder() function to handle the order, passing along the form and the handler id.
TaskAttributionTiming - Web APIs
the frame context, also
called the container, is the iframe, embed or object that is being implicated, on the whole, for a long task.
TextDecoder.prototype.decode() - Web APIs
options optional is a textdecodeoptions dictionary with the property: stream a boolean flag indicating that additional data will follow in subsequent
calls to decode().
TextEncoder - Web APIs
these sequences are not already precomputed because they serve to aestheti
cally illustrate how the polyfill works.
TextTrack.mode - Web APIs
example in this example, we configure the text track's cues so that every time a cue is finished, the video automati
cally pauses playback.
TextTrackList.onremovetrack - Web APIs
the texttracklist onremovetrack event handler is
called when the removetrack event occurs, indicating that a text track has been removed from the media element, and therefore also from the texttracklist.
TimeEvent - Web APIs
this method may only be
called before the timeevent has been dispatched via the dispatchevent method, though it may be
called multiple times during that phase if necessary.
TrackEvent - Web APIs
example this example sets up a function, handletrackevent(), which is
callled for any addtrack or removetrack event on the first <video> element found in the document.
TreeWalker.filter - Web APIs
when creating the treewalker, the filter object is passed in as the third parameter, and its method nodefilter.acceptnode() is
called on every single node to determine whether or not to accept it.
sourceCapabilities - Web APIs
for example, many user agents allow a window to be resized with a mouse or a keyboard, but this detail is not exposed to the web platform in any way, and so the sourcecapabilities of a resize event will typi
cally be null.
URL.search - Web APIs
the search property of the url interface is a search string, also
called a query string, that is a usvstring containing a '?' followed by the parameters of the url.
URL.search - Web APIs
the search property of the url interface is a search string, also
called a query string, that is a usvstring containing a '?' followed by the parameters of the url.
URL - Web APIs
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.
URLSearchParams - Web APIs
urlsearchparams.foreach() allows iteration through all values contained in this object via a
callback function.
USB.onconnect - Web APIs
the onconnect property of the usb interface is an event handler
called whenever a paired device is connected.
USBDevice.opened - Web APIs
it shows how to test that a device is open before
calling usbdevice.controltransferout to set a specified led color.
USBIsochronousInTransferPacket - Web APIs
the usbisochronousintransferpacket interface of the webusb api is part of the response from a
call to the isochronoustransferin() method of the usbdevice interface.
ValidityState - Web APIs
customerror read only a boolean indicating whether the element's custom validity message has been set to a non-empty string by
calling the element's setcustomvalidity() method.
VideoConfiguration - Web APIs
the videoconfiguration dictionary of the media capabilities api is used to define the video file being tested when
calling the mediacapabilities methods encodinginfo() and decodinginfo() to determine whether or not the described video configuration is supported, and how smoothly and how smoooth and power-efficient it can be handled.
VideoPlaybackQuality.corruptedVideoFrames - Web APIs
example this example determines the percentage of frames which have been corrupted, and if the value is greater than 5%,
calls a funciton
called downgradevideo() that would be implemented to switch to a different video that might tax the network less.
VideoTrack.id - Web APIs
syntax var trackid = videotrack.id; value a domstring which identifies the track, suitable for use when
calling gettrackbyid() on an videotracklist such as the one specified by a media element's videotracks property.
VideoTrack - Web APIs
this id can be used to locate a specific track within a video track list by
calling videotracklist.gettrackbyid().
VideoTrackList.onremovetrack - Web APIs
the videotracklist onremovetrack event handler is
called when the removetrack event occurs, indicating that a video track has been removed from the media element, and therefore also from the videotracklist.
WEBGL_debug_renderer_info - Web APIs
the webglrenderingcontext.getparameter() method can help you to detect which features are supported and the failifmajorperformancecaveat context attribute lets you control if a context should be returned at all, if the performance would be dramati
cally slow.
WebGL2RenderingContext.readBuffer() - Web APIs
the webgl2renderingcontext.readbuffer() method of the webgl 2 api selects a color buffer as the source for pixels for subsequent
calls to copyteximage2d, copytexsubimage2d, copytexsubimage3d or readpixels.
WebGL2RenderingContext - Web APIs
to get an object of this interface,
call getcontext() on a <canvas> element, supplying "webgl2" as the argument: var canvas = document.getelementbyid('mycanvas'); var gl = canvas.getcontext('webgl2'); webgl 2 is an extension to webgl 1.
WebGLActiveInfo.name - Web APIs
the read-only webglactiveinfo.name property represents the name of the requested data returned by
calling the getactiveattrib() or getactiveuniform() methods.
WebGLActiveInfo.size - Web APIs
the read-only webglactiveinfo.size property is a number representing the size of the requested data returned by
calling the getactiveattrib() or getactiveuniform() methods.
WebGLActiveInfo.type - Web APIs
the read-only webglactiveinfo.type property represents the type of the requested data returned by
calling the getactiveattrib() or getactiveuniform() methods.
WebGLActiveInfo - Web APIs
the webglactiveinfo interface is part of the webgl api and represents the information returned by
calling the webglrenderingcontext.getactiveattrib() and webglrenderingcontext.getactiveuniform() methods.
WebGLRenderingContext.getActiveUniform() - Web APIs
sampler_2d gl.sampler_3d gl.sampler_cube gl.sampler_2d_shadow gl.sampler_2d_array gl.sampler_2d_array_shadow gl.sampler_cube_shadow gl.int_sampler_2d gl.int_sampler_3d gl.int_sampler_cube gl.int_sampler_2d_array gl.unsigned_int_sampler_2d gl.unsigned_int_sampler_3d gl.unsigned_int_sampler_cube gl.unsigned_int_sampler_2d_array when gl.linkprogram is
called, webgl creates a list of active uniforms.
WebGLShaderPrecisionFormat - Web APIs
the webglshaderprecisionformat interface is part of the webgl api and represents the information returned by
calling the webglrenderingcontext.getshaderprecisionformat() method.
Data in WebGL - Web APIs
attributes are typi
cally used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the javascript code and the vertex shader.
Lighting in WebGL - Web APIs
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().
Using WebGL extensions - Web APIs
extension objects if an extension defines specific symbols or functions that are not available in the core specification of webgl, they will be available on the extension object returned by the
call to gl.getextension().
WebGL: 2D and 3D graphics for the web - Web APIs
advanced tutorials webgl model view projection a detailed explanation of the three core matrices that are typi
cally used to represent a 3d object view: the model, view and projection matrices.
WebSocket: close event - Web APIs
given that you have a variable
called examplesocket that refers to an opened websocket, this handler would handle the situation where the socket has been closed.
WebSocket.onerror - Web APIs
the websocket interface's onerror event handler property is a function which gets
called when an error occurs on the websocket.
WebSocket.send() - Web APIs
if the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automati
cally.
The WebSocket API (WebSockets) - Web APIs
jsonrpc-bidirectional: asynchronous rpc which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may
call server, server may also
call client).
WebXR performance guide - Web APIs
this section will combine information from https://github.com/immersive-web/webxr/blob/master/explainer.md#controlling-depth-precision and https://github.com/immersive-web/webxr/blob/master/explainer.md#preventing-the-compositor-from-using-the-depth-buffer optimizing memory use when using libraries that perform things such as matrix mathematics, you typi
cally have a number of working variables through which various vectors, matrices, and quaternions pass over time.
Targeting and hit detection - Web APIs
it's possible—or even likely—that whatever 3d graphics engine you're using offers hit testing, especially if it's designed specifi
cally for game development.
Using IIR filters - Web APIs
(), which creates a buffer source from an existing audiobuffer, attaches it to the default destination, starts it playing, and returns it: function playsourcenode(audiocontext, audiobuffer) { const soundsource = audiocontext.createbuffersource(); soundsource.buffer = audiobuffer; soundsource.connect(audiocontext.destination); soundsource.start(); return soundsource; } this function is
called when the play button is pressed.
Web audio spatialization basics - Web APIs
basics of spatialization in web audio, complex 3d spatializations are created using the pannernode, which in layman's terms is basi
cally a whole lotta cool maths to make audio appear in 3d space.
Web Crypto API - Web APIs
interfaces some browsers implemented an interface
called crypto without having it well defined or being cryptographi
cally sound.
Web NFC API - Web APIs
note: devices and tags have to be formatted and recorded specifi
cally to support ndef record format to be used with web nfc.
Web Speech API - Web APIs
window.speechsynthesis specced out as part of a [nointerfaceobject] interface
called speechsynthesisgetter, and implemented by the window object, the speechsynthesis property provides access to the speechsynthesis controller, and therefore the entry point to speech synthesis functionality.
Window.closed - Web APIs
refreshing a previously opened popup in this example the function refreshpopupwindow()
calls the reload() method of the popup's location object to refresh its data.
Window.devicePixelRatio - Web APIs
then the updatepixelratio() function is
called once to display the starting value, after which the media query is created using matchmedia() and addeventlistener() is
called to set up updatepixelratio() as a handler for the change event.
window.dump() - Web APIs
note that dump output from xpcom components goes to stderr, while dump
called elsewhere will output to stdout.
Window.getDefaultComputedStyle() - Web APIs
in particular, to avoid the so
called css history leak security issue, browsers may expressly "lie" about the used value for a link and always return values as if a user has never visited the linked site, and/or limit the styles that can be applied using the :visited pseudo-selector.
window.location - Web APIs
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.matchMedia() - Web APIs
css .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde; } result see testing media queries programmati
cally for additional code examples.
Window: message event - Web APIs
the message event is fired on a window object when the window receives a message, for example from a
call to window.postmessage() from another browsing context.
Window.onmozbeforepaint - Web APIs
notes this event fires immediately before the browser window is repainted, if the event has been requested by one or more scripts
calling window.mozrequestanimationframe().
Window.onuserproximity - Web APIs
the window.onuserproxymity property represents an eventhandler, that is a function to be
called when the userproximity event occurs.
Window.personalbar - Web APIs
also be aware that dynami
cally updating the visibilty of the various toolbars can change the size of the window rather dramati
cally, and may affect the layout of your page.
Window.routeEvent() - Web APIs
the window method routeevent(), which is obsolete and no longer available, used to be
called to forward an event to the next object that has asked to capture events.
Window.scrollMaxY - Web APIs
the window.scrollmaxy read-only property returns the maximum number of pixels that the document can be scrolled verti
cally.
Window.sizeToContent() - Web APIs
in order for it to work, the dom content should be loaded when this function is
called—for example, once the domcontentloaded event has been thrown.
Window.statusbar - Web APIs
also be aware that dynami
cally updating the visibilty of the various toolbars can change the size of the window rather dramati
cally, and may affect the layout of your page.
Window.toolbar - Web APIs
also be aware that dynami
cally updating the visibilty of the various toolbars can change the size of the window rather dramati
cally, and may affect the layout of your page.
Window.window - Web APIs
for example, if we refer to "this.window.location.href", a javascript module could define a property
called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor.
WindowEventHandlers.onhashchange - Web APIs
function hashhandler() { console.log('the hash has changed!'); } window.addeventlistener('hashchange', hashhandler, false); overriding the hash this function sets a new hash dynami
cally, setting it randomly to one of two values.
WindowEventHandlers.onmessageerror - Web APIs
the onmessageerror event handler of the windoweventhandlers interface is an eventlistener,
called whenever an messageevent of type messageerror is fired on a window—that is, when it receives a message that cannot be deserialized.
WindowOrWorkerGlobalScope.origin - Web APIs
examples executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message onmessage = function() { console.log(self.origin); }; if the origin is not a scheme/host/port tuple (say you are trying to run it lo
cally, i.e.
Worker.onmessageerror - Web APIs
the onmessageerror event handler of the worker interface is an eventlistener,
called whenever an messageevent of type messageerror is fired on the worker instance — that is, when it receives a message that cannot be deserialized.
WorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you wanted to close your worker instance from inside the worker itself, you could
call the following: close(); close() and self.close() are effectively equivalent — both represent close() being
called from inside the worker's inner scope.
WorkerGlobalScope.importScripts() - Web APIs
example if you had some functionality written in a separate script
called foo.js that you wanted to use inside worker.js, you could import it using the following line: importscripts('foo.js'); importscripts() and self.importscripts() are effectively equivalent — both represent importscripts() being
called from inside the worker's inner scope.
WorkerGlobalScope.location - Web APIs
example if you
called the following in a document served at localhost:8000 console.log(location); inside a worker (which would basi
cally be the equivalent of self.console.log(self.location);, as these are being
called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerlocation object written to the console — something like the following: workerlocation {hash: "", search: "", pathname: "/worker.js", port: "8000", hostname: "localhost"…} ...
WorkerGlobalScope.navigator - Web APIs
example if you
call the following console.log(navigator); inside a worker (which would basi
cally be the equivalent of self.console.log(self.navigator);, as these are being
called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workernavigator object written to the console — something like the following: object {online: true, useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) ap…ml, like gecko) chrome/40.0.2214.93 safari/537.
WorkerGlobalScope.onclose - Web APIs
summary the onclose property of the workerglobalscope interface represents an eventhandler to be
called when the close event occurs and bubbles through the worker.
WorkerGlobalScope.onerror - Web APIs
the onerror property of the workerglobalscope interface represents an eventhandler to be
called when the error event occurs and bubbles through the worker.
WorkerGlobalScope.onoffline - Web APIs
the onoffline property of the workerglobalscope interface represents an eventhandler to be
called when the offline event occurs and bubbles through the worker.
WorkerGlobalScope.ononline - Web APIs
the ononline property of the workerglobalscope interface represents an eventhandler to be
called when the online event occurs and bubbles through the worker.
WorkerGlobalScope.performance - Web APIs
example if you
called console.log(performance); inside a worker (which would basi
cally be the equivalent of self.console.log(self.performance);, as these are being
called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerperformance object written to the console — something like the following: workerperformance {now: function} __proto__: workerperformance constructor: function workerperformance() { [native code] } now: functi...
WorkerGlobalScope.self - Web APIs
example if you
called console.log(self); inside a worker, you will get a worker global scope of the same type as that worker object written to the console — something like the following: dedicatedworkerglobalscope { undefined: undefined, infinity: infinity, math: mathconstructor, nan: nan, intl: object…} infinity: infinity array: function array() { [native code] } arguments: null
caller: n...
WorkerLocation - Web APIs
such an object is initialized for each worker and is available via the workerglobalscope.location property obtained by
calling self.location.
WorkerNavigator - Web APIs
such an object is initialized for each worker and is available via the workerglobalscope.navigator property obtained by
calling window.self.navigator.
Worklet - Web APIs
instead, you can use one of the following classes: name description location specification paintworklet for programmati
cally generating an image where a css property expects a file.
WritableStreamDefaultWriter.ready - Web APIs
defaultwriter.ready .then(function() { defaultwriter.write(chunk) .then(function() { console.log("chunk written to sink.); }) .catch(function(err) { console.log("chunk error: " + err); }); }); //
call ready again to ensure that all chunks are written // before closing the writer.
XPathEvaluator.createNSResolver() - Web APIs
this adapter works like the dom level 3 method node.lookupnamespaceuri() in resolving the namespace uri from a given prefix using the current information available in the node's hierarchy at the time the method is
called, also correctly resolving the implicit xml prefix.
XRBoundedReferenceSpace - Web APIs
this is typi
cally used when the xr system is capable of tracking the user's physical movement within a limited distance of their starting position.
XRInputSource - Web APIs
if the device includes a trigger or other squeezable input, such as a hand gesture device that recognizes when the user squeezes their fist, that action is
called a primary squeeze action.
XRInputSourceArray - Web APIs
in addition to these methods, you may use array notation to access items in the list by index for example, the snippet of code below
calls a function handleinput(), passing into it the first item in the input source list, if the list isn't empty.
XRInputSourceEventInit.frame - Web APIs
usage notes the event frame does not correspond to a visual frame as is delivered to the frame rendering
callback function (see rendering and the webxr frame rendering
callback for details on the
callback).
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.
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.
XRPose - Web APIs
to obtain the xrpose for the xrspace used as the local coordinate system of an object,
call xrframe.getpose(), specifying that local xrspace and the space to which you wish to convert: thepose = xrframe.getpose(localspace, basespace); the pose for a viewer (or camera) is represented by the xrviewerpose subclass of xrpose.
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 canv...
XRRenderStateInit - Web APIs
the xrrenderstateinit dictionary is a writeable version of the xrrenderstate interface, and is used when
calling an xrsession's updaterenderstate() method to apply changes to the render state prior to rendering the next frame.
XRRigidTransform.orientation - Web APIs
the read-only xrrigidtransform property orientation is a dompointreadonly containing a normalized quaternion (also
called a unit quaternion or versor) specifying the rotational component of the transform represented by the object.
XRRigidTransform.position - Web APIs
however, for inline sesions, we know we're in a space not automati
cally adjusted for floor level, so we request an offset reference space to shift the viewer's height to 1.5 meters above the presumed floor level of 0 meters.
XRSession.end() - Web APIs
the end() method shuts down the xrsession on which it's
called, returning a promise which resolves once the session has fully shut down.
XRSession.onsqueeze - Web APIs
then we pass the currently held object and the target ray's transform matrix into a function we
call dropobjectusingray() to drop the object, using the target ray to determine the surface upon which the object should be placed.
XRSession.onsqueezeend - Web APIs
if heldobject has an object reference, that object is passed to a function
called cancelobjectdrag(), which would be written to return the object to its original position.
XRSession.onsqueezestart - Web APIs
examples this snippet of code adds a simple handler for the squeezestart event, which responds only to events on the user's dominant hand by getting the target ray, then
calling a function findobjectusingray() to identify the object that the user is pointing at.
XRSession: select event - Web APIs
the handler fetches the pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function
called myhandleselectwithray().
XRSession: squeeze event - Web APIs
the handler fetches the pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function
called myhandlesqueezewithray().
XRSessionEvent() - Web APIs
it reacts by
calling a function mysessionvisible() with a boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene.
XRSessionEvent.session - Web APIs
xrsession.addeventlistener("visibilitychange", e => { switch(e.session.visibilitystate) { case "hidden": myenablerendering(true); break; case "visible": case "visible-blurred": myenablerendering(false); break; } }); this
calls a function that reacts to the session's visibility state change.
XRSessionEvent - Web APIs
it reacts by
calling a function mysessionvisible() with a boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene.
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: devicechange event - Web APIs
if (navigator.xr) { navigator.xr.addeventlistener("devicechange", event => { navigator.xr.issessionsupported("immersive-vr") .then(immersiveok) => { if (immersiveok) { enablexrbutton.disabled = false; } else { enablexrbutton.disabled = true; } }); }); } when devicechange is received, the handler set up in this code
calls the xr method issessionsupported() to find out if there's a device available that can handle immersive vr presentations.
XRViewerPose.views - Web APIs
examples in this example—part of the code to render an xrframe, getviewerpose() is
called to get an xrviewerpose using the same reference space the code is using as its base reference space.
XRViewport.x - Web APIs
the read-only xrviewport interface's x property indicates the offset from the left edge of the destination surface (typi
cally a xrwebgllayer to the left edge of the viewport within the surface into which webxr content is to be rendered.
XRWebGLLayer.getViewport() - Web APIs
example this example demonstrates in part what the
callback for the requestanimationframe() function might look like, using getviewport() to get the viewport so that drawing can be constrained to the area set aside for the eye whose viewpoint is currently being rendered.
XRWebGLLayerInit.antialias - Web APIs
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.
XRWebGLLayerInit.ignoreDepthValues - Web APIs
the depth buffer is typi
cally used to assist in ordering vertices and, by extension, polygons while compositing, to ensure that the scene is correctly composited, with objects the correct distance away and with clipping and other distance-related computations performed as accurately as possible.
msCapsLockWarningOff - Web APIs
starting with internet explorer 10, input type=password fields will automati
cally display a warning if the caps lock is on.
msthumbnailclick - Web APIs
.mssitemodecleariconoverlay(); // pinned icons on your taskbar can be instructed to trigger specific events on your site from the taskbar // add an event handlerdocument.addeventlistener('msthumbnailclick', onbuttonclicked, false); // add the buttons var btnplay = window.external.mssitemodeaddthumbbarbutton(iconuri, tooltip); // refresh the taskbar window.external.mssitemodeshowthumbbar(); //
call a javascript function when the button is pressed function onbuttonclicked(e) { switch (e.buttonid) { case btnplay: play(); break;} } see also microsoft api extensions ...
Using the article role - Accessibility
possible effects on user agents and assistive technology when the user navigates an element assigned the role of article, assistive technologies that typi
cally intercept standard keyboard events should switch to document browsing mode, as opposed to passing keyboard events through to the web application.
Using the group role - Accessibility
the group role is used to identify a set of user interface objects which, in contrast with a region, are not intended to be included in a table of contents or a page summary (such as the structures that are dynami
cally created by a script or assistive technologies); a group should not be considered a major perceivable section on a page.
Using the status role - Accessibility
<p role="status">your changes were automati
cally saved.</p> working examples: notes aria attributes used status related aria techniques alert role live region roles live region attributes compatibility the paciello group published some data on compatibility via their 2014 blog post: screen reader support for aria live regions tbd: add updated support information for common ua and at product combinations add...
ARIA: banner role - Accessibility
the banner is typi
cally includes things a logo or corporate identity, possibly a site-specific search tool, and is generally what your marketing team would
call the header or top banner of the site.
ARIA: List role - Accessibility
examples aria lists — some useful examples and thoughts by scott o'hara best practices only use role="list" and role="listitem" if you have to — for example if you don't have control over your html but are able to improve accessibility dynami
cally after the fact with javascript.
ARIA: Listitem role - Accessibility
examples aria lists — some useful examples and thoughts by scott o'hara best practices only use role="list" and role="listitem" if you have to — for example if you don't have control over your html but are able to improve accessibility dynami
cally after the fact with javascript.
ARIA: textbox role - Accessibility
for example, in a combobox, focus may remain on the textbox while the value of aria-activedescendant on the textbox element refers to a descendant of a popup listbox that is controlled by the textbox.this attribute must be updated programmati
cally as the focus changes.
Keyboard - Accessibility
in such a case, focusing the nested document is the only way of returning assistive technology to a non-interactive state (often
called "browse mode").
-webkit-mask-position-y - CSS: Cascading Style Sheets
formal definition initial value0%applies toall elementsinheritednopercentagesrefer to the size of the box itselfcomputed valuefor <length> the absolute value, otherwise a percentageanimation typediscrete formal syntax [ <length-percentage> | top | center | bottom ]#where <length-percentage> = <length> | <percentage> examples verti
cally positioning a mask image .exampleone { -webkit-mask-image: url(mask.png); -webkit-mask-position-y: bottom; } .exampletwo { -webkit-mask-image: url(mask.png); -webkit-mask-position-y: 25%; } specifications not part of any standard.
::selection - CSS: Cascading Style Sheets
for people experiencing cognitive concerns or who are less technologi
cally literate, unexpected changes to selection styles may hurt their understanding of the functionality.
:target - CSS: Cascading Style Sheets
/* selects an element with an id matching the current url's fragment */ :target { border: 2px solid black; } for example, the following url has a fragment (denoted by the # sign) that points to an element
called section2: http://www.example.com/index.html#section2 the following element would be selected by a :target selector when the current url is equal to the above: <section id="section2">example</section> syntax :target examples a table of contents the :target pseudo-class can be used to highlight the portion of a page that has been linked to from a table of contents.
system - CSS: Cascading Style Sheets
an additional descriptor
called additive-symbols must be specified with at least one additive tuple, or else the counter style rule will not be valid.
font-stretch - CSS: Cascading Style Sheets
however some fonts,
called variable fonts, can support a range of stretching with more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight.
font-style - CSS: Cascading Style Sheets
true italics use different glyphs and are a bit different from their upright counterparts, having some unique features and generally have a rounded and
calligraphic quality.
font-weight - CSS: Cascading Style Sheets
however some fonts,
called variable fonts, can support a range of weights with more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight.
@import - CSS: Cascading Style Sheets
note that the url for a mozilla package need not actually specify a file; it can just specify the package name and part, and the appropriate file is chosen automati
cally (e.g.
-ms-high-contrast - CSS: Cascading Style Sheets
high contrast mode is a specialized display mode that prioritizes making content as legible as possible by dynami
cally replacing foreground and background colors with a user-specified theme.
orientation - CSS: Cascading Style Sheets
syntax values auto the user agent will set the document's orientation automati
cally, typi
cally based on the device's orientation as determined by an accelerometer (if the device has such a hardware sensor), although there is often a user-controlled, os-level "lock orientation" setting that will trump the accelerometer reading.
Questions about CSS - CSS: Cascading Style Sheets
an imported style sheet, using the css @import notation to automati
cally import and merge an external style sheet with the current style sheet style attributes specified by the viewer to the browser the default style sheet assumed by the browser in general, the web page creator's style sheet takes precedence, but it's recommended that browsers provide ways for the viewer to override the style attributes in some respects.
ID selectors - CSS: Cascading Style Sheets
/* the element with id="demo" */ #demo { border: red 2px solid; } syntax #id_value { style properties } note that syntacti
cally (but not specificity-wise), this is equivalent to the following attribute selector: [id=id_value] { style properties } examples css #identified { background-color: skyblue; } html <div id="identified">this div has a special id on it!</div> <div>this is just a regular div.</div> result specifications specification status comment selectors level 4the definition of 'id selectors' in that specification.
Layout mode - CSS: Cascading Style Sheets
a css layout mode, sometimes simply
called layout, is an algorithm that determines the position and size of boxes based on the way they interact with their sibling and ancestor boxes.
Universal selectors - CSS: Cascading Style Sheets
examples css * [lang^=en] { color: green; } *.warning { color: red; } *#maincontent { border: 1px solid blue; } .floating { float: left } /* automati
cally clear the next sibling after a floating element */ .floating + * { clear: left; } html <p class="warning"> <span lang="en-us">a green span</span> in a red paragraph.
WebKit CSS extensions - CSS: Cascading Style Sheets
ebkit-flow-into -webkit-grid-columns (see grid-column) -webkit-grid-rows (see grid-row) -webkit-hyphenate-charset -webkit-image-set (see image-set()) -webkit-mask-attachment -webkit-match-nearest-mail-blockquote-color -webkit-overflow-scrolling -webkit-region-break-after -webkit-region-break-before -webkit-region-break-inside -webkit-region-fragment -webkit-shape-inside -webkit-touch-
callout (see touch-action) background-origin-x (unprefixed!) background-origin-y (unprefixed!) * still supported in the safari technology preview, but not in a generally released browser.
animation-name - CSS: Cascading Style Sheets
syntax /* single animation */ animation-name: none; animation-name: test_05; animation-name: -specific; animation-name: sliding-verti
cally; /* multiple animations */ animation-name: test1, animation4; animation-name: none, -moz-specific, sliding; /* global values */ animation-name: initial animation-name: inherit animation-name: unset values none a special keyword denoting no keyframes.
background-color - CSS: Cascading Style Sheets
though techni
cally removing the transparent keyword, this doesn't change anything as it has been incorporated as a true <color> backgrounds level 3 github issues css level 2 (revision 1)the definition of 'background-color' in that specification.
background-position-y - CSS: Cascading Style Sheets
a value of 0% means that the top edge of the background image is aligned with the top edge of the container, and a value of 100% means that the bottom edge of the background image is aligned with the bottom edge of the container, thus a value of 50% verti
cally centers the background image.
block-size - CSS: Cascading Style Sheets
syntax /* <length> values */ block-size: 300px; block-size: 25em; /* <percentage> values */ block-size: 75%; /* keyword values */ block-size: max-content; block-size: min-content; block-size: fit-content(20em); block-size: auto; /* global values */ block-size: inherit; block-size: initial; block-size: unset; if the writing mode is verti
cally oriented, the value of block-size relates to the width of the element; otherwise, it relates to the height of the element.
border-image-slice - CSS: Cascading Style Sheets
however, we have also provided two sliders to allow you to dynami
cally change the values of the above two properties, allowing you to appreciate the effect they have: border-image-slice changes the size of the image slice sampled for use in each border and border corner (and the content area, if the fill keyword is used) — varying this away from 30 causes the border to look somewhat irregular, but can have some interesting effects.
box-align - CSS: Cascading Style Sheets
{ display: box; /* as specified */ display: -moz-box; /* mozilla */ display: -webkit-box; /* webkit */ /* make this box taller than the children, so there is room for the box-pack */ height: 400px; /* make this box wider than the children so there is room for the box-align */ width: 300px; /* children should be oriented verti
cally */ box-orient: vertical; /* as specified */ -moz-box-orient: vertical; /* mozilla */ -webkit-box-orient: vertical; /* webkit */ /* align children to the horizontal center of this box */ box-align: center; /* as specified */ -moz-box-align: center; /* mozilla */ -webkit-box-align: center; /* webkit */ /* pack children to the bottom of ...
box-decoration-break - CSS: Cascading Style Sheets
block box fragments a block element with similar styles as above and no fragmentation results in: fragmenting the above block into three columns results in: note that stacking these pieces verti
cally will result in the non-fragmented rendering.
box-lines - CSS: Cascading Style Sheets
the box-lines css property determines whether the box may have a single or multiple lines (rows for horizontally oriented boxes, columns for verti
cally oriented boxes).
box-pack - CSS: Cascading Style Sheets
start | center | end | justify examples div.example { border-style: solid; display: -moz-box; /* mozilla */ display: -webkit-box; /* webkit */ /* make this box taller than the children, so there is room for the box-pack */ height: 300px; /* make this box wide enough to show the contents are centered horizontally */ width: 300px; /* children should be oriented verti
cally */ -moz-box-orient: vertical; /* mozilla */ -webkit-box-orient: vertical; /* webkit */ /* align children to the horizontal center of this box */ -moz-box-align: center; /* mozilla */ -webkit-box-align: center; /* webkit */ /* pack children to the bottom of this box */ -moz-box-pack: end; /* mozilla */ -webkit-box-pack: end; /* webkit */ } div.example p { ...
calc() - CSS: Cascading Style Sheets
banner that stretches across the window, with a 40-pixel gap between both sides of the banner and the edges of the window: .banner { position: absolute; left: 40px; width: calc(100% - 80px); border: solid black 1px; box-shadow: 1px 2px; background-color: yellow; padding: 6px; text-align: center; box-sizing: border-box; } <div class="banner">this is a banner!</div> automati
cally sizing form fields to fit their container another use case for calc() is to help ensure that form fields fit in the available space, without extruding past the edge of their container, while maintaining an appropriate margin.
color-adjust - CSS: Cascading Style Sheets
exact the element's content has been specifi
cally and carefully crafted to use colors, images, and styles in a thoughtful and/or important way, such that being altered by the browser might actually make things worse rather than better.
flex-basis - CSS: Cascading Style Sheets
syntax /* specify <'width'> */ flex-basis: 10em; flex-basis: 3px; flex-basis: auto; /* intrinsic sizing keywords */ flex-basis: fill; flex-basis: max-content; flex-basis: min-content; flex-basis: fit-content; /* automati
cally size based on the flex item’s content */ flex-basis: content; /* global values */ flex-basis: inherit; flex-basis: initial; flex-basis: unset; the flex-basis property is specified as either the keyword content or a <'width'>.
font-language-override - CSS: Cascading Style Sheets
/* keyword value */ font-language-override: normal; /* <string> values */ font-language-override: "eng"; /* use english glyphs */ font-language-override: "trk"; /* use turkish glyphs */ /* global values */ font-language-override: initial; font-language-override: inherit; font-language-override: unset; by default, html's lang attribute tells browsers to display glyphs designed specifi
cally for that language.
font-weight - CSS: Cascading Style Sheets
however some fonts,
called variable fonts, can support a range of weights with a more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight.
grid-area - CSS: Cascading Style Sheets
note: named grid areas automati
cally generate implicit named lines of this form, so specifying grid-area: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it).
grid-column-end - CSS: Cascading Style Sheets
note: named grid areas automati
cally generate implicit named lines of this form, so specifying grid-column-end: foo; will choose the end edge of that named grid area (unless another line named foo-end was explicitly specified before it).
grid-column-start - CSS: Cascading Style Sheets
note: named grid areas automati
cally generate implicit named lines of this form, so specifying grid-column-start: foo; will choose the start edge of that named grid area (unless another line named foo-start was explicitly specified before it).
grid-column - CSS: Cascading Style Sheets
note: named grid areas automati
cally generate implicit named lines of this form, so specifying grid-column: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it).
grid-row-end - CSS: Cascading Style Sheets
note: named grid areas automati
cally generate implicit named lines of this form, so specifying grid-row-end: foo; will choose the end edge of that named grid area (unless another line named foo-end was explicitly specified before it).
grid-row-start - CSS: Cascading Style Sheets
note: named grid areas automati
cally generate implicit named lines of this form, so specifying grid-row-start: foo; will choose the start edge of that named grid area (unless another line named foo-start was explicitly specified before it).
grid-row - CSS: Cascading Style Sheets
note: named grid areas automati
cally generate implicit named lines of this form, so specifying grid-row: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it).
inherit - CSS: Cascading Style Sheets
for non-inherited properties, this specifies a behavior that typi
cally makes relatively little sense and you may consider using initial instead, or unset on the all property.
initial - CSS: Cascading Style Sheets
examples using initial to reset color for an element html <p> <span>this text is red.</span> <em>this text is in the initial color (typi
cally black).</em> <span>this is red again.</span> </p> css p { color: red; } em { color: initial; } result specifications specification status comment css cascading and inheritance level 4the definition of 'initial' in that specification.
inline-size - CSS: Cascading Style Sheets
syntax /* <length> values */ inline-size: 300px; inline-size: 25em; /* <percentage> values */ inline-size: 75%; /* keyword values */ inline-size: max-content; inline-size: min-content; inline-size: fit-content(20em); inline-size: auto; /* global values */ inline-size: inherit; inline-size: initial; inline-size: unset; if the writing mode is verti
cally oriented, the value of inline-size relates to the height of the element; otherwise, it relates to the width of the element.
linear-gradient() - CSS: Cascading Style Sheets
these somewhat complex definitions lead to an interesting effect sometimes
called magic corners: the corners nearest to the starting and ending points have the same color as their respective starting or ending points.
mask-border - CSS: Cascading Style Sheets
the source for the mask is a ".png" file of 90 by 90 pixels, with three diamonds going verti
cally and horizontally: html <div id="bitmap">this element is surrounded by a bitmap-based mask border!
min-block-size - CSS: Cascading Style Sheets
syntax /* <length> values */ min-block-size: 100px; min-block-size: 5em; /* <percentage> values */ min-block-size: 10%; /* keyword values */ min-block-size: max-content; min-block-size: min-content; min-block-size: fit-content(20em); /* global values */ min-block-size: inherit; min-block-size: initial; min-block-size: unset; if the writing mode is verti
cally oriented, the value of min-block-size relates to the minimum width of the element; otherwise, it relates to the minimum height of the element.
min-inline-size - CSS: Cascading Style Sheets
syntax /* <length> values */ min-inline-size: 100px; min-inline-size: 5em; /* <percentage> values */ min-inline-size: 10%; /* keyword values */ min-inline-size: max-content; min-inline-size: min-content; min-inline-size: fit-content(20em); /* global values */ min-inline-size: inherit; min-inline-size: initial; min-inline-size: unset; if the writing mode is verti
cally oriented, the value of min-inline-size relates to the minimum height of the element; otherwise, it relates to the minimum width of the element.
offset-distance - CSS: Cascading Style Sheets
inition initial value0applies totransformable elementsinheritednopercentagesrefer to the total path lengthcomputed valuefor <length> the absolute value, otherwise a percentageanimation typea length, percentage or calc(); formal syntax <length-percentage>where <length-percentage> = <length> | <percentage> examples using offset-distance in an animation the motion aspect in css motion path typi
cally comes from animating the offset-distance property.
outline-style - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | <'border-style'> examples setting outline style to auto the auto value indicates a custom outline style — typi
cally a style [that] is either a user interface default for the platform, or perhaps a style that is richer than can be described in detail in css, e.g.
overflow-anchor - CSS: Cascading Style Sheets
therefore, changing the value of this property is typi
cally only required if you are experiencing problems with scroll anchoring in a document or part of a document and need to turn the behavior off.
overflow - CSS: Cascading Style Sheets
the content can be scrolled programmati
cally (for example, by setting the value of a property such as offsetleft), so the element is still a scroll container.
overscroll-behavior-y - CSS: Cascading Style Sheets
formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto examples preventing an underlying element from scrolling verti
cally .messages { height: 220px; overflow: auto; overscroll-behavior-y: contain; } see overscroll-behavior for a full example and explanation.
overscroll-behavior - CSS: Cascading Style Sheets
you may also have noticed that when you have a dialog box with scrolling content on top of a page of scrolling content, once the dialog box's scroll boundary is reached, the underlying page will then start to scroll — this is
called scroll chaining.
position - CSS: Cascading Style Sheets
except for the case just described (of absolutely positioned elements filling the available space): if both top and bottom are specified (techni
cally, not auto), top wins.
text-decoration-color - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples <p>this paragraph has <s>some erroneous text</s> inside it that i want to
call attention to.</p> p { text-decoration-line: underline; text-decoration-color: cyan; } s { text-decoration-line: line-through; text-decoration-color: red; text-decoration-style: wavy; } specifications specification status comment css text decoration module level 3the definition of 'text-decoration-color' in that specification.
text-rendering - CSS: Cascading Style Sheets
formal definition initial valueautoapplies totext elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | optimizespeed | optimizelegibility | geometricprecision examples automatic application of optimizelegibility this demonstrates how optimizelegibility is used by browsers automati
cally when the font-size is smaller than 20px.
text-transform - CSS: Cascading Style Sheets
full-size-kana generally used for <ruby> annotation text, the keyword converts all small kana characters to the equivalent full-size kana, to compensate for legibility issues at the small font sizes typi
cally used in ruby.
transition-property - CSS: Cascading Style Sheets
syntax /* keyword values */ transition-property: none; transition-property: all; /* <custom-ident> values */ transition-property: test_05; transition-property: -specific; transition-property: sliding-verti
cally; /* multiple values */ transition-property: test1, animation4; transition-property: all, height, color; transition-property: all, -moz-specific, sliding; /* global values */ transition-property: inherit; transition-property: initial; transition-property: unset; values none no properties will transition.
user-select - CSS: Cascading Style Sheets
all the content of the element shall be selected atomi
cally: if a selection would contain part of the element, then the selection must contain the entire element including all its descendants.
var() - CSS: Cascading Style Sheets
the var() css function can be used to insert the value of a custom property (sometimes
called a "css variable") instead of any part of a value of another property.
CSS: Cascading Style Sheets
instead of versioning the css specification, w3c now periodi
cally takes a snapshot of the latest stable state of the css specification.
EXSLT
exslt modules to use an exslt function, you need to declare the namespace the function is in, and then use the appropriate prefix when
calling the function.
Guide to Web APIs - Developer guides
the web includes a wide array of apis that can be used from javascript to build increasingly more powerful and capable applications, running either on the web, lo
cally, or through technology such as node.js, on a server.
Writing Web Audio API code that works in every browser - Developer guides
if it's using, for example, oscillatornode, you will have to wait until it is supported, or maybe, if you're really eager, hack in some replacement using scriptprocessornode, which allows you to write a node with
callbacks that get
called periodi
cally, so that your javascript code generates or processes audio.
Block formatting context - Developer guides
formatting contexts affect layout, but typi
cally, 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.
Mutation events - Developer guides
amechanged domcharacterdatamodified 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 = und...
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
</canvas> javascript then in the javascript code,
call htmlcanvaselement.getcontext() to get a drawing context and start drawing onto the canvas: const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); result accessibility concerns alternative content the <canvas> element on its own is just a bitmap and does not provide information about any drawn objects.
<input type="button"> - HTML: Hypertext Markup Language
<input> elements of type button are rendered as simple push buttons, which can be programmed to control custom functionality anywhere on a webpage as required when assigned an event handler function (typi
cally for the click event).
data-* - HTML: Hypertext Markup Language
the data-* global attributes form a class of attributes
called custom data attributes, that allow proprietary information to be exchanged between the html and its dom representation by scripts.
dir - HTML: Hypertext Markup Language
as the directionality of the text is semanti
cally related to its content and not to its presentation, it is recommended that web developers use this attribute instead of the related css properties when possible.
is - HTML: Hypertext Markup Language
// create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always
call super first in constructor super(); // constructor contents ommitted for brevity ...
title - HTML: Hypertext Markup Language
some typical uses: labeling <iframe> elements for assistive technology providing a programmati
cally associated label for an <input> element as a fallback for a real <label> labeling controls in data tables additional semantics are attached to the title attributes of the <link>, <abbr>, <input>, and <menuitem> elements.
HTTP authentication - HTTP
the .htaccess file typi
cally looks like this: authtype basic authname "access to the staging site" authuserfile /path/to/.htpasswd require valid-user the .htaccess file references a .htpasswd file in which each line consists of a username and a password separated by a colon (:).
ETag - HTTP
weak etag values of two representations of the same resources might be semanti
cally equivalent, but not byte-for-byte identical.
Feature-Policy: geolocation - HTTP
when this policy is enabled,
calls to getcurrentposition() and watchposition() will cause those functions'
callbacks to be invoked with a positionerror code of permission_denied.
Feature-Policy - HTTP
when this policy is disabled,
calls to getcurrentposition() and watchposition() will cause those functions'
callbacks to be invoked with a positionerror code of permission_denied.
Forwarded - HTTP
proto=<http|https> indicates which protocol was used to make the request (typi
cally "http" or "https").
If-Match - HTTP
that they represent the resource semanti
cally, but not byte-for-byte.
Link - HTTP
it is semanti
cally equivalent to the html <link> element.
Location - HTTP
he 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 basi
cally don't know).
Server-Timing - HTTP
performanceservertiming interface in addition to having server-timing header metrics appear in the developer tools of the browser, the performanceservertiming interface enables tools to automati
cally collect and process metrics from javascript.
SameSite cookies - HTTP
the warning appears because the samesite policy for a cookie has not specified explicitly: set-cookie: flavor=choco while you could rely on modern browsers to apply samesite=lax automati
cally, you should rather specify it explicitly to clearly communicate your intent which samesite policy applies to your cookie.
TE - HTTP
(you could informally
call it accept-transfer-encoding, which would be more intuitive).
Trailer - HTTP
the trailer response header allows the sender to include additional fields at the end of chunked messages in order to supply metadata that might be dynami
cally generated while the message body is sent, such as a message integrity check, digital signature, or post-processing status.
WWW-Authenticate - HTTP
examples typi
cally, a server response contains a www-authenticate header that looks like these: www-authenticate: basic www-authenticate: basic realm="access to the staging site", charset="utf-8" see also http authentication for examples on how to configure apache or nginx servers to password protect your site with http basic authentication.
Warning - HTTP
113 heuristic expiration sent if a cache heuristi
cally chose a freshness lifetime greater than 24 hours and the response's age is greater than 24 hours.
PUT - HTTP
the difference between put and post is that put is idempotent:
calling it once or several times successively has the same effect (that is no side effect), whereas successive identical post requests may have additional effects, akin to placing an order several times.
Protocol upgrade mechanism - HTTP
in essence, then, this key simply confirms that "yes, i really mean to open a websocket connection." this header is automati
cally added by clients that choose to use it; it cannot be added using the xmlhttprequest.setrequestheader() method.
404 Not Found - HTTP
links that lead to a 404 page are often
called broken or dead links and can be subject to link rot.
416 Range Not Satisfiable - HTTP
the most likely reason is that the document doesn't contain such ranges, or that the range header value, though syntacti
cally correct, doesn't make sense.
CSS Houdini
worklets are conceptually similar to web workers, and are
called by and extend the rendering engine.
Enumerability and ownership of properties - JavaScript
rable); // or could use unfiltered for..in }, getownandprototypenonenumerables: function(obj) { return this._getpropertynames(obj, true, true, this._notenumerable); }, getownandprototypeenumerablesandnonenumerables: function(obj) { return this._getpropertynames(obj, true, true, this._enumerableandnotenumerable); }, // private static property checker
callbacks _enumerable: function(obj, prop) { return obj.propertyisenumerable(prop); }, _notenumerable: function(obj, prop) { return !obj.propertyisenumerable(prop); }, _enumerableandnotenumerable: function(obj, prop) { return true; }, // inspired by http://stackoverflow.com/a/8024294/271577 _getpropertynames: function getallpropertynames(obj, ite...
JavaScript Guide - JavaScript
script tools hello world grammar and types basic syntax & comments declarations variable scope variable hoisting data structures and types literals control flow and error handling if...else switch try/catch/throw error objects loops and iteration for while do...while break/continue for..in for..of functions defining functions
calling functions function scope closures arguments & parameters arrow functions expressions and operators assignment & comparisons arithmetic operators bitwise & logical operators conditional (ternary) operator numbers and dates number literals number object math object date object text formatting string literals string object template literals inter...
The legacy Iterator protocol - JavaScript
difference between legacy and es2015 iterator protocols the value was returned directly as a return value of
calls to next, instead of the value property of a placeholder object iteration termination was expressed by throwing a stopiteration object.
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
lelowercase', 'normalize', 'tolocaleuppercase', 'localecompare', 'match', 'search', 'slice', 'replace', 'split', 'substr', 'concat', 'localecompare' ], methodcount = methods.length, assignstringgeneric = function(methodname) { var method = string.prototype[methodname]; string[methodname] = function(arg1) { return method.apply(arg1, array.prototype.slice.
call(arguments, 1)); }; }; for (i = 0; i < methodcount; i++) { assignstringgeneric(methods[i]); } }()); ...
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
error: "use strict" not allowed in function with destructuring parameter 'use strict'; return a + b; }; this can be converted to the following expression: var sum = (function() { 'use strict'; return function sum([a, b]) { return a + b; }; })(); arrow function if an arrow function needs to access the this variable, you can use the arrow function as the enclosing function: var
callback = (...args) => { // syntaxerror: "use strict" not allowed in function with rest parameter 'use strict'; return this.run(args); }; this can be converted to the following expression: var
callback = (() => { 'use strict'; return (...args) => { return this.run(args); }; })(); ...
setter - JavaScript
the set syntax binds an object property to a function to be
called when there is an attempt to set that property.
Array.prototype.copyWithin() - JavaScript
return o; }, configurable: true, writable: true }); } examples using copywithin [1, 2, 3, 4, 5].copywithin(-2) // [1, 2, 3, 1, 2] [1, 2, 3, 4, 5].copywithin(0, 3) // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(0, 3, 4) // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(-2, -3, -1) // [1, 2, 3, 3, 4] [].copywithin.
call({length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, length: 5} // es2015 typed arrays are subclasses of array var 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 ecmascrip...
Array.prototype.fill() - JavaScript
// [4, 4, 4] [1, 2, 3].fill(4, 1) // [1, 4, 4] [1, 2, 3].fill(4, 1, 2) // [1, 4, 3] [1, 2, 3].fill(4, 1, 1) // [1, 2, 3] [1, 2, 3].fill(4, 3, 3) // [1, 2, 3] [1, 2, 3].fill(4, -3, -2) // [4, 2, 3] [1, 2, 3].fill(4, nan, nan) // [1, 2, 3] [1, 2, 3].fill(4, 3, 5) // [1, 2, 3] array(3).fill(4) // [4, 4, 4] [].fill.
call({ length: 3 }, 4) // {0: 4, 1: 4, 2: 4, length: 3} // a single object, referenced by each slot of the array: let arr = array(3).fill({}) // [{}, {}, {}] arr[0].hi = "hi" // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.fill' in that specification.
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.isarr...
Array.of() - JavaScript
if (!array.of) { array.of = function() { return array.prototype.slice.
call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } } examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] array.of(undefined); // [undefined] specifications specification ecmascript (ecma-262)the definition of 'array.of' in that specification.
BigInt - JavaScript
description a bigint is created by appending n to the end of an integer literal — 10n — or by
calling the function bigint().
Boolean.prototype.toString() - JavaScript
javascript
calls the tostring() method automati
cally when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation.
Date() constructor - JavaScript
if you simply
call the date object directly, such as now = date(), the returned value is a string rather than a date object.
Date.UTC() - JavaScript
utc() is a static method of date, so it's
called as date.utc() rather than as a method of a date instance.
Date.prototype.getTime() - JavaScript
// since month is zero based, birthday will be january 10, 1995 var birthday = new date(1994, 12, 10); var copy = new date(); copy.settime(birthday.gettime()); measuring execution time subtracting two subsequent gettime()
calls on newly generated date objects, give the time span between these two
calls.
Date - JavaScript
(this time is histori
cally known as greenwich mean time, as utc lies along the meridian that includes london—and nearby greenwich—in the united kingdom.) the user's device provides the local time.
Error.prototype.toSource() - JavaScript
examples using tosource
calling the tosource method of an error instance (including nativeerrors) will return a string containing the source code of the error.
Function.displayName - JavaScript
ining a displayname in function expressions you can define a function with a display name in a function expression: var object = { somemethod: function() {} }; object.somemethod.displayname = 'somemethod'; console.log(object.somemethod.displayname); // logs "somemethod" try { somemethod } catch(e) { console.log(e); } // referenceerror: somemethod is not defined changing displayname dynami
cally you can dynami
cally change the displayname of a function: var object = { // anonymous somemethod: function(value) { arguments.
callee.displayname = 'somemethod (' + value + ')'; } }; console.log(object.somemethod.displayname); // "undefined" object.somemethod('123') console.log(object.somemethod.displayname); // "somemethod (123)" specifications not part of any standard.
Function.name - JavaScript
ction names in classes you can use obj.constructor.name to check the "class" of an object (but be sure to read the warnings below): function foo() {} // es2015 syntax: class foo {} var fooinstance = new foo(); console.log(fooinstance.constructor.name); // logs "foo" warning: the script interpreter will set the built-in function.name property only if a function does not have an own property
called name (see section 9.2.11 of the ecmascript2015 language specification).
Generator.prototype.return() - JavaScript
function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } if return(value) is
called on a generator that is already in "completed" state, the generator will remain in "completed" state.
InternalError - JavaScript
function loop(x) { if (x >= 10) // "x >= 10" is the exit condition return; // do stuff loop(x + 1); // the recursive
call } loop(0); setting this condition to an extremely high value, won't work: function loop(x) { if (x >= 1000000000000) return; // do stuff loop(x + 1); } loop(0); // internalerror: too much recursion for more information, see internalerror: too much recursion.
Intl.PluralRules() constructor - JavaScript
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.
JSON - JavaScript
it can't be
called or constructed, and aside from its two method properties, it has no interesting functionality of its own.
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.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.
Math.cosh() - JavaScript
polyfill this can be emulated with the help of the math.exp() function: math.cosh = math.cosh || function(x) { return (math.exp(x) + math.exp(-x)) / 2; } or using only one
call to the math.exp() function: math.cosh = math.cosh || function(x) { var y = math.exp(x); return (y + 1 / y) / 2; }; examples using math.cosh() math.cosh(0); // 1 math.cosh(1); // 1.5430806348152437 math.cosh(-1); // 1.5430806348152437 specifications specification ecmascript (ecma-262)the definition of 'math.cosh' in that specification.
Math.hypot() - JavaScript
this function makes this calculation easier and faster; you simply
call math.hypot(v1, v2) , or math.hypot(v1, v2, v3, v4, ...).
Math.log1p() - JavaScript
when you calculate log(1 + x), you should get an answer very close to x, if x is small (that's why these are
called 'natural' logarithms).
Math.max() - JavaScript
getmaxofarray([1, 2, 3]) is equivalent to math.max(1, 2, 3), but you can use getmaxofarray() on programmati
cally constructed arrays.
Math.sinh() - JavaScript
polyfill this can be emulated with the help of the math.exp() function: math.sinh = math.sinh || function(x) { return (math.exp(x) - math.exp(-x)) / 2; } or using only one
call to the math.exp() function: math.sinh = math.sinh || function(x) { var y = math.exp(x); return (y - 1 / y) / 2; } examples using math.sinh() math.sinh(0); // 0 math.sinh(1); // 1.1752011936438014 specifications specification ecmascript (ecma-262)the definition of 'math.sinh' in that specification.
Math - JavaScript
you refer to the constant pi as math.pi and you
call the sine function as math.sin(x), where x is the method’s argument.
Number.MAX_VALUE - JavaScript
if the result is less than or equal to max_value, the func1 function is
called; otherwise, the func2 function is
called.
Number.MIN_VALUE - JavaScript
if the result is greater than or equal to min_value, the func1 function is
called; otherwise, the func2 function is
called.
Number.prototype.toExponential() - JavaScript
if you use the toexponential() method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method
call to prevent the dot from being interpreted as a decimal point.
Number.prototype.toFixed() - JavaScript
if the absolute value of numobj is greater or equal to 1e+21, this method simply
calls number.prototype.tostring() and returns a string in exponential notation.
Number.prototype.toLocaleString() - JavaScript
ter implementations, the requirement that illegal language tags are rejected with a rangeerror exception can be used: function tolocalestringsupportslocales() { var number = 0; try { number.tolocalestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } prior to es5.1, implementations were not required to throw a range error exception if tolocalestring is
called with arguments.
Object.assign() - JavaScript
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.prototype.hasownproperty.
call(nextsource, nextkey)) { to[nextkey] = nextsource[nextkey]; } } } } return to; }, writable: true, configurable: true }); } examples cloning an object const obj = { a: 1 }; const copy = object.assign({}, obj); console.log(copy); // { a: 1 } warning for deep clone for deep cloning, we need to use alternatives, because objec...
Object.prototype.hasOwnProperty() - JavaScript
not protect the property name hasownproperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasownproperty to get correct results: var foo = { hasownproperty: function() { return false; }, bar: 'here be dragons' }; foo.hasownproperty('bar'); // always returns false // use another object's hasownproperty // and
call it with 'this' set to foo ({}).hasownproperty.
call(foo, 'bar'); // true // it's also possible to use the hasownproperty property // from the object prototype for this purpose object.prototype.hasownproperty.
call(foo, 'bar'); // true note that in the last case there are no newly created objects.
Object.isFrozen() - JavaScript
object.defineproperty(accessor, 'food', { configurable: false }); object.isfrozen(accessor); // === true // but the easiest way for an object to be frozen // is if object.freeze has been
called on it.
Object.keys() - JavaScript
ums = [ '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]); } } } return resu...
Object.setPrototypeOf() - JavaScript
ochain : new ochain.constructor(ochain); for (var o1st = this.getprototypeof(o2nd); o1st !== object.prototype && o1st !== function.prototype; o1st = this.getprototypeof(o2nd) ) { o2nd = o1st; } if (oproto.constructor === string) { onewproto = function.prototype; oreturn = function.apply(null, array.prototype.slice.
call(arguments, 1)); this.setprototypeof(oreturn, olast); } this.setprototypeof(o2nd, onewproto); return oreturn; } usage first example: appending a chain to a prototype function mammal() { this.ismammal = 'yes'; } function mammalspecies(smammalspecies) { this.species = smammalspecies; } mammalspecies.prototype = new mammal(); mammalspecies.prototype.constructor = mammalspecies; ...
Promise.all() - JavaScript
it is typi
cally used when there are multiple asynchronous tasks that are dependent on one another to complete successfully, as it does not wait and will reject immediately upon any of the input promises rejecting.
Promise.allSettled() - JavaScript
it is typi
cally used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise.
Promise.race() - JavaScript
/ "two" // both fulfill, but p2 is faster }); var p3 = new promise(function(resolve, reject) { settimeout(() => resolve('three'), 100); }); var 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 s...
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.
handler.defineProperty() - JavaScript
const p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('
called: ' + prop); return true; } }); const desc = { configurable: true, enumerable: true, value: 10 }; object.defineproperty(p, 'a', desc); // "
called: a" when
calling object.defineproperty() or reflect.defineproperty(), the descriptor passed to defineproperty() trap has one restriction—only following properties are usable (non-standard properties will be ignored): enumerable configura...
handler.get() - JavaScript
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.
handler.getOwnPropertyDescriptor() - JavaScript
const p = new proxy({ a: 20}, { getownpropertydescriptor: function(target, prop) { console.log('
called: ' + prop); return { configurable: true, enumerable: true, value: 10 }; } }); console.log(object.getownpropertydescriptor(p, 'a').value); // "
called: a" // 10 the following code violates an invariant.
handler.has() - JavaScript
const p = new proxy({}, { has: function(target, prop) { console.log('
called: ' + prop); return true; } }); console.log('a' in p); // "
called: a" // true the following code violates an invariant.
handler.isExtensible() - JavaScript
const p = new proxy({}, { isextensible: function(target) { console.log('
called'); return true; } }); console.log(object.isextensible(p)); // "
called" // true the following code violates the invariant.
handler.ownKeys() - JavaScript
const 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.
handler.preventExtensions() - JavaScript
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.
RegExp.prototype.flags - JavaScript
property attributes of regexp.prototype.flags writable no enumerable no configurable yes description flags in the flags property are sorted alphabeti
cally (from left to right, e.g.
RegExp.$1-$9 - JavaScript
regexp.$1 : '0'; number; // "24" please note that any operation involving the usage of other regular expressions between a re.test(str)
call and the regexp.$n property, might have side effects, so that accessing these special properties should be done instantly, otherwise the result might be unexpected.
RegExp.prototype.sticky - JavaScript
perhaps because of the bug, the es2015 specification specifi
cally
calls out the fact that: when the y flag is used with a pattern, ^ always matches only at the beginning of the input, or (if multiline is true) at the beginning of a line.
String.prototype.big() - JavaScript
es string methods to change the size of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <fontsize=7>hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generi
cally, for example: document.getelementbyid('yourelemid').style.fontsize = '2em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.big' in that specification.
String.prototype.codePointAt() - JavaScript
https://mths.be/codepointat v0.2.0 by @mathias */ if (!string.prototype.codepointat) { (function() { 'use strict'; // needed to support `apply`/`
call` with `undefined`/`null` var defineproperty = (function() { // ie 8 only supports `object.defineproperty` on dom elements try { var object = {}; var $defineproperty = object.defineproperty; var result = $defineproperty(object, object, object) && $defineproperty; } catch(error) {} return result; }()); var codepointat = function(position) ...
String.prototype.fontcolor() - JavaScript
console.log(worldstring.fontcolor('red') + ' is red in this line'); // '<font color="red">hello, world</font> is red in this line' console.log(worldstring.fontcolor('ff00') + ' is red in hexadecimal in this line'); // '<font color="ff00">hello, world</font> is red in hexadecimal in this line' with the element.style object you can get the element's style attribute and manipulate it more generi
cally, for example: document.getelementbyid('yourelemid').style.color = 'red'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fontcolor' in that specification.
String.prototype.fontsize() - JavaScript
string methods to change the size of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generi
cally, for example: document.getelementbyid('yourelemid').style.fontsize = '0.7em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fontsize' in that specification.
String.fromCodePoint() - JavaScript
because fromcodepoint() is a static method of string, you must
call it as string.fromcodepoint(), rather than as a method of a string object you created.
String.prototype.localeCompare() - JavaScript
examples using localecompare() // the letter "a" is before "c" yielding a negative value 'a'.localecompare('c'); // -2 or -1 (or some other negative value) // alphabeti
cally the word "check" comes after "against" yielding a positive value 'check'.localecompare('against'); // 2 or 1 (or some other positive value) // "a" and "a" are equivalent yielding a neutral value of zero 'a'.localecompare('a'); // 0 sort an array localecompare() enables case-insensitive sorting for an array.
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.
String.prototype.small() - JavaScript
string methods to change the size of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generi
cally, for example: document.getelementbyid('yourelemid').style.fontsize = '0.7em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.small' in that specification.
String.prototype.substr() - JavaScript
ou can use the following code: // only run when the substr() function is broken if ('ab'.substr(-1) != 'b') { /** * get the substring of a string * @param {integer} start where to start the substring * @param {integer} length how many characters to return * @return {string} */ string.prototype.substr = function(substr) { return function(start, length) { //
call the original method return substr.
call(this, // did we get a negative start, calculate how much it is from the beginning of the string // adjust the start parameter for negative value start < 0 ?
Symbol.asyncIterator - JavaScript
yield "iteration!"; } }; (async () => { for await (const x of myasynciterable) { console.log(x); // expected output: // "hello" // "async" // "iteration!" } })(); when creating an api, remember that async iterables are designed to represent something iterable — like a stream of data or a list —, not to completely replace
callbacks and events in most situations.
Symbol.iterator - JavaScript
description whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is
called with no arguments, and the returned iterator is used to obtain the values to be iterated.
Symbol.prototype.toString() - JavaScript
no string concatenation while you can
call tostring() on symbols, you cannot use string concatenation with them: symbol('foo') + 'bar' // typeerror: can't convert symbol to string examples using tostring symbol('desc').tostring() // "symbol(desc)" // well-known symbols symbol.iterator.tostring() // "symbol(symbol.iterator) // global symbols symbol.for('foo').tostring() // "symbol(foo)" specifications specific...
Symbol - JavaScript
the "safer" string(sym) conversion works like a
call to symbol.prototype.tostring() with symbols, but note that new string(sym) will throw.
SyntaxError - JavaScript
the syntaxerror object represents an error when trying to interpret syntacti
cally invalid code.
TypeError() constructor - JavaScript
the typeerror() constructor creates a new error when an operation could not be performed, typi
cally (but not exclusively) when a value is not of the expected type.
TypeError - JavaScript
the typeerror object represents an error when an operation could not be performed, typi
cally (but not exclusively) when a value is not of the expected type.
TypedArray.of() - JavaScript
hence, when working with proxy objects, it
calls handler.set to create new elements rather than handler.defineproperty.
TypedArray.prototype.slice() - JavaScript
if (!uint8array.prototype.slice) { object.defineproperty(uint8array.prototype, 'slice', { value: function (begin, end) { return new uint8array(array.prototype.slice.
call(this, begin, end)); } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable.
WebAssembly.Instance() constructor - JavaScript
examples 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.expor...
WebAssembly.compileStreaming() - JavaScript
because the compilestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch()
call, and it will pass the response into the function when it fulfills.
WebAssembly.instantiateStreaming() - JavaScript
because the instantiatestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch()
call, and it will pass the response into the function when it fulfills.
WebAssembly - JavaScript
because the instantiatestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch()
call, and it will pass the response into the function when it fulfills.
encodeURIComponent() - JavaScript
// i.e., %27 %28 %29 %2a (note that valid encoding of "*" is %2a // which necessitates
calling touppercase() to properly encode) // the following are not required for percent-encoding per rfc5987, // so we can allow for a little better readability over the wire: |`^ replace(/%(7c|60|5e)/g, (str, hex) => string.fromcharcode(parseint(hex, 16))); } specifications specification ecmascript (ecma-262)the definition of 'encodeuricomponent' in that specification.
globalThis - JavaScript
property attributes of globalthis writable yes enumerable no configurable yes description histori
cally, accessing the global object has required different syntax in different javascript environments.
isNaN() - JavaScript
you can use this, for example, to test whether an argument to a function is arithmeti
cally processable (usable "like" a number), or if it's not and you have to provide a default value or something else.
undefined - JavaScript
javascript is a stati
cally scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context.
Logical AND assignment (&&=) - JavaScript
escription short-circuit evaluation the logical and operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule: (some falsy expression) && expr is short-circuit evaluated to the falsy expression; short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function
call, the
calling never takes place).
Logical nullish assignment (??=) - JavaScript
short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function
call, the
calling never takes place).
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 ?.
delete operator - JavaScript
the javascript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automati
cally.
void operator - JavaScript
this can cause unintended side effects by returning the result of a function
call that previously returned nothing.
yield* - JavaScript
examples delegating to another generator in following code, values yielded by g1() are returned from next()
calls just like those which are yielded by g2().
block - JavaScript
description the block statement is often
called compound statement in other languages.
class - JavaScript
note that super(), used in the constructor, can only be used in constructors, and must be
called before the this keyword can be used.
debugger - JavaScript
syntax debugger; examples using the debugger statement the following example shows code where a debugger statement has been inserted, to invoke a debugger (if one exists) when the function is
called.
for...in - JavaScript
it may be most practi
cally used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise).
switch - JavaScript
this shows you that it will traverse in the order that you put the case clauses, and it does not have to be numeri
cally sequential.
try...catch - JavaScript
if any statement within the try-block (or in a function
called from within the try-block) throws an exception, control is immediately shifted to the catch-block.
JavaScript
on june 17, 2015, ecma international published the sixth major version of ecmascript, which is officially
called ecmascript 2015, and was initially referred to as ecmascript 6 or es6.
MathML attribute reference - MathML
symmetric <mo> if stretchy is true, this attribute specifies whether the operator should be verti
cally symmetric around the imaginary math axis (centered fraction line).
<mi> - MathML
that is, although the names suggest the typographic style for the class, semanti
cally, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography.
<mlabeledtr> - MathML
the first child is the label whereas all other children are representing row contents and are treated identi
cally to children of <mtr> elements.
<mn> - MathML
that is, although the names suggest the typographic style for the class, semanti
cally, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography.
<ms> - MathML
that is, although the names suggest the typographic style for the class, semanti
cally, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography.
<mtable> - MathML
possible values are: axis (default): the vertical center of the table aligns on the environment's axis (typi
cally the minus sign).
<mtext> - MathML
that is, although the names suggest the typographic style for the class, semanti
cally, items with the same class are treated "the same" within an expression, which might or might not involve displaying them with the named typography.
Proving the Pythagorean theorem - MathML
proof: we can prove the theorem algebrai
cally by showing that the area of the big square equals the area of the inner square (hypotenuse squared) plus the area of the four triangles: ( a + b ) 2 = c 2 + 4 ⋅ ( 1 2 a b ) a 2 + 2 a b + b 2 = c 2 + 2 a ba 2 + b 2 = c 2 ...
MathML documentation index - MathML
the first child is the label whereas all other children are representing row contents and are treated identi
cally to children of <mtr> elements.
Web media technologies
media capture and streams api a reference for the api which makes it possible to stream, record, and manipulate media both lo
cally and across a network.
Lazy loading - Web Performance
lazy loading can occur on different moments in the application, but it typi
cally happens on some user interactions such as scrolling and navigation.
Progressive loading - Progressive web apps (PWAs)
placeholder image instead of having all the screenshots of games referenced in <img> element src attributes, which will force the browser to download them automati
cally, we can do it selectively via javascript.
Mobile first - Progressive web apps (PWAs)
i installed the volo automation tool by running the following on the command line sudo npm install -g volo (you'll also need to get node.js too if you don't already have it) i then created my sample project using volo create myapp mozilla/mortar-app-stub this creates a sample project inside a directory
called myapp.
Structural overview of progressive web apps - Progressive web apps (PWAs)
t).then(function(response) { return caches.open(cachename).then(function(cache) { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); return response; }); }); }) ); }); auxiliary javascript file: games.js the games data for this app example is provided in a javascript source file
called games.js.
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
</filter> </svg> the five filters are applied using the following css: p.target { filter:url(#f3); } p.target:hover { filter:url(#f5); } b.target { filter:url(#f1); } b.target:hover { filter:url(#f4); } pre.target { filter:url(#f2); } pre.target:hover { filter:url(#f3); } view this example live example: blurred text in order to blur text, webkit based browsers have a (prefixed) css filter
called blur (see also css filter).
href - SVG: Scalable Vector Graphics
specifi
cally, timeevents are dispatched and the animation element can be used as syncbase in an identical fashion to when the url refers to a valid target element.
rotate - SVG: Scalable Vector Graphics
usage notes value auto | auto-reverse | <number> default value 0 animatable no the auto and auto-reverse values allow the animated element's rotation to change dynami
cally as it travels along the path.
stitchTiles - SVG: Scalable Vector Graphics
stitch this value indicates that the user agent will automati
cally adjust the x and y values of the base frequency such that the <feturbulence> node’s width and height (i.e., the width and height of the current subregion) contain an integral number of the tile width and height for the first octave.
systemLanguage - SVG: Scalable Vector Graphics
for example, content that is presented simultaneously in the original maori and english versions, would
call for: <text systemlanguage="mi, en"><!-- content goes here --></text> however, just because multiple languages are present within the object on which the systemlanguage test attribute is placed, this does not mean that it is intended for multiple linguistic audiences.
xlink:arcrole - SVG: Scalable Vector Graphics
for example, a resource might generi
cally represent a "person," but in the context of a particular arc it might have the role of "mother" and in the context of a different arc it might have the role of "daughter." twentytwo elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <color-profile>, <cursor>, <feimage>, <filter>, <font-face-uri>, <glyphref>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, <tref>, <use> usage notes valu...
Basic Transformations - SVG: Scalable Vector Graphics
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100"> <svg width="100" height="100" viewbox="0 0 50 50"> <rect width="50" height="50" /> </svg> </svg> the example above has basi
cally the same effect as the one above, namely that the rect will be twice as large as specified.
SVG In HTML Introduction - SVG: Scalable Vector Graphics
rule makes an error message appear.) this approach has the following points in its favor: we have taken a regular html form that could have been part of an existing web site, and added an attractive, interactive background the approach is backwards compatible to browsers that do not support svg; simply, no background appears in them it's very simple and performs very well the picture dynami
cally sizes itself to the required size in an intelligent way we can have declarative style rules applying to both html and svg the same script manipulates both html and svg the document is entirely standards-based to add a linked image with dom methods to an embedded svg element, one has to use setattributens to set href.
SVG: Scalable Vector Graphics
as such, it's a text-based, open web standard for describing images that can be rendered cleanly at any size and are designed specifi
cally to work well with other web standards including css, dom, javascript, and smil.
Certificate Transparency - Web security
newly issued certificates are 'logged' to publicly run, often independent ct logs which maintain an append-only, cryptographi
cally assured record of issued tls certificates.
How to turn off form autocompletion - Web security
note that the wcag 2.1 success criterion 1.3.5: identify input purpose does not require that autocomplete/autofill actually work - merely that form fields that relate to specific personal user information are programmati
cally identified.
Securing your site - Web security
user information security how to turn off form autocompletion form fields support autocompletion in gecko; that is, their values can be remembered and automati
cally brought back the next time the user visits your site.
Subdomain takeovers - Web security
typi
cally, this happens when the subdomain has a canonical name (cname) in the domain name system (dns), but no host is providing content for it.
Using shadow DOM - Web Components
to begin with, in our javascript file we define a class
called popupinfo, which extends htmlelement: class popupinfo extends htmlelement { constructor() { // always
call super first in constructor super(); // write element functionality in here ...
document - XPath
if the uri argument is a node-set, and the second argument is present, each node in the node-set will be evaluated as a separate uri, and the returned node-set will be as if the document function has been
called multiple times (each time with the same second argument just as given in the function
call) and the resulting node-sets had been concatenated into a single node-set.
number - XPath
a node-set is first converted to a string as if by a
call to the string() function and then converted in the same way as a string argument.
system-property - XPath
notes xsl:version, a number giving the version of xslt implemented by the processor; for xslt processors implementing the version of xslt specified by this document, this is the number 1.0 xsl:vendor, a string identifying the vendor of the xslt processor xsl:vendor-url, a string containing a url identifying the vendor of the xslt processor; typi
cally this is the host page (home page) of the vendor's web site.
XPath snippets - XPath
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 i...