Search completed in 1.09 seconds.
JSException - Archive of obsolete content
summary the public class js
exception extends runtime
exception java.lang.object | +----java.lang.throwable | +----java.lang.
exception | +----java.lang.runtime
exception | +----netscape.javascript.js
exception description js
exception is an
exception which is thrown when javascript code returns an error. constructor summary the netscape.javascript.js
exception class has the following constructors: js
exception deprecated constructors optionally let you specify a detail message and other information. method summary the netscape.javascript.js
exception class has the following methods: getwrapped
exception instance method getwrapped
exception. getwrap...
...avascript code returns an error. constructor summary the netscape.javascript.js
exception class has the following constructors: js
exception deprecated constructors optionally let you specify a detail message and other information. method summary the netscape.javascript.js
exception class has the following methods: getwrapped
exception instance method getwrapped
exception. getwrapped
exceptiontype instance method getwrapped
exceptiontype returns the int mapping of the type of the wrapped
exception object. ...
... let you specify a detail message and other information. method summary the netscape.javascript.js
exception class has the following methods: getwrapped
exception instance method getwrapped
exception. getwrapped
exceptiontype instance method getwrapped
exceptiontype returns the int mapping of the type of the wrapped
exception object. backward compatibility javascript 1.1 through 1.3 js
exception had three public constructors which optionally took a string argument, specifying the detail message or other information for the
exception. the getwrapped
exception method was not available. js
exception constructors, deprecated in javascript 1.4, constructs a js
exception object with an optional detail message. declaration 1. public js
exception() 2. public js
exception(string s) 3. public jsex...
...And 12 more matches
Exception logging in JavaScript - Archive of obsolete content
in versions of firefox prior to firefox 3, all javascript
exceptions were always logged into the error console if they remained unhandled at the time execution returned back into c++ code. 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. this had the unintended consequence of logging "expected" errors at length into the console. javascript code is sometimes designed to throw
exceptions to report a result condition back to the c++ caller. these might be perfectly normal circumstances, but the
exceptions were dutifully logged nonetheless. ...
..., that
exception would be logged to the console before control was returned to the c++ caller. this had the unintended consequence of logging "expected" errors at length into the console. javascript code is sometimes designed to throw
exceptions to report a result condition back to the c++ caller. these might be perfectly normal circumstances, but the
exceptions were dutifully logged nonetheless.
exception reporting in firefox 3 firefox 3 improves reporting of unhandled
exceptions by establishing a set of rules that determines whether or not an
exception is worth reporting: any methods on interfaces annotated with the [function] attribute in idl (see, for example, nsidomeventlistener) that throw
exceptions always report those
exceptions into the error console. ...
... the ns_nointerface error is never reported when returned by a javascript object's queryinterface() method on the nsisupports interface. ...
...And 6 more matches
JS_IsExceptionPending
determine whether an
exception is pending in the js engine. syntax bool js_is
exceptionpending(jscontext *cx); name type description cx jscontext * pointer to a js context to check for pending
exceptions. description js_is
exceptionpending returns true if an
exception has been thrown in the context cx and the
exception has not yet been caught or cleared. otherwise, it returns false this can be used from jsnative functions which call js code to determine if the called js code threw an
exception or not. example /* jsapi */ bool pending; js::rootedvalue
exception(cx); /* if an
exception is pending, save and clear it. ...
...turns true if an
exception has been thrown in the context cx and the
exception has not yet been caught or cleared. otherwise, it returns false this can be used from jsnative functions which call js code to determine if the called js code threw an
exception or not. example /* jsapi */ bool pending; js::rootedvalue
exception(cx); /* if an
exception is pending, save and clear it. */ pending = js_is
exceptionpending(cx); if (pending) { if (!js_getpending
exception(cx, &
exception)) return false; js_clearpending
exception(cx); } /* ... code that might throw js
exception ... */ if (js_is
exceptionpending(cx)) { /* ... react to
exception thrown in this block ... */ js_clearpending
exception(cx); } /* restore the original
exception. ...
...js_is
exceptionpending(cx); if (pending) { if (!js_getpending
exception(cx, &
exception)) return false; js_clearpending
exception(cx); } /* ... code that might throw js
exception ... */ if (js_is
exceptionpending(cx)) { /* ... react to
exception thrown in this block ... */ js_clearpending
exception(cx); } /* restore the original
exception. ...
...And 6 more matches
JS_GetPendingException
otherwise, it returns false, and the value left in *vp is undefined. see examples in the jsapi phrasebook. ...
...otherwise, it returns false, and the value left in *vp is undefined. see examples in the jsapi phrasebook. ...
...tax bool js_getpending
exception(jscontext *cx, js::mutablehandlevalue vp); name type description cx jscontext * pointer to the js context in which the
exception was thrown. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. vp js::mutablehandlevalue out parameter. on success, *vp receives the current pending
exception. description if an
exception has been thrown in the context cx, and it has not yet been caught or cleared, js_getpending
exception stores the
exception object in *vp and returns true. otherwise, it returns false, and the value left in *vp is undefined. see examples in the jsapi phrasebook. ...
...And 5 more matches
nsIXPCException
js/src/xpconnect/idl/xpc
exception.idlscriptable these
exception objects are the preferred types of
exceptions when implementing xpcom interfaces in javascript. ...
... js/src/xpconnect/idl/xpc
exception.idlscriptable these
exception objects are the preferred types of
exceptions when implementing xpcom interfaces in javascript. ...
.../idl/xpc
exception.idlscriptable these
exception objects are the preferred types of
exceptions when implementing xpcom interfaces in javascript. ...
...And 5 more matches
JS_ClearPendingException
clear the currently pending
exception in a context. syntax void js_clearpending
exception(jscontext *cx); name type description cx jscontext * the context in which the
exception was thrown. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_clearpending
exception cancels the currently pending
exception in cx, if any. (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_clearpending
exception to catch the
exception; or return false to allow the
exception to propagate to the caller. note that a jsapi failure does not necessarily indicate that an
exception is pending. many jsa...
...et been caught or cleared.) when any jsapi call fails with an
exception, the caller must either use js_clearpending
exception to catch the
exception; or return false to allow the
exception to propagate to the caller. note that a jsapi failure does not necessarily indicate that an
exception is pending. many jsapi functions can simply report an error and return false without building and throwing an
exception object. use js_is
exceptionpending or js_getpending
exception to check for a pending
exception. see examples in the jsapi phrasebook. ...
... to propagate to the caller. note that a jsapi failure does not necessarily indicate that an
exception is pending. many jsapi functions can simply report an error and return false without building and throwing an
exception object. use js_is
exceptionpending or js_getpending
exception to check for a pending
exception. see examples in the jsapi phrasebook. ...
...And 4 more matches
JS_SetPendingException
sets the current
exception being thrown within a context. syntax void js_setpending
exception(jscontext *cx, js::handlevalue v); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handlevalue value to throw as an
exception. description js_setpending
exception sets the current
exception being thrown within a context. if an
exception is already being thrown, it is replaced with the new one given. v is the new value to throw as an
exception. a native function or hook using this to throw an
exception must also return false to ensure the
exception is thrown. ...
... value to throw as an
exception. description js_setpending
exception sets the current
exception being thrown within a context. if an
exception is already being thrown, it is replaced with the new one given. v is the new value to throw as an
exception. a native function or hook using this to throw an
exception must also return false to ensure the
exception is thrown. each jscontext's pending-
exception field is a gc root. that is, garbage collection never collects a pending
exception. see examples in the jsapi phrasebook. ...
...t is replaced with the new one given. v is the new value to throw as an
exception. a native function or hook using this to throw an
exception must also return false to ensure the
exception is thrown. each jscontext's pending-
exception field is a gc root. that is, garbage collection never collects a pending
exception. see examples in the jsapi phrasebook. ...
...And 4 more matches
Components.Exception
summary components.
exception is a javascript constructor to create nsixpc
exception objects. these
exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will. see also nsixpc
exception. ...
... summary components.
exception is a javascript constructor to create nsixpc
exception objects. these
exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will. see also nsixpc
exception. ...
... summary components.
exception is a javascript constructor to create nsixpc
exception objects. these
exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will. see also nsixpc
exception. ...
...And 4 more matches
JS_RestoreExceptionState
restores the
exception state from a js
exceptionstate object previously created using js_save
exceptionstate. syntax void js_restore
exceptionstate(jscontext *cx, js
exceptionstate *state); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. state js
exceptionstate * pointer to the js
exceptionstate object to restore
exception state from. description this function permits to restore any previously saved
exception state which was saved into a js
exceptionstate object created by the js_save
exceptionstate function. ...
...on. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. state js
exceptionstate * pointer to the js
exceptionstate object to restore
exception state from. description this function permits to restore any previously saved
exception state which was saved into a js
exceptionstate object created by the js_save
exceptionstate function. if any
exception was pending when js_save
exceptionstate was called, the same
exception will be set to pend for the current context. if no
exceptions were pending when calling js_save
exceptionstate, any pending
exception for the context will likewise be cleared. ...
... which was saved into a js
exceptionstate object created by the js_save
exceptionstate function. if any
exception was pending when js_save
exceptionstate was called, the same
exception will be set to pend for the current context. if no
exceptions were pending when calling js_save
exceptionstate, any pending
exception for the context will likewise be cleared. ...
...And 3 more matches
JS_SaveExceptionState
saves the
exception state from the specified context. syntax js
exceptionstate * js_save
exceptionstate(jscontext *cx); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description saves the current
exception state (that is, any pending
exception, or a cleared
exception state) associated with the specified context cx, and returns a js
exceptionstate object holding this state. that object may then be used to restore again the context using js_restore
exceptionstate, or discarded using js_drop
exceptionstate. either of those two functions frees any memory used by the js
exceptionstate. ...
...rrent
exception state (that is, any pending
exception, or a cleared
exception state) associated with the specified context cx, and returns a js
exceptionstate object holding this state. that object may then be used to restore again the context using js_restore
exceptionstate, or discarded using js_drop
exceptionstate. either of those two functions frees any memory used by the js
exceptionstate. the js
exceptionstate created by this function automatically roots any pending
exception object which needs to be protected from the gc. this function returns null if the engine was not built with support for
exceptions. ...
...js_restore
exceptionstate, or discarded using js_drop
exceptionstate. either of those two functions frees any memory used by the js
exceptionstate. the js
exceptionstate created by this function automatically roots any pending
exception object which needs to be protected from the gc. this function returns null if the engine was not built with support for
exceptions. ...
...And 3 more matches
JS::AutoSaveExceptionState
this article covers features introduced in spidermonkey 31 save and later restore the current
exception state of a given jscontext. syntax js::autosave
exceptionstate(jscontext *cx); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js::autosave
exceptionstate saves and later restores the current
exception state of a given jscontext. this is useful for implementing behavior in c++ that's like try/catch or try/finally in js. example // typical usage: bool ok = js::evaluate(cx, ...); autosave
exceptionstate savedexc(cx); ... cleanup that might re-enter js ... return ok; see also mxr id...
...scription js::autosave
exceptionstate saves and later restores the current
exception state of a given jscontext. this is useful for implementing behavior in c++ that's like try/catch or try/finally in js. example // typical usage: bool ok = js::evaluate(cx, ...); autosave
exceptionstate savedexc(cx); ... cleanup that might re-enter js ... ...
...
exceptionstate saves and later restores the current
exception state of a given jscontext. this is useful for implementing behavior in c++ that's like try/catch or try/finally in js. example // typical usage: bool ok = js::evaluate(cx, ...); autosave
exceptionstate savedexc(cx); ... cleanup that might re-enter js ... ...
...And 2 more matches
JSExceptionState
the fields of this structure are private/opaque. this is used to save and restore
exception states. syntax struct js
exceptionstate; description a js
exceptionstate object is returned by the js_save
exceptionstate function, and is passed to functions js_restore
exceptionstate and js_drop
exceptionstate. ...
... the fields of this structure are private/opaque. this is used to save and restore
exception states. syntax struct js
exceptionstate; description a js
exceptionstate object is returned by the js_save
exceptionstate function, and is passed to functions js_restore
exceptionstate and js_drop
exceptionstate. ...
... the fields of this structure are private/opaque. this is used to save and restore
exception states. syntax struct js
exceptionstate; description a js
exceptionstate object is returned by the js_save
exceptionstate function, and is passed to functions js_restore
exceptionstate and js_drop
exceptionstate. ...
...And 2 more matches
JS_DropExceptionState
destroys a js
exceptionstate object previously created using js_save
exceptionstate. syntax void js_drop
exceptionstate(jscontext *cx, js
exceptionstate *state); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. state js
exceptionstate * pointer to the js
exceptionstate object to destroy. description this function destroys the specified js
exceptionstate object, unrooting as necessary any attached
exception object and freeing the memory resources associated with the js
exceptionstate object. this object should previously have been created using js_save
exceptionstate. see also mxr id search for js_dropstate...
...s
exceptionstate * pointer to the js
exceptionstate object to destroy. description this function destroys the specified js
exceptionstate object, unrooting as necessary any attached
exception object and freeing the memory resources associated with the js
exceptionstate object. this object should previously have been created using js_save
exceptionstate. ...
...ate * pointer to the js
exceptionstate object to destroy. description this function destroys the specified js
exceptionstate object, unrooting as necessary any attached
exception object and freeing the memory resources associated with the js
exceptionstate object. this object should previously have been created using js_save
exceptionstate. ...
...And 2 more matches
DOMException - Web APIs
the dom
exception 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 basically how error conditions are described in web apis. each
exception has a name, which is a short "camelcase" style string identifying the error or abnormal condition. constructor dom
exception() returns a dom
exception object with a specified message and name. properties dom
exception.code read only returns a short that contains one of the error code constants, or 0 if none match. this field is used for historical reasons. new dom
exceptions don't use this anymore: they put this info in the dom
exception.name attribute. ...
... error names common error names are listed here. ...
... error names common error names are listed here. some apis define their own sets of names, so this is not necessarily a complete list. ...
...And 2 more matches
IDBDatabaseException - Web APIs
constants note: do not rely on the numeric values of the constants, which might change as the specifications continue to change. use the constant names instead. ...
... constants note: do not rely on the numeric values of the constants, which might change as the specifications continue to change. use the constant names instead. ...
... constants note: do not rely on the numeric values of the constants, which might change as the specifications continue to change. use the constant names instead. constant value description abort_err 8 a request was aborted, for example, through a call to idbtransaction.abort. ...
... browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Debug.setNonUserCodeExceptions - Archive of obsolete content
the debug.setnonusercode
exceptions property determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled.
exceptions can be classified as thrown, user-unhandled or unhandled. syntax debug.setnonusercode
exceptions [= bool]; remarks if this property is set to true within a given scope, the debugger can then choose whether to take some specified action on
exceptions thrown inside that scope: for instance, if the developer wishes to break on user-unhandled
exceptions. setting this property to false is the same as never having set the property. for more information on debugging, see the active script debugging overview. example the following code shows how to set this property. ...
... } })(); requirements supported in the following document modes: internet explorer 10 standards and internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
... } })(); requirements supported in the following document modes: internet explorer 10 standards and internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
JS_ReportPendingException
forward the current pending
exception in a given jscontext to the current jserrorreporter callback. syntax bool js_reportpending
exception(jscontext *cx); name type description cx jscontext * the context in which the
exception was thrown. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description if an
exception is pending in the context cx, js_reportpending
exception converts the
exception to a string and reports it to the current error reporter. on success, it clears the
exception as though by calling js_clearpending
exception and returns true. if no
exception is pending, or if a second error occurs while trying to report the first one, it returns false. ...
...if an
exception is pending in the context cx, js_reportpending
exception converts the
exception to a string and reports it to the current error reporter. on success, it clears the
exception as though by calling js_clearpending
exception and returns true. if no
exception is pending, or if a second error occurs while trying to report the first one, it returns false. this function can be used to catch
exceptions thrown from scripts and send them to the error reporter to be logged or ignored. note that certain jsapi functions automatically do this for uncaught
exceptions; see "automatic handling of uncaught
exceptions" in the jsapi user guide. ...
...econd error occurs while trying to report the first one, it returns false. this function can be used to catch
exceptions thrown from scripts and send them to the error reporter to be logged or ignored. ...
nsIException
inherits from: nsisupports last changed in gecko 1.7 method overview string tostring(); attributes attribute type description columnnumber pruint32 valid column numbers begin at 0. there is no unambiguous indicator for unknown. read only. data nsisupports arbitary data for the implementation. read only. filename string filename location. this is the location that caused the error, which may or may not be a source file location. for example, standard language errors would generally have the same location as their top stack entry. file parsers may put the location of the file they were parsing. ...
...lementation. read only. filename string filename location. this is the location that caused the error, which may or may not be a source file location. for example, standard language errors would generally have the same location as their top stack entry. file parsers may put the location of the file they were parsing. null indicates "no data" read only. inner nsi
exception an inner
exception that triggered this, if available. read only. linenumber pruint32 valid line numbers begin at '1'. '0' indicates unknown. read only. location nsistackframe a stack trace, if available. read only. message string a custom message set by the thrower. [binaryname(messagemoz)] read only. name string the name of the error...
...bers begin at '1'. '0' indicates unknown. read only. location nsistackframe a stack trace, if available. read only. message string a custom message set by the thrower. [binaryname(messagemoz)] read only. name string the name of the error code (a string representation of result) read only. result nsresult the nsresult associated with this
exception. read only. methods tostring() a generic formatter - make it suitable to print, etc. string tostring(); parameters none. return value a string suitable for output. ...
DOMException.name - Web APIs
specifications specification status comment web idlthe definition of 'name' in that specification. ...
... specifications specification status comment web idlthe definition of 'name' in that specification. ...
... specifications specification status comment web idlthe definition of 'name' in that specification. ...
Exception - MDN Web Docs Glossary: Definitions of Web-related terms
an
exception is a condition that interrupts normal code execution. in javascript syntax errors are a very common source of
exceptions. ...
... an
exception is a condition that interrupts normal code execution. in javascript syntax errors are a very common source of
exceptions. ...
JS_ErrorFromException
get or create jserrorreport from an
exception object. syntax jserrorreport * js_errorfrom
exception(jscontext *cx, js::handleobject obj); name type description cx jscontext * pointer to a js context whose errors should be reported via your function. other contexts in the same runtime can have their own error reporting functions. obj js::handleobject an
exception object. description if obj is an
exception object, the
exception will have (or be able to lazily create) an error report struct, and js_errorfrom
exception will return the address of that struct. otherwise, it returns nullptr. the lifetime of the error report struct that might be returned is the same as the lifetime of the
exception object. see also mxr id search for js_errorfrom...
...eption object. description if obj is an
exception object, the
exception will have (or be able to lazily create) an error report struct, and js_errorfrom
exception will return the address of that struct. otherwise, it returns nullptr. the lifetime of the error report struct that might be returned is the same as the lifetime of the
exception object. ...
DOMException() - Web APIs
the dom
exception() constructor returns a dom
exception object with a specified message and name. syntax var dom
exception = new dom
exception(); var dom
exception = new dom
exception(message); var dom
exception = new dom
exception(message, name); parameters message optional a description of the
exception. if not present, the empty string '' is used. name optional returns a domstring that contains one of the strings associated with an error constant. return value dom
exception a newly created dom
exception object. example tbd specifications specification status comment web idlthe definition of 'dom
exception()' in that specification. candidate recommendation adds the constructor for the dom
exception class. browser compatibility the compatibility t...
...n class. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
FileException - Web APIs
basic concepts synchronous apis do not have error callbacks, which makes it difficult to catch errors. the added complexity of using webworkers with this api makes debugging even more challenging. to simplify things a bit, wrap your worker code in a try/catch. when errors occur, forward them to the main app using postmessage() as in the following: function onerror(e) { postmessage('error:' + e.tostring()); } try { //error is thrown if "log.txt" already exists. ...
...eentry. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
XPathException - Web APIs
constants constant value description invalid_expression_err 51 if the expression has a syntax error or otherwise is not a legal expression according to the rules of the specific xpathevaluator or contains specialized extension functions or variables not supported by this implementation. type_err 52 if the expression cannot be converted to return the specified type. ...
... recommendation initial definition ...
NPN_SetException - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary a plugin can call this function to indicate that a call to one of the plugin's npobjects generated an error. syntax #include <npruntime.h> void npn_set
exception(npobject *npobj, const nputf8 *message); parameters the function has the following parameters: <tt>npobj</tt> the object on which the
exception occurred. <tt>message</tt> a utf-8 string describing the error that occurred. returns nothing. ...
nsIDOMFileException
last changed in gecko 1.9 (firefox 3) attributes attribute type description code unsigned short the error code describing the error condition that took place; see the constants list for details. constants constant value description not_found_err 0 the specified file wasn't found. not_readable_err 1 the specified file wasn't readable. ...
nsIDOMXPathException
inherits from: nsisupports last changed in gecko 1.7 attributes attribute type description code unsigned short the error code; see error codes for details. constants error codes constant value description invalid_expression_err 51 an invalid xpath expression was used. type_err 52 an attempt was made to reference an unavailable type. ...
nsIXSLTException
content/xslt/public/nsixslt
exception.idlscriptable please add a summary to this article. inherits from: nsi
exception last changed in gecko 1.7 attributes attribute type description sourcenode nsidomnode the context node, may be null. read only. stylenode nsidomnode the node in the stylesheet that triggered the
exception. read only. ...
Breaking on exceptions - Firefox Developer Tools
to instruct the debugger to pause on an
exception, tick these checkboxes in the breakpoints list: pause on
exceptions pause on caught
exceptions when an
exception occurs, the line where it occurs is highlighted in the source pane, with a squiggly red line under the problematic code. a tooltip describes the
exception. starting in firefox 80, a disclosure triangle within the tooltip reveals a stack trace. ...
DOMException.code - Web APIs
specifications specification status comment web idlthe definition of 'code' in that specification. candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
DOMException.message - Web APIs
specifications specification status comment web idlthe definition of 'message' in that specification. candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
XPathException.code - Web APIs
the code read-only property of the xpath
exception interface returns a short that contains one of the error code constants. syntax var
exceptioncode =
exception.code; value a short number representing the error code. specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpath
exception' in that specification. recommendation initial definition ...
nsIXPConnect
, in nsiclassinfo aclassinfo, in nsixpconnectjsobjectholder aprototype); void setdebugmodewhenpossible(in prbool mode); native code only! void setdefaultsecuritymanager(in nsixpcsecuritymanager amanager, in pruint16 flags); nsixpcfunctionthistranslator setfunctionthistranslator(in nsiidref aiid, in nsixpcfunctionthistranslator atranslator); void setreportalljs
exceptions(in boolean reportalljs
exceptions); void setsafejscontextforcurrentthread(in jscontextptr cx); void setsecuritymanagerforjscontext(in jscontextptr ajscontext, in nsixpcsecuritymanager amanager, in pruint16 flags); void syncjscontexts(); void updatexows(in jscontextptr ajscontext, in nsixpconnectwrappednative aobject, in pruint32 away); native code only! obsol...
...objectholder aholder); attributes attribute type description collectgarbageonmainthreadonly prbool obsolete since gecko 1.9 currentjsstack nsistackframe read only. currentnativecallcontext nsaxpcnativecallcontextptr read only. deferreleasesuntilaftergarbagecollection prbool obsolete since gecko 1.9 pending
exception nsi
exception constants constant value description init_js_standard_classes 1 << 0 flag_system_global_object 1 << 1 omit_components_object 1 << 2 xpc_xow_clearscope 1 tells updatexows() to clear the scope of all of the xows it finds. obsolete since gecko 2.0 methods native code only!addjsholder ...
... xpc_xow_clearscope 1 tells updatexows() to clear the scope of all of the xows it finds. obsolete since gecko 2.0 methods native code only!addjsholder root js objects held by aholder. void addjsholder( in voidptr aholder, in nsscriptobjecttracerptr atracer ); parameters aholder the object that hold the js objects that should be rooted. atracer missing description
exceptions thrown missing
exception missing description clearallwrappednativesecuritypolicies() void clearallwrappednativesecuritypolicies(); parameters none.
exceptions thrown missing
exception missing description native code only!createsandbox create a sandbox for evaluating code in isolation using evalinsandboxobject(). nsixpconnectjsobjectholder createsandbox( in jscontextptr cx,...
...And 54 more matches
imgIContainer
2.0 void startanimation(); obsolete since gecko 2.0 void stopanimation(); obsolete since gecko 2.0 void unlockimage(); attributes attribute type description animated boolean whether this image is animated. you can only be guaranteed that querying this will not throw if status_decode_complete is set on the imgirequest. read only.
exceptions thrown ns_error_not_available if the animated state cannot be determined. animationmode unsigned short currentframe gfxasurface get a surface for the current frame. this may be a platform-native, optimized frame, so you cannot inspect its pixel data. read only. native code only! obsolete since gecko 2.0 currentframein...
...nsigned long the index of the current frame that would be drawn if the image was to be drawn now. read only. obsolete since gecko 2.0 currentframeisopaque boolean whether the current frame is opaque; that is, needs the background painted behind it. read only. height print32 the height of the container rectangle. in the case of any error, zero is returned, and an
exception will be thrown. read only. loopcount long number of times to loop the image. note: -1 means forever. obsolete since gecko 2.0 numframes unsigned long the total number of frames in this image. read only. obsolete since gecko 2.0 preferredalphachannelformat gfx_format read only. obsolete since gecko 1.9.2 type unsigned short the t...
...long the total number of frames in this image. read only. obsolete since gecko 2.0 preferredalphachannelformat gfx_format read only. obsolete since gecko 1.9.2 type unsigned short the type of this image (one of the type_* values above). read only. width print32 the width of the container rectangle. in the case of any error, zero is returned, and an
exception will be thrown. read only. constants constant value description type_raster 0 enumerated values for the 'type' attribute (below). type_vector 1 flag_none 0x0 flags for imgicontainer operations. meanings: flag_none: lack of flags. flag_sync_decode: forces synchronous/non-progressive decode of all available data be...
...And 49 more matches
nsIMsgIncomingServer
server. usesecauth boolean valid boolean constants constant value description defaultsocket 0 trytls 1 alwaysusetls 2 usessl 3 keepdups 0 deletedups 1 movedupstotrash 2 markdupsread 3 methods clearallvalues() this is really dangerous. this destroys all pref values do not call this unless you know what you're doing! void clearallvalues(); parameters none. ...
...an valid boolean constants constant value description defaultsocket 0 trytls 1 alwaysusetls 2 usessl 3 keepdups 0 deletedups 1 movedupstotrash 2 markdupsread 3 methods clearallvalues() this is really dangerous. this destroys all pref values do not call this unless you know what you're doing! void clearallvalues(); parameters none. ...
...at you're doing! void clearallvalues(); parameters none.
exceptions thrown missing
exception missing description cleartemporaryreturnreceiptsfilter() if sent folder pref is changed we need to clear the temporary return receipt filter so that the new return receipt filter can be recreated (by configuretemporaryreturnreceiptsfilter()). void cleartemporaryreturnreceiptsfilter(); parameters none.
exceptions thrown missing
exception missing description closecachedconnections() void closecachedconnections(); parameters none.
exceptions thrown missing
exception missing description configuretemporaryfilters() for mail, this configures both the mdn filter, and the server-side spam filter filters, if needed. if we have set up to filter return receipts into our sent folder, this utility method create...
...And 34 more matches
WebIDL bindings
implemented by an object with a property whose name matches the operation, the object itself is always used as this. if the interface is not a single-operation interface, it just exposes a single method for every idl method/getter/setter. the signatures of the methods correspond to the signatures for throwing idl methods/getters/setters with an additional trailing "mozilla::dom::callbackobject::
exceptionhandling a
exceptionhandling" argument, defaulting to ereport
exceptions. if areport
exceptions is set to ereport
exceptions, the methods will report js
exceptions before returning. if areport
exceptions is set to erethrow
exceptions, js
exceptions will be stashed in the errorresult and will be reported when the stack unwinds to wherever the errorresult was set up. for example, this webidl: callback i...
... short somemethod(domstring somestring); }; callback interface myothercallback { // single-operation interface short dosomething(node somenode); }; interface myinterface { attribute mycallback foo; attribute mycallback? ...
...(domstring somestring); }; callback interface myothercallback { // single-operation interface short dosomething(node somenode); }; interface myinterface { attribute mycallback foo; attribute mycallback? ...
...And 31 more matches
Index - Web APIs
lerate, which indicates the sample rate to use for the new context. 140 audiodestinationnode api, audiodestinationnode, interface, reference, web audio api audiodestinationnode has no output (as it is the output, no more audionode can be linked after it in the audio graph) and one input. the number of channels in the input must be between 0 and the maxchannelcount value or an
exception is raised. 141 audiodestinationnode.maxchannelcount api, audiodestinationnode, property, reference, référence(2), web audio api, maxchannelcount an unsigned long. 142 audiolistener api, audiolistener, interface, reference, référence(2), web audio api the audiolistener interface represents the position and orientation of the unique person listening to ...
...07 audioworkletnode.onprocessorerror api, audio, audioworkletnode, audioworkletprocessor, event handler, property, reference, web audio api, onprocessorerror the onprocessorerror property of the audioworkletnode interface defines an event handler function to be called when the processorerror event fires. this occurs when the underlying audioworkletprocessor behind the node throws an
exception in its constructor, the process method, or any user-defined class method. 208 audioworkletnode.parameters api, audio, audioparam, audioworkletnode, experimental, property, reference, web audio api the read-only parameters property of the audioworkletnode interface returns the associated audioparammap — that is, a map-like collection of audioparam objects. they are instantia...
...sprimitivevalue interface derives from the cssvalue interface and represents the current computed value of a css property. 440 cssprimitivevalue.getcountervalue() api, cssprimitivevalue, method, needsexample, getcountervalue the getcountervalue() method of the cssprimitivevalue interface is used to get the counter value. if this css value doesn't contain a counter value, a dom
exception is raised. modification to the corresponding style property can be achieved using the counter interface. 441 cssprimitivevalue.getfloatvalue() api, cssprimitivevalue, method, getfloatvalue the getfloatvalue() method of the cssprimitivevalue interface is used to get a float value in a specified unit. if this css value doesn't contain a float value or can't be converted into th...
...And 23 more matches
Index
js::add*root jsapi reference, needscontent, obsolete, reference, référence(2), spidermonkey these functions are obsoleted, use js::persistentrooted instead. 23 js::autoidarray jsapi reference, reference, référence(2), spidermonkey js::autoidarray takes the ownership of jsidarray, and frees it in destructor by calling js_destroyidarray. 24 js::autosave
exceptionstate jsapi reference, reference, référence(2), spidermonkey js::autosave
exceptionstate saves and later restores the current
exception state of a given jscontext. 25 js::autovaluearray jsapi reference, reference, référence(2), spidermonkey js::autovaluearray<n> holds a rooted array of js::value. this is typically used for local variables being passed to function ...
...lloc}cangc, the js engine may call the large-allocation- failure callback, if set, to allow the embedding to flush caches, possibly perform shrinking gcs, etc. to make some room. the allocation will then be retried (and may still fail.) 68 js::setoutofmemorycallback jsapi reference, reference, référence(2), spidermonkey unlike the error reporter, which is only called if the
exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called immediately at the oom site to allow the embedding to capture the current state of heap allocation before anything is freed. if the large-allocation-failure callback is called at all (not all allocation sites call the large-allocation-failure callback on failure), it is called before the out-of-memory callback; the out...
...e ownership of string and frees it in destructor. 87 jsautocompartment jsapi reference, spidermonkey no summary! 88 jsbool jsapi reference, obsolete, spidermonkey no summary! 89 jscheckaccessop jsapi reference, obsolete, reference, référence(2), spidermonkey check whether obj[id] may be accessed per mode, returning js_false on error/
exception, js_true on success with obj[id]'s stored value in *vp. as for jspropertyop, id is either a string or an int jsval. 90 jsclass jsapi reference, spidermonkey use jsclass to define a custom class of javascript objects. a jsclass has a name, flags, and several callback functions for advanced customization of object behavior. 91 jsclass.call jsapi reference, spider...
...And 20 more matches
nsIDBFolderInfo
rvalue sorttype nsmsgviewsorttypevalue version unsigned long viewflags nsmsgviewflagstypevalue viewtype nsmsgviewtypevalue methods andflags() long andflags( in long flags ); parameters flags missing description return value missing description
exceptions thrown missing
exception missing description changeexpungedbytes() void changeexpungedbytes( in long delta ); parameters delta missing description
exceptions thrown missing
exception missing description changenummessages() void changenummessages( in long delta ); parameters delta missing description
exceptions thrown m...
...n missing
exception missing description changeexpungedbytes() void changeexpungedbytes( in long delta ); parameters delta missing description
exceptions thrown missing
exception missing description changenummessages() void changenummessages( in long delta ); parameters delta missing description
exceptions thrown missing
exception missing description changenumunreadmessages() void changenumunreadmessages( in long delta ); parameters delta missing description
exceptions thrown missing
exception missing description getbooleanproperty() boolean getbooleanproperty( in string propertyname, in boolean defaultvalue ); parameters propertyname missing description ...
...messages( in long delta ); parameters delta missing description
exceptions thrown missing
exception missing description getbooleanproperty() boolean getbooleanproperty( in string propertyname, in boolean defaultvalue ); parameters propertyname missing description defaultvalue missing description return value missing description
exceptions thrown missing
exception missing description getcharacterset() void getcharacterset( out acstring charset, out boolean overriden ); parameters charset missing description overriden missing description
exceptions thrown missing
exception missing description getcharactersetoverride() obsolete since gecko 1.8 (firef...
...And 20 more matches
LiveConnect Overview - Archive of obsolete content
argument of type char. for example, you can pass the string "h" to the character constructor as follows: var c = new java.lang.character("h"); in javascript 1.3 and earlier, you must pass such methods an integer which corresponds to the unicode value of the character. for example, the following code also assigns the value "h" to the variable c: var c = new java.lang.character(72); handling java
exceptions in javascript when java code fails at run time, it throws an
exception. if your javascript code accesses a java data member or method and fails, the java
exception is passed on to javascript for you to handle. beginning with javascript 1.4, you can catch this
exception in a try...catch statement. (although this functionality (along with some others) had been broken in gecko 1.9 (see bug 391642) ...
...he mozilla-specific liveconnect code had not been maintained inside mozilla, with java 6 update 11 and 12 building support for reliance on mozilla's implementation of the generic (and cross-browser) npapi plugin code, this has again been fixed.) for example, suppose you are using the java forname method to assign the name of a java class to a variable called theclass. ...
...mplementation of the generic (and cross-browser) npapi plugin code, this has again been fixed.) for example, suppose you are using the java forname method to assign the name of a java class to a variable called theclass. the forname method throws an
exception if the value you pass it does not evaluate to the name of a java class. place the forname assignment statement in a try block to handle the
exception, as follows: function getclass(javaclassname) { try { var theclass = java.lang.class.forname(javaclassname); } catch (e) { return ("the java
exception is " + e); } return theclass; } in this example, if javaclassname evaluates to a legal class name, such as "java.lang.string", the assignment succeeds. if javaclassname evaluates to an invalid class name, such as "string", ...
...And 19 more matches
Control flow and error handling - JavaScript
nevertheless, not all thrown objects are created equal. while it is common to throw numbers or strings as errors, it is frequently more effective to use one of the e...
... 'cherries': console.log('cherries are $3.00 a pound.'); break; case 'mangoes': console.log('mangoes are $0.56 a pound.'); break; case 'papayas': console.log('mangoes and papayas are $2.79 a pound.'); break; default: console.log(`sorry, we are out of ${fruittype}.`); } console.log("is there anything else you'd like?");
exception handling statements you can throw
exceptions using the throw statement and handle them using the try...catch statements. throw statement try...catch statement
exception types just about any object can be thrown in javascript. nevertheless, not all thrown objects are created equal. while it is common to throw numbers or strings as errors, it is frequently more effective to use one of the
exception types specifically created for this ...
...ment and handle them using the try...catch statements. throw statement try...catch statement
exception types just about any object can be thrown in javascript. nevertheless, not all thrown objects are created equal. while it is common to throw numbers or strings as errors, it is frequently more effective to use one of the
exception types specifically created for this purpose: ecmascript
exceptions dom
exception and domerror throw statement use the throw statement to throw an
exception. a throw statement specifies the value to be thrown: throw expression; you may throw any expression, not just expressions of a specific type. ...
...And 16 more matches
nsIMsgHeaderParser
iven a string which contains a list of header addresses, returns a comma-separated list of just the 'mailbox' portions. if any of the addresses doesn't have a mailbox, then the user name is used instead. autf8string extractheaderaddressmailboxes( in string line ); parameters line the header line to parse. return value a comma-separated list of just the mailbox parts of the addresses.
exceptions thrown missing
exception missing description native code only!extractheaderaddressnames given a string which contains a list of header addresses, returns a comma-separated list of just the 'user name' portions. if any of the addresses doesn't have a name, then the mailbox is used instead. autf8string extractheaderaddressnames( in string line ); parameters line the header line to...
...snames given a string which contains a list of header addresses, returns a comma-separated list of just the 'user name' portions. if any of the addresses doesn't have a name, then the mailbox is used instead. autf8string extractheaderaddressnames( in string line ); parameters line the header line to parse. return value a comma-separated list of just the name parts of the addresses. ...
...contains a list of header addresses, returns a comma-separated list of just the 'user name' portions. if any of the addresses doesn't have a name, then the mailbox is used instead. autf8string extractheaderaddressnames( in string line ); parameters line the header line to parse. return value a comma-separated list of just the name parts of the addresses. ...
...And 14 more matches
nsIRadioInterfaceLayer
void dial( in domstring number ); parameters number missing description ex...
..._disconnected 10 call_state_incoming 11 datacall_state_unknown 0 datacall_state_connecting 1 datacall_state_connected 2 datacall_state_disconnecting 3 datacall_state_disconnected 4 call_state_ringing 2 obsolete since gecko 14.0 methods answercall() void answercall( in unsigned long callindex ); parameters callindex missing description
exceptions thrown missing
exception missing description deactivatedatacall() void deactivatedatacall( in domstring cid, in domstring reason ); parameters cid missing description reason missing description
exceptions thrown missing
exception missing description dial() functionality for making and managing phone calls. void dial( in domstring number ); parameters number missing description
exceptions thrown missing ex...
... dial() functionality for making and managing phone calls. void dial( in domstring number ); parameters number missing description
exceptions thrown missing
exception missing description enumeratecalls() will continue calling callback.enumeratecallstate until the callback returns false. void enumeratecalls( in nsiriltelephonycallback callback ); parameters callback missing description
exceptions thrown missing
exception missing description getdatacalllist() void getdatacalllist(); parameters none.
exceptions thrown missing
exception missing description getnumberofmessagesfortext() returns the number of multi-part sms needed for a given text (160 characters for one sms). unsigned short getnumberofmessagesfortext( in domstring text ); parameters text the body text of an sms. ret...
...And 14 more matches
try...catch - JavaScript
the try...catch statement marks a block of statements to try and specifies a response should an
exception be thrown. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax try { try_statements } [catch (
exception_var_1 if condition_1) { // non-standard catch_statements_1 }] ... [catch (
exception_var_2) { catch_statements_2 }] [finally { finally_statements }] try_statements the statements to be executed. ...
...github.com/mdn/interactive-examples and send us a pull request. syntax try { try_statements } [catch (
exception_var_1 if condition_1) { // non-standard catch_statements_1 }] ... [catch (
exception_var_2) { catch_statements_2 }] [finally { finally_statements }] try_statements the statements to be executed. catch_statements_1, catch_statements_2 statements that are executed if an
exception is thrown in the try-block.
exception_var_1,
exception_var_2 an identifier to hold an
exception object for the associated catch-block. condition_1 a conditional expression. finally_statements statements that are executed after the try statement completes. these statements execute regardless of whether an
exception was thrown or caught. description the try statement consists of a...
...s thrown or caught. description the try statement consists of a try-block, which contains one or more statements. {} must always be used, even for single statements. at least one catch-block, or a finally-block, must be present. this gives us three forms for the try statement: try...catch try...finally try...catch...finally a catch-block contains statements that specify what to do if an
exception is thrown in the try-block. 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. if no
exception is thrown in the try-block, the catch-block is skipped. the finally-block will always execute after the try-block and catch-block(s) have finished executing. it always executes, regardless of ...
...And 14 more matches
nsIFile
astring newname); void remove(in boolean recursive); void reveal(); void setrelativedescriptor(in nsifile fromfile, in acstring relativedesc); attributes attribute type description directoryentries nsisimpleenumerator returns an enumeration of the elements in a directory. each element in the enumeration is an nsifile. read only.
exceptions thrown ns_error_file_not_directory indicates that this nsifile does not reference a directory. diskspaceavailable print64 the number of bytes available to non-superuser on the disk volume containing the nsifile. read only. filesize print64 the value of this attribute is the number of bytes corresponding to the data represented by the fi...
...anteed to be a usable path to pass to nspr or the c stdlib. there are problems that affect platforms on which a path does not fully specify a file because two volumes can have the same name (for example mac). this is solved by holding "private", native data in the nsifile implementation. this native data is lost when you convert to a string. do not pass to use with nspr or stdlib! read only.
exceptions thrown ns_error_file_invalid_path indicates that this nsifile does not reference a symbolic link. constants constant value description normal_file_type 0 a normal file. directory_type 1 a directory/folder. delete_on_close 0x80000000 optional parameter used by opennsprfiledesc methods append() th...
... this function is used for constructing a descendant of the current nsifile. note: this method does not return a new nsifile; it modifies the object it was called on. if the old nsifile should be retained, use clone(). void append( in astring node ); parameters node a string which is intended to be a child node of the nsifile. this string must not contain a path separator character.
exceptions thrown ns_error_file_unrecognized_path indicates that anode incorrectly contains a path separator character. native code only! appendnative this method is used for constructing a descendant of the current nsifile. [native character encoding variant] void appendnative( in acstring node ); parameters node a string that is intended to be a child node of the current nsifile. th...
...And 12 more matches
nsIHttpChannel
to indicate whether or not the underlying http transaction should be allowed to be pipelined with other transactions. this should be set to false, for example, if the application knows that the corresponding document is likely to be very large. this attribute is true by default, though other factors may prevent pipelining. this attribute may only be set before the channel is opened.
exceptions thrown ns_error_failure if set after the channel has been opened. redirectionlimit unsigned long this attribute specifies the number of redirects this channel is allowed to make. if zero, the channel will fail to redirect and will generate a ns_error_redirect_loop failure status. note: an http redirect results in a new channel being created.
... from which this channel's uri was obtained (see rfc2616 section 14.36). this attribute may only be set before the channel is opened. note: the channel may silently refuse to set the referer: header if the uri does not pass certain security checks (e.g., a "https://" url will never be sent as the referrer for a plaintext http request). the implementation is not required to throw an
exception when the referrer uri is rejected.
exceptions thrown ns_error_in_progress if set after the channel has been opened. ns_error_failure if used for setting referrer during visitrequestheaders(). getting the value will not throw. requestmethod acstring set or get the http request method (default is "get"). setter is case insensitive; g...
...get"). setter is case insensitive; getter returns an uppercase string. this attribute may only be set before the channel is opened. note: the data for a "post" or "put" request can be configured via nsiuploadchannel. however, after setting the upload data, it may be necessary to set the request method explicitly. the documentation for nsiuploadchannel has further details.
exceptions thrown ns_error_in_progress if set after the channel has been opened. requestsucceeded boolean returns true if the http response code indicates success. the value of nsirequest.status() will be ns_ok even when processing a 404 file not found response because such a response may include a message body that (in some cases) should be shown to the user. u...
...And 12 more matches
JSAPI User Guide
o c++ types and store them in local variables. the native function uses js_set_rval(cx, vp, val) to store its javascript return value. on success, a jsnative must call js_set_rval and return true. the value passed to js_set_rval is returned to the javascript caller. on failure, a jsnative calls an error-reporting function, in this case js_reporterror, and returns false. this causes a javascript
exception to be thrown. the caller can catch the
exception using a javascript try/catch statement. to make native functions callable from javascript, declare a table of jsfunctionspecs describing the functions. then call js_definefunctions. static jsfunctionspec myjs_global_functions[] = { js_fs("rand", myjs_rand, 0, 0), js_fs("srand", myjs_srand, 0, 0), js_fs("system", myjs_system, 1, ...
...pt to grow the process. this means that garbage collection typically happens when memory-intensive code is running, perhaps the worst possible time. an application can trigger garbage collection at a more convenient time by calling js_gc or js_maybegc. js_gc forces garbage collection. js_maybegc performs garbage collection only if it is likely to reclaim a worthwhile amount of memory. errors and
exceptions the importance of checking the return value of jsapi functions, of course, goes without saying. almost every jsapi function that takes a jscontext * argument can fail. the system might run out of memory. there might be a syntax error in a script. or a script might explicitly throw an
exception. the javascript language has
exceptions, and c++ has
exceptions, but they are not the same thing. spi...
...ng the return value of jsapi functions, of course, goes without saying. almost every jsapi function that takes a jscontext * argument can fail. the system might run out of memory. there might be a syntax error in a script. or a script might explicitly throw an
exception. the javascript language has
exceptions, and c++ has
exceptions, but they are not the same thing. spidermonkey does not use c++
exceptions for anything. jsapi functions never throw c++
exceptions, and when spidermonkey calls an application callback, the callback must not throw a c++
exception. throwing and catching
exceptions we have already seen one example of how to throw an
exception from a jsnative function. simply call js_reporterror, with printf-style arguments, and return false. rc = system(cmd); if (rc != 0) { ...
...And 11 more matches
Debugger - Firefox Developer Tools
nary form. the webassembly text generation will be disabled. collectcoverageinfo a boolean value indicating whether code coverage should be enabled inside each debuggee of this debugger instance. changing this flag value will recompile all jit code to add or remove code coverage instrumentation. changing this flag when any frame of the debuggee is currently active on the stack will produce an
exception. setting this to true enables code coverage instrumentation, which can be accessed via the debugger.script getoffsetscoverage function. in some cases, the code coverage might expose information which pre-date the modification of this flag. code coverage reports are monotone, thus one can take a snapshot when the debugger is enabled, and output the difference. setting this to false prevents th...
...ses, the code coverage might expose information which pre-date the modification of this flag. code coverage reports are monotone, thus one can take a snapshot when the debugger is enabled, and output the difference. setting this to false prevents this debugger instance from requiring any code coverage instrumentation, but it does not guarantee that the instrumentation is not present. ...
...t when the debugger is enabled, and output the difference. setting this to false prevents this debugger instance from requiring any code coverage instrumentation, but it does not guarantee that the instrumentation is not present. uncaught
exceptionhook 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. ...
...And 11 more matches
FileSystemEntrySync - Web APIs
olders that are stored in the origin of your app. just use filesystem: scheme for the root directory of the origin of the app. for example, if your app is in http://ww.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. chrome shows a read-only list of all the files and folders stored the origin of your app. ...
...he app. for example, if your app is in http://ww.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. chrome shows a read-only list of all the files and folders stored the origin of your app. method overview metadata getmetadata () raises (file
exception); filesystementrysync moveto (in directoryentrysync parent, optional domstring newname) raises (file
exception); filesystementrysync copyto(in directoryentrysync parent, optional domstring newname) raises (file
exception); domstring tourl(); void remove() raises (file
exception); directoryentrysync getparent(); attributes attribute type description filesystem readonly filesystemsync the file system where the entry resides. ...
...isdirectory readonly boolean true if filesystementrysync is a directory. isfile readonly boolean true if the filesystementrysync is a file. name readonly domstring the name of the entry, excluding the path leading to it. methods getmetadata() look up metadata about this entry. [ todo: specify what kind of metadata ] metadata getmetada () raises (file
exception); parameter none returns metadata
exceptions this method can raise a file
exception with the following codes:
exception description not_found_err the entry does not exist. invalid_state_err the filesystemsync is no longer valid for some reason besides being deleted. moveto() move an entry to a different location on the file system. movin...
...And 11 more matches
IDBIndexSync - Web APIs
ended for use only with web workers, and was eventually removed from the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the idbindexsync interface of the indexeddb api provides synchronous access to an index in a database. ...
...ed from the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the idbindexsync interface of the indexeddb api provides synchronous access to an index in a database. ...
...be reintroduced in the future if there is enough demand from web developers. the idbindexsync interface of the indexeddb api provides synchronous access to an index in a database. ...
...And 11 more matches
IDBObjectStoreSync - Web APIs
only with web workers, and was eventually removed from the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the idbobjectstoresync interface of the indexeddb api provides synchronous access to an object store of a database. ...
.... the idbobjectstoresync interface of the indexeddb api provides synchronous access to an object store of a database. ...
... any add (in any value, in optional any key) raises (idbdatabase
exception); idbindexsync createindex (in domstring name, in domstring storename, in domstring keypath, in optional boolean unique); any get (in any key) raises (idbdatabase
exception); idbcursorsync opencursor (in optional idbkeyrange range, in optional unsigned short direction) raises (idbdatabase
exception); idbindexsync openindex (in domstring name) raises (idbdatabase
exception); any put (in any value, in optional any key) raises (idbdatabase
exception); void remove (in any key) raises (idbdatabase
exception); void removeindex (in domstring indexname) raises (idbdatabase
exception); attributes attribute type description indexna...
...And 10 more matches
throw - JavaScript
the throw statement throws a user-defined
exception. 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. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax throw expression; expression the expression to throw. description use the throw statement to throw an
exception. when you throw an
exception, expression specifies the value of the
exception. ...
...pository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax throw expression; expression the expression to throw. description use the throw statement to throw an
exception. when you throw an
exception, expression specifies the value of the
exception. ...
... interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax throw expression; expression the expression to throw. description use the throw statement to throw an
exception. when you throw an
exception, expression specifies the value of the
exception. each of the following throws an
exception: throw 'error2'; // generates an
exception with a string value throw 42; // generates an
exception with the value 42 throw true; // generates an
exception with the value true throw new error('required'); // generates an error object with the message of required also note that the throw statement is affected by automatic semicolon insertion (asi) as no line terminator between the throw keyword and the expression is allowed. e...
...And 10 more matches
Scripting Java
y was available only to embeddings that used org.mozilla.javascript.importertoplevel class as the top level scope. the class provides additional importpackage() and importclass() global functions for scripts but their extensive usage has tendency to pollute the global name space with names of java classes and prevents loaded classes from garbage collection. see bugzilla 245882 for details. ...
...ble only to embeddings that used org.mozilla.javascript.importertoplevel class as the top level scope. the class provides additional importpackage() and importclass() global functions for scripts but their extensive usage has tendency to pollute the global name space with names of java classes and prevents loaded classes from garbage collection. see bugzilla 245882 for details. ...
...provides additional importpackage() and importclass() global functions for scripts but their extensive usage has tendency to pollute the global name space with names of java classes and prevents loaded classes from garbage collection. see bugzilla 245882 for details. java
exceptions
exceptions thrown by java methods can be caught by javascript code using try...catch statement. ...
...And 8 more matches
test/assert - Archive of obsolete content
e different exports["test strict equality"] = function(assert) { assert.notstrictequal(1, "1", "test strict equality between 1 and '1'"); } parameters actual : object the actual result. expected : object the expected result. message : string optional message to log, providing extra information about the test. throws(block, error, message) assert that a block of code throws the expected
exception. ...
...tequal(1, "1", "test strict equality between 1 and '1'"); } parameters actual : object the actual result. expected : object the expected result. message : string optional message to log, providing extra information about the test. throws(block, error, message) assert that a block of code throws the expected
exception. ...
...tual : object the actual result. expected : object the expected result. message : string optional message to log, providing extra information about the test. throws(block, error, message) assert that a block of code throws the expected
exception. this method takes an optional error argument: to check that the
exception thrown is of the expected type, pass a constructor function: the
exception thrown must be an instance of the object returned by that function. ...
...And 7 more matches
Promise
illed, when and if the final value becomes available. a fulfillment value becomes permanently associated with the promise. this may be any value, including undefined. rejected, if an error prevented the final value from being determined. a rejection reason becomes permanently associated with the promise. this may be any value, including undefined, though it is generally an error object, like in
exception handling. note: you should always handle, forward, or report errors (rejection reasons). if you see the message "a promise chain failed to handle a rejection", there is likely something to be fixed in the code. see handling errors and common pitfalls below. documentation conventions in documentation, the type of the fulfillment value is usually specified between angular brackets. for exampl...
... new promise(executor); parameters executor this function is invoked immediately with the resolving functions as its two arguments: executor(resolve, reject); the constructor will not return until the executor has completed. the resolving functions can be used at any time, before or after the executor has completed, to control the final state of the promise. if the executor throws an
exception, its value will be passed to the reject resolving function. resolving functions resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. note: calling this method with a pending promise as the avalue ar...
...ture transitions). reject() rejects the associated promise with the specified reason. if the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. void reject( areason ); parameters areason optional the rejection reason for the associated promise. although the reason can be undefined, it is generally an error object, like in
exception handling. note: this argument should not be a promise. specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. methods then() calls one of the provided functions as soon as this promise is either fulfilled or rejected. a new promise is returned, whose state evolves depending on this promise and the provided callbac...
...And 7 more matches
Task.jsm
keeping in mind that only the core subset is implemented in this module. tasks are built upon generator functions and promises. the task.spawn() function takes a generator function and starts running it as a task. every time the task yields a promise, it waits until the promise is resolved. task.spawn() returns a promise that is resolved when the task completes successfully, or is rejected if an
exception occurs. you can use the yield operator inside the generator function to wait on a promise, spawn another task, or propagate a value: let resolutionvalue = yield (promise/generator/iterator/value); if you specify a promise, the yield operator returns its resolution value as soon as the promise is resolved. if the promise is rejected, its rejection reason is thrown as an
exception. if you spe...
...in handy when iterating over function lists where some items have been converted to tasks and some not. if you specify anything else, the yield operator returns exactly what you specified. method overview function async(atask); promise spawn(atask); properties attribute type description result read only constructor constructs a special
exception that, when thrown inside a legacy generator function, allows the associated task to be resolved with a specific value. example: task.spawn( function() { yield ... ; throw new task.result("value"); } note: if you want to exit early from a generator function, without returning a value for the task, you can just use the return statement without any arguments. note: if you want to retu...
...with the thrown error if the generator throws. if you specify a function that is not a generator, it is called with no arguments, and its return value is used to fulfill the returned promise. if you specify anything else, you get a promise that is already fulfilled with the specified value. return value a promise that is fulfills when the task returns or rejects when the task throws an
exception. examples general example cu.import("resource://gre/modules/task.jsm"); task.spawn(function* () { // this is our task. it is a generator function because it contains the // "yield" operator at least once. let's create a promise object, wait on // it and capture its resolution value. let mypromise = getpromiseresolvedontimeoutwithvalue(1000, "value"); let result = yield mypromise;...
...And 7 more matches
Bytecode Descriptions
r and jsop::enditer, or by error handling. the script's jsscript::trynotes() must mark the body of the for-in loop, i.e. exactly those instructions that begin executing with iter on the stack, starting with the next instruction (always jsop::loophead). code must not jump into or out of this region: control can enter only by executing jsop::iter and can exit only by executing a jsop::enditer or by
exception unwinding. (a jsop::enditer is always emitted at the end of the loop, and extra copies are emitted on "exit slides", where a break, continue, or return statement exits the loop.) typically a single try note entry marks the contiguous chunk of bytecode from the instruction after jsop::iter to jsop::enditer (inclusive); but if that range contains any instructions on exit slides, after a jsop::endit...
...ex) stack: ⇒ regexp clone and push a new regexp object. implements: evaluation for regularexpressionliteral. functions creating functions lambda operands: (uint32_t funcindex) stack: ⇒ fn push a function object. this clones the function unless it's a singleton; see canreusefunctionforclone. the new function inherits the current environment chain. used to create most js functions. notable
exceptions are arrow functions and derived or default class constructors. the function indicated by funcindex must be a non-arrow function. implements: instantiatefunctionobject, evaluation for functionexpression, and so on. format: jof_object lambdaarrow operands: (uint32_t funcindex) stack: newtarget ⇒ arrowfn push a new arrow function. newtarget matters only if the arrow function uses the expressio...
...es one of the generatorresumekind values as int32value. checkresumekind stack: rval, gen, resumekind ⇒ rval handle throw and return resumption. gen must be the generator object for the current frame. resumekind must be a generatorresumekind stored as an int32 value. if it is next, continue to the next instruction. if resumekind is throw or return, these completions are handled by throwing an
exception. see generatorthroworreturn. resume stack: gen, val, resumekind ⇒ rval resume execution of a generator, async function, or async generator. this behaves something like a call instruction. it pushes a stack frame (the one saved when gen was suspended, rather than a fresh one) and runs instructions in it. once gen returns or yields, its return value is pushed to this frame's stack and executio...
...And 7 more matches
Index
reflected into javascript. the components object is actually a native instance of the nsixpccomponents interface which is reflected into javascript as a top level object using xpconnect. 17 components.constructor xpcom:language bindings, xpconnect creates a javascript function which can be used to create or construct new instances of xpcom components. 18 components.
exception xpcom:language bindings, xpconnect components.
exception is a javascript constructor to create nsixpc
exception objects. these
exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will. 19 components.id xpcom:language bindings, xpc...
...review, xpcom:language bindings, xpconnect ensures that the specified object's methods are all in the object's scope, and aren't cross-component wrappers. 44 components.utils.reporterror xpcom:language bindings, xpconnect components.utils.reporterror reports a javascript error object to the error console, and returns. it is meant for use by extension developers who have
exception handler blocks which want to "eat" an
exception, but still want to report it to the console. 45 components.utils.scheduleprecisegc guide, needscontent, xpcom, xpcom:language bindings, xpconnect this method lets scripts schedule a garbage collection cycle. the garbage collection cycle will occur sometime in the future, when no javascript code is executing. this is useful parti...
...his context, if it is an nsisupports, |null| otherwise. retrieve the underlying context wrapped by this jsdicontext. top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. this attribute is only valid for contexts which implement nsiscriptcontext. setting or getting this attribute on any other context will throw a ns_error_no_interface
exception. stack frame objects. these are only valid inside the jsdiexecutionhook which gave it to you. after you return from that handler the bottom frame, and any frame you found attached through it, are invalidated via the jsdiephemeral interface. once a jsdistackframe has been invalidated all method and property accesses will throw a ns_error_not_available
exception. 193 moziasyncfavicons ...
...And 7 more matches
SVGTransform - Web APIs
svg transform interface svgtransform is the interface for one of the component transformations within an svgtransformlist; thus, an svgtransform object corresponds to a single component (e.g., scale(…) or matrix(…)) within a transform attribute. an svgtransform object can be designated as read only, which means that attempts to modify the object will result in an
exception being thrown. interface overview also implement none methods void setmatrix(in svgmatrix matrix) void settranslate(in float tx, in float ty) void setscale(in float sx, in float sy) void setrotate(in float angle, in float cx, in float cy) void setskewx(in float angle) void setskewy(in float angle) properties readonly unsigned short...
... the given rotation. when the rotation is around the center point (0, 0), e and f will be zero. methods name & arguments return description setmatrix(in svgmatrix matrix) void sets the transform type to svg_transform_matrix, with parameter matrix defining the new transformation. note that the values from the parameter matrix are copied. ...
...e rotation is around the center point (0, 0), e and f will be zero. methods name & arguments return description setmatrix(in svgmatrix matrix) void sets the transform type to svg_transform_matrix, with parameter matrix defining the new transformation. note that the values from the parameter matrix are copied. ...
...And 7 more matches
SVGTransformList - Web APIs
svg transform list interface the svgtransformlist defines a list of svgtransform objects. an svgtransformlist object can be designated as read only, which means that attempts to modify the object will result in an
exception being thrown. note: starting in gecko 9.0,the svgtransformlist dom interface is now indexable and can be accessed like arrays interface overview also implement none methods void clear() svgtransform initialize(in svgtransform newitem) svgtransform getitem(in unsigned long index) svgtransform insertitembefore(in svgtransform newitem, in unsigned long index) svgtransform replaceitem(in svgtransform newitem, in unsigned long index) svgtransform removeitem(in unsigned long index) svgtransform appenditem(in svgt...
... properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgtransform newitem) svgtransform clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is al...
...transform newitem) svgtransform clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgtransform returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the l...
...And 7 more matches
nsIZipWriter
irefox 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. operations performed on the queue throw any errors that occur out to the observer. attempting to perform a synchronous operation on the interface while the background queue is in progress will throw an ns_error_in_progress
exception. file and directory names should use slashes ("/") as separators and should not begin with a slash. note: although it is not necessary to add directory entries in order to add file entries within them, some zip utilities may have problems with that, so it may be best to add the directory entries explicitly first. implemented by: @mozilla.org/zipwriter;1. to create an instance, use: var zipwri...
...ing azipentry); void open(in nsifile afile, in print32 aioflags); void processqueue(in nsirequestobserver aobserver, in nsisupports acontext); void removeentry(in autf8string azipentry, in boolean aqueue); attributes attribute type description comment acstring gets or sets the comment associated with the currently open zip file.
exceptions thrown ns_error_not_initialized if no zip file has been opened. file nsifile the zip file being written to. read only. inqueue boolean true if operations are being performed in the background queue, or false if background operations are not in progress. read only. constants constant value description compressi...
...d slashes ('/') in the path. amodtime the modification time of the entry in microseconds. acompression one of the compression constants, indicating the compression method to use. achannel the channel from which to get the data. aqueue if true, the operation is queued for later execution. if false, the operation is performed immediately. will be performed when processqueue() is called.
exceptions thrown ns_error_not_initialized no zip file is open. ns_error_file_already_exists the specified path already exists in the zip file. ns_error_in_progress the zip writer is already performing another operation. addentrydirectory() adds a new directory entry to the zip file. if azipentry does not end with "/" then it will be added. note: although it is not necessary to add directory en...
...And 6 more matches
IDBDatabaseSync - Web APIs
om the spec because its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the databasesync interface in the indexeddb api represents a synchronous connection to a database. ...
...velopers. the databasesync interface in the indexeddb api represents a synchronous connection to a database. ...
...nection to a database. method overview idbobjectstoresync createobjectstore (in domstring name, in domstring keypath, in optional boolean autoincrement) raises (idbdatabase
exception); idbobjectstoresync openobjectstore (in domstring name, in optional unsigned short mode) raises (idbdatabase
exception); void removeobjectstore (in domstring storename) raises (idbdatabase
exception); void setversion (in domstring version); idbtransactionsync transaction (in optional domstringlist storenames, in optional unsigned int timeout) raises (idbdatabase
exception); attributes attribute type description description readonly domstring the human-readable description of the connected database. name readonly domstri...
...And 6 more matches
SVGLengthList - Web APIs
svg length list interface the svglengthlist defines a list of svglength objects. an svglengthlist object can be designated as read only, which means that attempts to modify the object will result in an
exception being thrown. note: starting in gecko 5.0,the svglengthlist dom interface is now indexable and can be accessed like arrays interface overview also implement none methods void clear() svglength initialize(in svglength newitem) svglength getitem(in unsigned long index) svglength insertitembefore(in svglength newitem, in unsigned long index) svglength replaceitem(in svglength newitem, in unsigned long index) svglength removeitem(in unsigned long index) svglength appenditem(in svglength newitem) properties ...
... properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svglength newitem) svglength clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a...
...e(in svglength newitem) svglength clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svglength returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. th...
...And 6 more matches
SVGNumberList - Web APIs
note: starting in gecko 5.0,the svgnumberlist dom interface is now indexable and can be accessed like arrays. ...
... properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgnumber newitem) svgnumber clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a l...
...alize(in svgnumber newitem) svgnumber clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgnumber returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list...
...And 6 more matches
Index - Archive of obsolete content
opment, web development:tools the error console is a tool available in most mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. it reports javascript-related errors and warnings, css errors and arbitrary messages from chrome code. in firefox, the error console can be opened from the tools menu or by ctrl-shift-j. 433
exception logging in javascript extensions, extensions:tools, guide, javascript, javascript:tools, tools, web development, web development:tools in versions of firefox prior to firefox 3, all javascript
exceptions were always logged into the error console if they remained unhandled at the time execution returned back into c++ code. as a result, if, for example, c++ code called a javascript compon...
... 434 existing content this is a list of existing mozilla.org documentation. ...
... 434 existing content this is a list of existing mozilla.org documentation. it needs to be checked, prioritized, and migrated. ...
...And 5 more matches
SVGPointList - Web APIs
svg point list interface the svgpointlist defines a list of svgpoint objects. an svgpointlist object can be designated as read only, which means that attempts to modify the object will result in an
exception being thrown. interface overview also implement none methods void clear() svgpoint initialize(in svgpoint newitem) svgpoint getitem(in unsigned long index) svgpoint insertitembefore(in svgpoint newitem, in unsigned long index) svgpoint replaceitem(in svgpoint newitem, in unsigned long index) svgpoint removeitem(in unsigned long index) svgpoint appenditem(in svgpoint newitem) ...
... numberofitems unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgpoint newitem) svgpoint clears all existing current items from the list and re-initializes the list to hold the single item specif...
... svgpoint clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgpoint returns the specified item from the list. the returned item is the item itself and not a copy. any changes...
...And 5 more matches
SVGStringList - Web APIs
svg string list interface the svgstringlist defines a list of domstring objects. an svgstringlist object can be designated as read only, which means that attempts to modify the object will result in an
exception being thrown. interface overview also implement none methods void clear() domstring initialize(in domstring newitem) domstring getitem(in unsigned long index) domstring insertitembefore(in domstring newitem, in unsigned long index) domstring replaceitem(in domstring newitem, in unsigned long index) domstring removeitem(in unsigned long index) domstring appenditem(in domstring newitem) properties readonly unsigned long numberofitems readonly unsigned long length norm...
...ription numberofitems unsigned long the number of items in the list. length unsigned long a mirror of the value in numberofitems, for consistency with other interfaces. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in domstring newitem) domstring clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already ...
...in domstring newitem) domstring clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) domstring returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list...
...And 5 more matches
console - Archive of obsolete content
essages appear in the browser console. if you're developing your add-on using the extension auto-installer, then the add-on is installed in firefox, meaning that messages will appear in the browser console. but see the discussion of logging levels: by default, messages logged using log(), info(), trace(), or warn() won't be logged in these situations. console methods all console methods except
exception() and trace() accept one or more javascript objects as arguments and log them to the console. depending on the console's underlying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) deprecated, you should use console.log() instead. console.error(object[, object, ...]) logs the arguments to the console, pre...
...on and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) deprecated, you should use console.log() instead. ...
...r interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) deprecated, you should use console.log() instead. ...
...And 4 more matches
JSAPI Cookbook
i * * warning: this only works for integers that fit in 32 bits. * otherwise, convert the number to floating point (see the next example). */ js::callargs args = js::callargsfromvp(argc, vp); args.rval().setint32(23); return true; returning a floating-point number // javascript return 3.14159; /* jsapi */ js::callargs args = js::callargsfromvp(argc, vp); args.rval().setdouble(3.14159);
exception handling throw the most common idiom is to create a new error object and throw that. js_reporterror does this. note that javascript
exceptions are not the same thing as c++
exceptions. the jsapi code also has to return false to signal failure to the caller. // javascript throw new error("failed to grow " + varietal + ": too many greenflies."); /* jsapi */ js_reporterror(cx, "failed to grow %...
...ror("failed to grow " + varietal + ": too many greenflies."); /* jsapi */ js_reporterror(cx, "failed to grow %s: too many greenflies.", varietal); return false; to internationalize your error messages, and to throw other error types, such as syntaxerror or typeerror, use js_reporterrornumber instead. javascript also supports throwing any value at all, not just error objects. use js_setpending
exception to throw an arbitrary js::value from c/c++. // javascript throw exc; /* jsapi */ js_setpending
exception(cx, exc); return false; when js_reporterror creates a new error object, it sets the filename and linenumber properties to the line of javascript code currently at the top of the stack. this is usually the line of code that called your native function, so it's usually what you want. jsapi c...
... return throwerror(cx, global, message, __file__, __line__); the jsapi code here is actually simulating throw error(message) without the new, as new is a bit harder to simulate using the jsapi. in this case, unless the script has redefined error, it amounts to the same thing. catch // javascript try { // try some stuff here; for example: foo(); b...
...And 4 more matches
nsICrashReporter
m/system/nsicrashreporter.idlscriptable provides access to crash reporting functionality. ...
...ble provides access to crash reporting functionality. ...
.... 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void annotatecrashreport(in acstring key, in acstring data); void appendappnotestocrashreport(in acstring data); void appendobjc
exceptioninfotoappnotes(in voidptr a
exception); native code only! void writeminidumpfor
exception(in voidptr a
exceptioninfo); native code only! attributes attribute type description enabled boolean enable or disable the crashreporter at runtime. minidumppath nsilocalfile get or set the path on the local system to which minidumps will be written when a crash happens.
exceptions thrown ns_error_not_initialized if crash reporting is not initialized. serverurl nsiurl get or set t...
...And 4 more matches
nsIFaviconService
n is dispatched through the observer's service. void expireallfavicons(); parameters none. getfavicondata() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.getfavicondataforpage() instead. this method retrieves the given favicon data. throws an
exception if we don't have data. if there is no data but we have an entry for this favicon, adatalen will be "0" and adata will be null. void getfavicondata( in nsiuri afaviconuri, out autf8string amimetype, out unsigned long adatalen, optional from gecko 2.0 [array,retval,size_is(adatalen)] out octet adata ); parameters afaviconuri uri of the favicon whose data is being read. amimety...
...ctet adata ); parameters afaviconuri uri of the favicon whose data is being read. amimetype output parameter where the mime type will be placed. adatalen output parameter where the size of the binary data will be placed. adata output parameter where the binary favicon data will be placed. this will be null if we have this uri but have no data associated with it.
exceptions thrown ns_error_not_available thrown when we have never heard of this favicon url. getfavicondataasdataurl() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.getfavicondataforpage() instead. this method retrieves the given favicon data...
... thrown when we have never heard of this favicon url. getfavicondataasdataurl() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.getfavicondataforpage() instead. ...
...And 4 more matches
nsIOutputStream
iinputstream afromstream, in unsigned long acount); unsigned long writesegments(in nsreadsegmentfun areader, in voidptr aclosure, in unsigned long acount); native code only! methods close() close the stream. forces the output stream to flush() any buffered data. note: this method may be called more than once, but subsequent calls are ignored. void close(); parameters none.
exceptions thrown ns_base_stream_would_block indicates that closing the output stream would block the calling thread for an indeterminate amount of time. this
exception may only be thrown if isnonblocking() returns true. flush() this method may be called to instruct the output stream to write out the contents of any internal buffers to a low-level data sink, such as a file on disk. however, the flus...
... isnonblocking() note: writing to a blocking output stream will block the calling thread until all given data can be consumed by the stream. ...
... write out the contents of any internal buffers to a low-level data sink, such as a file on disk. however, the flush method may simply do nothing depending on the implementation of the output stream. void flush(); parameters none.
exceptions thrown ns_base_stream_would_block indicates that flushing the output stream would block the calling thread for an indeterminate amount of time. this
exception may only be thrown if isnonblocking() returns true. isnonblocking() note: writing to a blocking output stream will block the calling thread until all given data can be consumed by the stream. note: a non-blocking output stream may implement nsiasyncoutputstream to provide consumers with a way to wait for the stream to accept more data once its write() method is unable to accept any data witho...
...And 4 more matches
nsIScriptableIO
lf. nsifile getfile( in astring alocation, in astring afilename ); parameters alocation a location key identifying a known standard directory. the afilename parameter is treated as being local to this directory. afilename the relative path of the file to generate a reference for. return value returns an nsifile object referencing the specified file location.
exceptions thrown ns_error_invalid_arg alocation was null. getfilewithpath() returns a file reference using an absolute file path to locate the file. note: you should avoid using this method, since file paths are platform-dependent and non-portable. instead, you should use getfile() and construct the path from the base location manually. nsifile getfilewithpath( in astring afilepath );...
...s are platform-dependent and non-portable. instead, you should use getfile() and construct the path from the base location manually. nsifile getfilewithpath( in astring afilepath ); parameters afilepath the absolute pathname of the file to reference, or the value of a file's persistentdescriptor. return value returns an nsifile object referencing the specified file location.
exceptions thrown ns_error_invalid_arg afilepath was null. newuri() creates a uri object that implements the nsiuri interface. nsiuri newuri( in nsivariant auri ); parameters auri the file for which to create a new nsiuri object. this parameter may be specified either as a url string or as an nsifile object. return value returns an nsiuri object corresponding to the sp...
...r_invalid_arg afilepath was null. newuri() creates a uri object that implements the nsiuri interface. nsiuri newuri( in nsivariant auri ); parameters auri the file for which to create a new nsiuri object. this parameter may be specified either as a url string or as an nsifile object. return value returns an nsiuri object corresponding to the specified string or file.
exceptions thrown ns_error_invalid_arg auri was null. newinputstream() retrieves a stream from which data can be read. nsisupports newinputstream( in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize ); parameters abase the base object from which to read. this shoul...
...And 4 more matches
nsITextInputProcessor
is specified, defaultprevented attribute of dispatching keyboard events true. this is not useful in usual cases. this may be useful for automated tests. key_non_printable_key 0x00000002 one of akeyflags. when you attempt to dispatch a non-printable key's events, it's recommented this be specified. if the key attribute value is not a registered key name, this flag causes throwing an
exception. therefore, this can prevent non-printable key events to cause dispatching as printable keyboard events and you can detect the registered key name change from the thrown
exception. key_force_printable_key 0x00000004 one of akeyflags. when you attempt to dispatch a printable key's event whose key attribute value (i.e., inputting string) will match with a registered key name, this fl...
...of akeyflags. the location attribute value of dispatching keyboard events is computed automatically if the attribute isn't initialized or initialized with 0. for the latter case, you may not want textinputprocessor to compute location attribute value. in this case, you can suppress the computation with this flag. if this is specified with non-zero location attribute value, this causes throwing an
exception since it doesn't make sense. key_keep_keycode_zero 0x00000010 one of akeyflags. the keycode attribute value of dispatching printable keyboard events is computed from key value automatically if the attribute isn't initialized or initialized with 0. for the latter case, you may not want textinputprocessor to compute keycode attribute value. in this case, you can suppress the computat...
... dispatching keyboard events, you need to dispatch modifier key events before and after that. however, especially for keeping compatibility with legacy api, you may want to modify only the modifier state of a textinputprocessor instance. in this case, you can suppress textinputprocessor dispatches modifier key events with this flag. if this is specified for non-modifier key, it causes throwing an
exception since it doesn't make sense. methods appendclausetopendingcomposition() appends a clause to the pending composition string which is set by setpendingcompositionstring(). sum of alength must be same as the length of astring of setpendingcompositionstring(). void appendclausetopendingcomposition(in unsigned long alength, in unsigned long aattribute); ...
...And 4 more matches
Debugger.Frame - Firefox Developer Tools
more than one debugger instance is debugging the same code, each debugger gets a separate debugger.frame instance for a given frame. 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. note that frames only become inactive at times that are predictable for the debugger: when the debuggee runs, or when the debugger removes frames from the stack itself. visible frames when ...
... frame on the stack, witholder as its older property. invoke the debuggee code as appropriate for the given invocation function, with the "debugger" frame as its continuation. for example, debugger.frame.prototype.eval pushes an "eval" frame for code it runs, whereas debugger.object.prototype.call pushes a "call" frame. when the debuggee code completes, whether by returning, throwing an
exception or being terminated, pop the "debugger" frame, and return an appropriate completion value from the invocation function to the debugger. when a debugger calls an invocation function to run debuggee code, that code’s continuation is the debugger, not the next debuggee code frame. pushing a "debugger" frame makes this continuation explicit, and makes it easier to find the extent of the stack c...
...ger.frame instance as the this value. the function should return a resumption value indicating how execution should proceed. on newly created frames, this property’s value is undefined. when this handler is called, this frame’s current execution location, as reflected in its offset and environment properties, is the operation which caused it to be unwound. in frames returning or throwing an
exception, the location is often a return or a throw statement. in frames propagating
exceptions, the location is a call. when an onpop call reports the completion of a construction call (that is, a function called via the new operator), the completion value passed to the handler describes the value returned by the function body. if this value is not an object, it may be different from the value produced...
...And 4 more matches
DirectoryEntrySync - Web APIs
tory. var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method returns a directoryentrysync, which represents a file in the file system. the following creates a new directory called superseekrit in the root directory. var direntry = fs.root.getdirectory('superseekrit', {create: true}); method overview directoryreadersync createreader () raises (file
exception); fileentrysync getfile (in domstring path, in optional flags options) raises (file
exception); directoryentrysync getdirectory (in domstring path, in optional flags options) raises (file
exception); void removerecursively () raises (file
exception); methods createreader() creates a new directoryreadersync to read entries from this directory. directoryreadersync...
...ile (in domstring path, in optional flags options) raises (file
exception); directoryentrysync getdirectory (in domstring path, in optional flags options) raises (file
exception); void removerecursively () raises (file
exception); methods createreader() creates a new directoryreadersync to read entries from this directory. directoryreadersync createreader ( ) raises (file
exception); returns directoryreadersync represents a directory in a file system. parameter none
exceptions this method can raise a file
exception with the following codes:
exception description not_found_err the directory does not exist. security_err the browser determined that it was not safe to look up the metadata. [ todo: explain why ] getfile() ...
... description not_found_err the directory does not exist. security_err the browser determined that it was not safe to look up the metadata. [ todo: explain why ] getfile() depending on how you've set the options parameter, the method either creates a file or looks up an existing file. void getfile ( in domstring path, in optional flags options ) raises (file
exception); parameter path either an absolute path or a relative path from the directory to the file to be looked up or created. you cannot create a file whose immediate parent does not exist. create the parent directory first. options an object literal describing the behavior of the method. if the file does not exist, it is created. object literal condition result create: ...
...And 4 more matches
SVGPathSegList - Web APIs
description numberofitemsread only unsigned long the number of items in the list. methods clear() void clears all existing current items from the list, with the result being an empty list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list cannot be modified. initialize(in svgpathseg newitem) svgpathseg clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if t...
... svgpathseg clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list cannot be modified. getitem(in unsigned long index) svgpathseg returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are ...
...d_err is raised when the list cannot be modified. getitem(in unsigned long index) svgpathseg returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the list cannot be modified. insertitembefore(in svgpathseg newitem, in unsigned long index) svgpathseg inserts a new item into the list at the specified position. the first item is number 0. ...
...And 4 more matches
Operable - Accessibility
ble to close that window again and return to the main content using the keyboard. this is very important so that keyboard users do not get trapped on specific sections of your apps. 2.1.3 keyboard — all functionality (aaa) this is a further step beyond criterion 2.1.1. to achieve aaa conformance, all functionality should be accessible using keyboard controls — with no
exceptions. see ui controls and building keyboard accessibility back in 2.1.4 character key shortcuts (a) added in 2.1 if a single character key shortcut exists, then at least one of the following is true: single character key shortcuts can be turned off, remapped or are only active when the relevant user interface component is in focus. understanding character key shortcuts note:...
...need to be completed within a time limit for security reasons. success criteria how to conform to the criteria practical resource 2.2.1 timing is adjustable (a) for functionality with time limits (e.g. completing a hotel or flight booking often has a time limit), the user should be given controls to allow them to adjust, extend or turn off the time limit.
exceptions to this are activities with time limits longer than 20 hours, real time events (e.g. live multiplayer games), and any other activity that requires a time limit and would be invalidated if it were turned off. 2.2.2 pausing, stopping, hiding (a) for moving/blinking content that starts automatically, lasts longer than 5 seconds, and is shown alongside other content, control...
... ui controls for general advice on tabbing to controls. if you need to place elements in an unusual layout, it is better to make sure the source order is sensible, then use css features like positioning to handle the layout. 2.4.4 link purpose (in context) (a) the purpose/destination of a link can be determined from the link text, or from its surroundings (e.g. the surrounding text).
exceptions are where the link purpose is ambiguous to all users (see ambiguous to users in general for a useful explanation of this). see meaningful text labels. also note that you should minimize instances where multiple copies of the same text are linked to different places. this can cause problems for screenreader users, who will often bring up a list of the links out of context — several links all...
...And 4 more matches
Shell global objects
if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, the name of property of element that holds this code. this is wha...
...he dom element o. if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, the name of property of element that holds this code. this is what debugger.source.prototype.elementattributename returns. runoffthreadscript() wait for off-thread compilation to complete. ...
...a negative value (default) means that the execution time is unlimited. if a second argument is provided, it will be invoked when the timer elapses. ...
...And 3 more matches
nsIAccessNode
attribute type description document nsiaccessibledocument the document accessible that this access node resides in. read only. note: renamed from accessibledocument in gecko 2.0 domnode node the dom node this nsiaccessnode is associated with. read only. firstchildnode nsiaccessnode the first nsiaccessnode child. read...
..., for the purposes of caching and referencing this object. read only. native code only! methods getchildnodeat() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) get the nth child of this node. nsiaccessnode getchildnodeat( in long childnum ); parameters childnum zero-based child index. return value the nth nsiaccessnode child.
exceptions thrown ns_error_failure indicates that the access node is unattached from the accessible tree. getcomputedstylecssvalue() retrieve the computed style value as nsidomcssprimitivevalue for the dom node this access node is associated with. note: the meanings of width, height and other size measurements depend on the version of css being used. therefore, for bounds information, it is better ...
....getbounds(). nsidomcssprimitivevalue getcomputedstylecssvalue( in domstring pseudoelt, in domstring propertyname ); parameters pseudoelt the pseudo element to retrieve style for, or empty string for general computed style information for the node. propertyname retrieve the computed style value for this property name. return value the nsidomcssprimitivevalue computed style value.
exceptions thrown ns_error_failure indicates that the access node is unattached from the accessible tree. getcomputedstylevalue() retrieve the computed style value for this dom node, if it is a dom element. note: the meanings of width, height and other size measurements depend on the version of css being used. therefore, for bounds information, it is better to use nsiaccessible.getbounds(). domstr...
...And 3 more matches
nsIContentPrefService
the result. if desired, javascript callers can instead provide a function to call upon completion. return value the preference's value is returned; this value may be a string, integer, boolean, or any other value. the result may be null (nsidatatype:vtype_empty) if the preference's value is either null, or undefined (nsidatatype:vtype_void) if there is no saved preference by the specified name.
exceptions thrown ns_error_illegal_value if agroup is not a string, nsiuri, or null. or if aname is null or an empty string getprefs() get all preferences and their values for the specified uri. note: prior to gecko 2.0, the site could only be specified by nsiuri. now a string can be used as well. nsipropertybag2 getprefs( in nsivariant agroup ); parameters agroup the group whose p...
... group whose preferences are to be retrieved; this may be specified as either a uri or as a string; in either case, the group consists of all sites matching the hostname portion of the specified uri. specify null to get the preferences from the global preference space; those preferences apply to all sites. return value the result is an nsipropertybag2 containing the preferences and their values. ...
... haspref() determines whether or not a preference exists. note: prior to gecko 2.0, the site could only be specified by nsiuri. now a string can be used as well. ...
...And 3 more matches
Debugger.Object - Firefox Developer Tools
value the promise has been rejected with. if the referent is not a promise, or the promise has not been rejected, throw a typeerror. promiseallocationsite if the referent is a promise, this is the javascript execution stack captured at the time of the promise’s allocation. this can return null if the promise was not created from script. if the referent is not a promise, throw a typeerror
exception. promiseresolutionsite if the referent is a promise, this is the javascript execution stack captured at the time of the promise’s resolution. this can return null if the promise was not resolved by calling its resolve or reject resolving functions from script. if the referent is not a promise, throw a typeerror
exception. promiseid if the referent is a promise, this is a process-unique iden...
... promisedependentpromises if the referent is a promise, this is an array of debugger.objects referring to the promises directly depending on the referent promise. these are: return values of then() calls on the promise. ...
... of the arguments. once a promise is settled, it will generally notify its dependent promises and forget about them, so this is most useful on pending promises. note that the array only contains the promises that directly depend on the referent promise. it does not contain promises that depend on promises that depend on the referent promise. if the referent is not a promise, throw a typeerror
exception. promiselifetime if the referent is a promise, this is the number of milliseconds elapsed since the promise was created. if the referent is not a promise, throw a typeerror
exception. promisetimetoresolution if the referent is a promise, this is the number of milliseconds elapsed between when the promise was created and when it was resolved. if the referent hasn’t been resolved or is not ...
...And 3 more matches
RTCPeerConnection.setRemoteDescription() - Web APIs
n the connection). the promise fulfillment handler receives no input parameters. note: the process of changing descriptions actually involves intermediary steps handled by the webrtc layer to ensure that an active connection can be changed without losing the connection if the change does not succeed. see pending and current descriptions in webrtc connectivity for more details on this process.
exceptions the following
exceptions are reported to the rejection handler for the promise returned by setremotedescription(): invalidaccesserror the content of the description is invalid. invalidstateerror the rtcpeerconnection is closed, or it's in a state which isn't compatible with the specified description's type. for example, if the type is rollback and the signaling state is one of stable, hav...
...rejection handler for the promise returned by setremotedescription(): invalidaccesserror the content of the description is invalid. invalidstateerror the rtcpeerconnection is closed, or it's in a state which isn't compatible with the specified description's type. for example, if the type is rollback and the signaling state is one of stable, have-local-pranswer, or have-remote-pranswer, this
exception is thrown, because you can't roll back a connection that's either fully established or is in the final stage of becoming connected. operationerror any errors that occur which don't match the others specifeid here are reported as operationerror. this includes identity validation errors. rtcerror an rtcerror with the errordetail set to sdp-syntax-error is reported if the sdp specified by rtcses...
...nnection to a stable signaling state, then, once the rollback is completed, sets the remote description to the specified offer. this begins a new negotiation session, with the newly-established offer as the starting point. upon starting the new negotiation with the newly-established offer, the local peer is now the callee, even if it was previously the caller. ...
...And 3 more matches
SVGAngle - Web APIs
an svgangle object can be associated with a particular element. the associated element is used to determine which element's content attribute to update if the object reflects an attribute. ...
...d an <angle> with a rad unit. svg_angletype_grad an <angle> with a grad unit. properties unittype the type of the value as specified by one of the svg_angletype_* constants defined on this interface. value the value as a floating point value, in user units. setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automatically to reflect this setting. ...
...t. svg_angletype_grad an <angle> with a grad unit. properties unittype the type of the value as specified by one of the svg_angletype_* constants defined on this interface. value the value as a floating point value, in user units. setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automatically to reflect this setting. ...
...And 3 more matches
SVGLength - Web APIs
svg length interface the svglength interface correspond to the <length> basic data type. an svglength object can be designated as read only, which means that attempts to modify the object will result in an
exception being thrown. interface overview also implement none methods void newvaluespecifiedunits(in unsigned short unittype, in float valueinspecifiedunits) void converttospecifiedunits(in unsigned short unittype) properties readonly unsigned short unittype float value float valueinspecifiedunits domstring valueasstring constants svg_lengthtype_unknown = 0 svg_lengthtype_number = 1 svg_lengthtype_percentage = 2 svg_lengthtype_ems = 3 svg_lengthtype_exs ...
... name type description unittype unsigned short the type of the value as specified by one of the svg_lengthtype_* constants defined on this interface. value float the value as a floating point value, in user units. setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automatically to reflect this setting.
exceptions on setting: a dom
exception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. valueinspecifiedunits float the value as a floating point value, in the units expressed by unittype. setting this attribute will cause value and valueasstring to be updated automatically to reflect this set...
... valueasstring domstring the value as a string value, in the units expressed by unittype. ...
...And 3 more matches
/loader - Archive of obsolete content
ided in the paths option. if this option is not provided, the loader will use plain path resolution. this feature may also be used to implement specific security constraints. for example, the sdk generates a manifest file at build time representing a dependency graph of all modules used by an add-on. ...
... id add-on debugging requires knowing which objects belong to which add-on. when created with this option, loader will transparently mark all new global objects with the provided v...
...ction(id, requirer) { let requirements = manifest[requirer].requirements; if (id in manifest) return requirements[id]; else throw error('module "' + requirer + '" has no authority to require ' + 'module "' + id + "') } }); thrown
exceptions will propagate to the caller of require(). if the function assigned to resolve does not return a string value, an
exception will still be thrown as the loader will be unable to resolve the required module's location. id add-on debugging requires knowing which objects belong to which add-on. when created with this option, loader will transparently mark all new global objects with the provided value. all together all of these options can be combined to configure the loader for a specific use case. don't get too exci...
...And 2 more matches
Web Replay
ll as a diff containing the original contents of all pages of heap and static memory that were modified since the previous snapshot. certain memory regions are excluded from snapshots; these memory regions are allocated with a special api and are used for state that needs to be preserved when rewinding. snapshot data may be stored in memory or on disk. diffs are computed by first setting up an
exception handler thread (mac only) very similar to the one used by asm.js. when taking the first snapshot all addressable memory in the process is enumerated and write-protected, and as faults occur a special
exception handler thread unprotects the memory, copies its contents and marks it as dirty. when the next snapshot is taken, only the dirty memory is examined for any changes vs. the copy made. thi...
...er the debugger is interacting with the child process the child process is paused at some point in execution, and the contents of the debug objects are only valid until the middleman notifies the child process that it can resume forward execution or must rewind to an earlier snapshot. when the child process pauses again (at a breakpoint, say) the debug objects must be reconstructed. there is an
exception to this, for scripts and script source objects; debug objects for these will continue to hold the same referent after resuming or rewinding the replaying process. this is necessary for script breakpoints to work, and is implemented by ensuring that the ordering of creation of scripts and script sources is deterministic (mainly by disabling off thread parsing, which is one of the behavior changes...
...tures should not be too hard. unrecordable executions there are restrictions on the executions that can be recorded. these should all be detectable during recording, so that we don't attempt to replay an execution we know will not match up with the recording. the following executions run into fundamental limits of the approach and cannot be replayed: executions which throw overrecursion js
exceptions can't be reliably replayed; overrecursion happens at different times depending on how scripts are compiled, which can vary between recording and replaying. similarly, executions which run out of memory at some point can't be reliably replayed. executions which are stopped at some point by the slow script dialog can't be reliably replayed. keeping track of the exact point where an interrupt oc...
...And 2 more matches
mozIStorageConnection
es a database connection, allowing all pending asynchronous statements to complete first. void asyncclose( in mozistoragecompletioncallback acallback optional ); parameters acallback optional an optional callback handler to be executed when the connection is successfully closed. that object's mozistoragecompletioncallback.complete() routine will be called once the connection is closed.
exceptions thrown ns_error_unexpected thrown if the method was called on a thread other than the one that opened the connection. begintransaction() starts a new transaction deferred transaction. this is the same as calling mozistorageconnection with mozistorageconnection.transaction_deferred. void begintransaction(); parameters none. begintransactionas() this method starts a new transaction o...
...onous and synchronous statement execution. the best way to deal with this is to only execute your statements asynchronously using mozistorageconnection.executeasync(). this method will manage the transactions for you, so you don't have to worry about them. note: the database engine does not support nested transactions, so attempting to start a transaction when one is already active will throw an
exception. void begintransactionas( in print32 transactiontype ); parameters transactiontype one of the transaction constants (mozistorageconnection.transaction_deferred, mozistorageconnection.transaction_immediate, mozistorageconnection.transaction_exclusive) clone() clones a database connection, optionally making the new connection read only. note: if your connection is already read-only,...
...s access privileges will be the same as the original connection, regardless of the value you specify for the areadonly parameter. mozistorageconnection clone( in boolean areadonly optional ); parameters areadonly if true, the returned database connection is in read only mode. this is false by default. return value a new mozistorageconnection object representing the cloned connection. ...
...And 2 more matches
nsIAccessibleHyperLink
boolean isvalid(); obsolete since gecko 1.9 attributes attribute type description anchorcount long the number of anchors within this hyperlink. is normally 1 for anchors. this anchor is, for example, the visible output of the html:a tag. with an image map, reflects the actual areas within the map. read only. note: renamed from anchors in gecko 1.9
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. endindex long the end offset of the hyperlink accessible within the parent accessible. the returned value is related to the nsiaccessiblehyperlink interface of the object that owns this hyperlink. read only. note: the link itself is represented by one emb...
...rom the accessible tree. endindex long the end offset of the hyperlink accessible within the parent accessible. the returned value is related to the nsiaccessiblehyperlink interface of the object that owns this hyperlink. read only. note: the link itself is represented by one embedded character within the parent text, so the endindex should be startindex + 1.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. selected boolean determines whether the element currently has the focus, for example after returning from the destination page. read only. note: aria links can only be focused if they have the tabindex attribute set. also, state_focused should then be se...
... indicates that the accessible is unattached from the accessible tree. selected boolean determines whether the element currently has the focus, for example after returning from the destination page. read only. note: aria links can only be focused if they have the tabindex attribute set. also, state_focused should then be set on the accessible for this link. ...
...And 2 more matches
nsIContentViewer
dom document object. hide() void hide(); parameters none. native code only!init initializes the content viewer. ...
...d hide(); parameters none. native code only!init initializes the content viewer. void init( in nsiwidgetptr aparentwidget, [const] in nsintrectref abounds ); parameters aparentwidget missing description abounds missing description loadcomplete() void loadcomplete( in unsigned long astatus ); parameters astatus missing description
exceptions thrown missing
exception missing description loadstart() void loadstart( in nsisupports adoc ); parameters adoc missing description
exceptions thrown missing
exception missing description move() void move( in long ax, in long ay ); parameters ax missing description ay missing description open() attaches the content viewer to its dom window and docshell. void open( in n...
...ate, in nsishentry ashentry ); parameters astate a state object that might be useful in attaching the dom window. ashentry the history entry that the content viewer was stored in. the entry must have the docshells for all of the child documents stored in its child shell list. pagehide() void pagehide( in boolean isunload ); parameters isunload missing description
exceptions thrown missing
exception missing description permitunload() determins whether or not the document wants to prevent unloading by firing beforeunload on the document, and if it does, prompts the user. the result is returned. boolean permitunload( in boolean acallercloseswindow optional ); parameters acallercloseswindow optional indicates that the current caller will close() t...
...And 2 more matches
nsIControllers
ller controller); nsicontroller removecontrollerat(in unsigned long index); attributes attribute type description commanddispatcher nsidomxulcommanddispatcher obsolete since gecko 1.9 methods appendcontroller() adds a controller to the end of the list. void appendcontroller( in nsicontroller controller ); parameters controller a controller to be added to the list of controllers.
exceptions thrown ns_error_out_of_memory getcontrollerat() returns the controller instance at the given position. nsicontroller getcontrollerat( in unsigned long index ); parameters index the position of the wanted controller. return value the controller at the given position.
exceptions thrown ns_error_failure the given index is out of range. getcontrollerbyid() returns a controller given by its ...
... getcontrollercount() returns the current number of controllers. unsigned long getcontrollercount(); parameters none. return value the number of controllers currently in the list of controllers. ...
...nd the name of a command, e.g. cmd_copy return value the first controller in the list that supports the given command. getcontrollerid() returns the order of insertion of a controller. unsigned long getcontrollerid( in nsicontroller controller ); parameters controller the controller for which you want to retrieve the insertion index. return value the id in which the controller was inserted.
exceptions thrown ns_error_failure the controller is not in the list of controllers. insertcontrollerat() inserts a controller at a specific position in the list of controllers. if the position is out of range, nothing happens. void insertcontrollerat( in unsigned long index, in nsicontroller controller ); parameters index the position within the list where you want the controller to be inserted. c...
...And 2 more matches
nsICryptoHash
any time after " .. manch("init") .. " is called. this call resets the object. acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. return value this method returns a hash of the data that was read by this object. this can be either binary data or a base-64 encoded string.
exceptions thrown ns_error_not_initialized indicates that init() or initwithstring() has not been called. init() initialize the hashing object. this method may be called multiple times with different algorithm types. note: this method or " .. manch("initwithstring") .. " must be called before any other method on this interface is called. void init( in unsigned long aalgorithm ); parameters ...
...() has not been called. init() initialize the hashing object. this method may be called multiple times with different algorithm types. note: this method or " .. manch("initwithstring") .. " must be called before any other method on this interface is called. void init( in unsigned long aalgorithm ); parameters aalgorithm the hash algorithm to use. must be one of the hash algorithms.
exceptions thrown ns_error_invalid_arg indicates that an unsupported algorithm type was passed initwithstring() initialize the hashing object. this method may be called multiple times with different algorithm types. note: this method or " .. manch("init") .. " must be called before any other method on this interface is called. void initwithstring( in acstring aalgorithm ); parameters aalgor...
...type was passed initwithstring() initialize the hashing object. this method may be called multiple times with different algorithm types. note: this method or " .. manch("init") .. " must be called before any other method on this interface is called. void initwithstring( in acstring aalgorithm ); parameters aalgorithm the hash algorithm type to be used as a string, such as "sha256".
exceptions thrown ns_error_invalid_arg indicates that an unsupported algorithm type was passed update() adds an array of data to be hashed to the object. see computing the hash of a string for an example of using this method. void update( [const, array, size_is(alen)] in octet adata, in unsigned long alen ); parameters adata a buffer to calculate the hash over. alen the length of the bu...
...And 2 more matches
nsIDownloadManager
rameters alistener the nsidownloadprogresslistener object to receive status information from the download manager. canceldownload() cancels the download with the specified id if it's currently in-progress. this calls cancel(ns_binding_aborted) on the nsicancelable provided by the download. void canceldownload( in unsigned long aid ); parameters aid the unique id of the download.
exceptions thrown ns_error_failure the download is not in progress. cleanup() removes completed, failed, and canceled downloads from the list. also notifies observers of the "download-manager-remove-download" topic with a null subject to allow any download manager consumers to react to the removals. void cleanup(); parameters none. endbatchupdate() obsolete since gecko 1.9.1 (...
...he download datasource to disk. void flush(); parameters none. getdownload() retrieves a download managed by the download manager. this can be one that is in progress, or one that has completed in the past and is stored in the database. nsidownload getdownload( in unsigned long aid ); parameters aid the unique id of the download. return value the download with the specified id.
exceptions thrown ns_error_not_available the download is not in the database. onclose() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. called when the download manager front end is closed. useful for third party mana...
...rs adownload the download object to display progress for, as returned by getdownload() or adddownload(). aparent the parent, or opener, of the front end. acanceldownloadonclose whether closing the dialog should cancel the download. pausedownload() pauses the specified download. void pausedownload( in unsigned long aid ); parameters aid the unique id of the download to pause.
exceptions thrown ns_error_failure the download is not in progress. removedownload() removes the download with the specified id if it is not currently in progress. whereas canceldownload() simply cancels the transfer while retaining information about it, removedownload() removes all knowledge of it. also notifies observers of the "download-manager-remove-download" topic with the download id as the ...
...And 2 more matches
nsIEffectiveTLDService
given number of additional domain name parts. acstring getbasedomain( in nsiuri auri, [optional] in pruint32 aadditionalparts ); parameters auri the uri to be analyzed. aadditionalparts the number of domain name parts to be returned in addition to the public suffix. return value an acstring containing the base domain (public suffix plus the requested number of additional parts).
exceptions thrown ns_error_invalid_arg this
exception is thrown if the hostname in auri is empty. ns_error_insufficient_domain_levels this
exception is thrown if there were insufficient subdomain levels in the hostname to satisfy the requested aadditionalparts value. ns_error_host_is_ip_address this
exception is thrown if auri is a numeric ipv4 or ipv6 address. ns_error_unexpected or other error ...
...s not the case. acstring getbasedomainfromhost( in autf8string ahost, in pruint32 aadditionalparts optional ); parameters ahost the host string to be analyzed. aadditionalparts optional the number of domain name parts to be returned in addition to the public suffix. return value an acstring containing the base domain (public suffix plus the requested number of additional parts). ...
...( in autf8string ahost, in pruint32 aadditionalparts optional ); parameters ahost the host string to be analyzed. aadditionalparts optional the number of domain name parts to be returned in addition to the public suffix. return value an acstring containing the base domain (public suffix plus the requested number of additional parts).
exceptions thrown ns_error_invalid_arg this
exception is thrown if ahost is empty. ns_error_unexpected this
exception originates in the normalize() method in nsiidnservice and is thrown when ahost contains characters disallowed in uris. ns_error_insufficient_domain_levels this
exception is thrown if there were insufficient subdomain levels in the hostname to satisfy the requested aadditionalparts value. ns_error_host_is_ip_address this excepti...
...And 2 more matches
nsIIOService
y and according to spec (see rfc 3986). note: most url parsing is done via nsiuri, and in fact the scheme can also be extracted from a url string via nsiuri. this method is provided purely as an optimization. acstring extractscheme( in autf8string urlstring ); parameters urlstring the string for the url to extract the scheme from. return value a string corresponding to the scheme.
exceptions thrown ns_error_malformed_uri if url string is not of the right form. getprotocolflags() returns the protocol flags for a given scheme. unsigned long getprotocolflags( in string ascheme ); parameters ascheme the scheme for which to get the protocol flags. return value the value of the protocolflags attribute for the corresponding nsiprotocolhandler. getprotocolhandler() retu...
...loadingnode, so when aloadingnode is passed this can be left as null. however for loads where aloadingnode is null this argument must be passed. for example for loads from a webworker, pass the principal of that worker. for loads from an addon or from internal browser features, pass the system principal. this principal should almost always be the system principal if aloadingnode is null. the only
exception to this is for loads from webworkers since they don't have any nodes to be passed as aloadingnode. please note, aloadingprincipal is *not* the principal of the resource being loaded. but rather the principal of the context where the resource will be used. atriggeringprincipal the triggeringprincipal of the load. the triggeringprincipal is the principal of the resource that caused this particula...
...oadingnode, so when aloadingnode is passed this can be left as null. however for loads where aloadingnode is null this argument must be passed. for example for loads from a webworker, pass the principal of that worker. for loads from an addon or from internal browser features, pass the system principal. this principal should almost always be the system principal if aloadingnode is null. the only
exception to this is for loads from webworkers since they don't have any nodes to be passed as aloadingnode. please note, aloadingprincipal is *not* the principal of the resource being loaded. but rather the principal of the context here the resource will be used. atriggeringprincipal the triggeringprincipal of the load. the triggeringprincipal is the ...
...And 2 more matches
nsILivemarkService
his method retrieves the uri of the syndication feed associated with a livemark container. nsiuri getfeeduri( in long long container ); parameters container the folder id of a livemark container. return value a nsiuri representing the uri of the feed; if the livemark container doesn't have a valid feed uri, null will be returned or the nsiuri object returned will be the empty string.
exceptions thrown ns_error_invalid_arg if the folder id isn't known or identifies a folder that isn't a livemark container. ns_error_malformed_uri if the site uri annotation has somehow been corrupted (and can't be turned into an nsiuri) getlivemarkidforfeeduri() determines whether the feed uri is a currently registered livemark. long long getlivemarkidforfeeduri( in nsiuri afeeduri ); parame...
...for. return value the id of the livemark. getsiteuri() this method retrieves the uri of the website associated with a livemark container. nsiuri getsiteuri( in long long container ); parameters container the folder id of a livemark container. return value a nsiuri representing the uri of the website; if the livemark container doesn't have a valid site uri, null will be returned.
exceptions thrown ns_error_invalid_arg if the folder id isn't known or identifies a folder that isn't a livemark container. ns_error_malformed_uri if the site uri annotation has somehow been corrupted (and can't be turned into an nsiuri) islivemark() this method determines whether the folder with the given folder id identifies a livemark container. boolean islivemark( in long long folder ); p...
...or_malformed_uri if the site uri annotation has somehow been corrupted (and can't be turned into an nsiuri) islivemark() this method determines whether the folder with the given folder id identifies a livemark container. boolean islivemark( in long long folder ); parameters folder a folder id. return value true if the given folder is a livemark folder, otherwise it returns false.
exceptions thrown ns_error_invalid_arg if the folder id isn't known. reloadalllivemarks() this method reloads all livemark subscriptions, whether or not they have expired. void reloadalllivemarks(); parameters none. reloadlivemarkfolder() this method reloads the livemark with this folder id, whether or not it's expired. void reloadlivemarkfolder( in long long folderid ); parameters fol...
...And 2 more matches
nsINavHistoryContainerResultNode
read only. childrenreadonly boolean false if the node's list of children can be modified (by adding or removing children, or rearranging them), or true if the user interface should not allow the list of children to be altered. read-only. this is false for bookmark folder nodes unless the setfolderreadonly() method has been called to specifically make the folder read-o...
... and day groupings, doing this has no performance cost since the children have already been computed. for queries and bookmark folders, however, being open means they must keep themselves up-to-date by listening for updates and re-querying as needed. dynamiccontainertype autf8string a string representing the dynamic container api service responsible for this container. accessing this throws an
exception if the node isn't a dynamic container. read only. haschildren boolean indicates whether or not the node can have children, and may be used whether the container is open or closed. when the container is closed, the result is an exact answer if the node can be populated easily (for example, for bookmark folders). if it can't be populated easily (for complex history queries, for example), the resu...
...meters auristring the uri attribute value to match on. atime the time attribute to match on. aitemid the item id to match on. arecursive if true, the search will recurse through all child containers of the current container; if false, only direct children of the container are searched. return value an nsinavhistoryresultnode of a node matching the specified details or null if no match is found. ...
...And 2 more matches
Component; nsIPrefBranch
specific preference. this will, in effect, reset the value to the default value. if no default value exists the preference will cease to exist. note: this method does nothing if the prefbranch it is called on is a default branch. void clearuserpref( in string aprefname ); parameters aprefname the preference to be cleared. remarks note: prior to gecko 6.0, this method would throw an
exception if there was no user value set for the specified preference. now, this method never throws. instead, it simply does nothing. deletebranch() called to remove all of the preferences referenced by this branch. note: this method can be called on either a default or user branch but, in effect, always operates on both. void deletebranch( in string astartingat ); parameters astartingat the ...
... preferences referenced by this branch. getboolpref() called to get the state of an individual boolean preference. boolean getboolpref( in string aprefname, [optional] in boolean adefaultvalue ); parameters aprefname the boolean preference to get the state of. adefaultvalue requires gecko 54 optional - a default value to use if the preference does not exist (instead of throwing an
exception). return value the value of the requested boolean preference. getcharpref() called to get the state of an individual string preference. string getcharpref( in string aprefname, [optional] in string adefaultvalue ); parameters aprefname the string preference to retrieve. adefaultvalue requires gecko 54 optional - a default value to use if the preference does not exist (instead of...
...alue the value of the requested boolean preference. getcharpref() called to get the state of an individual string preference. string getcharpref( in string aprefname, [optional] in string adefaultvalue ); parameters aprefname the string preference to retrieve. adefaultvalue requires gecko 54 optional - a default value to use if the preference does not exist (instead of throwing an
exception). return value returns string - the value of the requested string preference. getstringpref() requires gecko 58 (firefox 58 / thunderbird 58 / seamonkey 2.55) called to get the state of an individual utf-8 string preference. utf8string getstringpref( in string aprefname, [optional] in utf8string adefaultvalue ); parameters aprefname the string preference to retrieve. ...
...And 2 more matches
nsIPrincipal
inimum is computed. constant value description enable_denied 1 enable_unknown 2 enable_with_user_permission 3 enable_granted 4 methods native code only!canenablecapability short canenablecapability( in string capability ); parameters capability missing description return value missing description
exceptions thrown missing
exception missing description checkmayload() checks whether this principal is allowed to load the network resource located at the given uri under the same-origin policy. this means that codebase principals are only allowed to load resources from the same domain, the system principal is allowed to load anything, and null principals are not allowed to load anything. note...
...nction throws ns_error_dom_bad_uri. note: other policies might override this, such as the access-control specification. note: the 'domain' attribute has no effect on the behaviour of this function. void checkmayload( in nsiuri uri, in boolean report ); parameters uri missing description report if true, will report a warning to the console service if the load is not allowed.
exceptions thrown ns_error_dom_bad_uri the load is not permitted. native code only!disablecapability void disablecapability( in string capability, inout voidptr annotation ); parameters capability missing description annotation missing description native code only!enablecapability void enablecapability( in string capability, inout voidptr annotation ); parameters ...
... space-delineated list of capabilities which are explicitly denied by a preference. istrusted true if the certificate is a codebase trusted one. ...
...And 2 more matches
nsIURI
he rules of rfc3986. the result is strictly ascii. read only. hasref boolean returns if there is a reference portion (the part after the "#") of the uri. host autf8string the host is the internet domain name to which this uri refers. it could be an ipv4 (or ipv6) address literal. if supported, it could be a non-ascii internationalized domain name. ...
...about:blank) note: characters are not escaped. origincharset acstring the charset of the document from which this uri originated. an empty value implies utf-8. ...
...inated. an empty value implies utf-8. if this value is something other than utf-8 then the uri components (for example spec, prepath, username, and so on) are all fully url-escaped. otherwise, the uri components may contain unescaped multibyte utf-8 characters. read only. password autf8string the optional password, assuming the prehost consists of "username:password".
exceptions thrown ns_error_failure if password is not applicable to the uri scheme (e.g. about:blank) note: some characters may be escaped. path autf8string the path, typically including at least a leading '/' (but may also be empty, depending on the protocol). note: some characters may be escaped. port long the uri's port. a port va...
...And 2 more matches
CSSPrimitiveValue - Web APIs
e object only occurs in a context of a css property. conversions are allowed between absolute values (from millimeters to centimeters, from degrees to radians, and so on) but not between relative values. (for example, a pixel value cannot be converted to a centimeter value.) percentage values can't be converted since they are relative to the parent value (or another property value). there is one
exception for color percentage values: since a color percentage value is relative to the range 0-255, a color percentage value can be converted to a number (see also the rgbcolor interface). <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position...
... css_unknown the value is not a recognized css2 value. the value can only be obtained by using the csstext attribute. css_uri the value is a <uri>. the value can be obtained by using the getstringvalue() method. methods cssprimitivevalue.getcountervalue() this method is used to get the counter value. if this css value doesn't contain a counter value, a dom
exception is raised. modification to the corresponding style property can be achieved using the counter interface. cssprimitivevalue.getfloatvalue() this method is used to get a float value in a specified unit. if this css value doesn't contain a float value or can't be converted into the specified unit, a dom
exception is raised. cssprimitivevalue.getrgbcolorvalue() this method is used to get the rgb c...
... be achieved using the counter interface. cssprimitivevalue.getfloatvalue() this method is used to get a float value in a specified unit. if this css value doesn't contain a float value or can't be converted into the specified unit, a dom
exception is raised. cssprimitivevalue.getrgbcolorvalue() this method is used to get the rgb color. if this css value doesn't contain a rgb color value, a dom
exception is raised. modification to the corresponding style property can be achieved using the rgbcolor interface. cssprimitivevalue.getrectvalue() this method is used to get the rect value. if this css value doesn't contain a rect value, a dom
exception is raised. modification to the corresponding style property can be achieved using the rect interface. cssprimitivevalue.getstringvalue() this method i...
...And 2 more matches
FileEntrySync - Web APIs
this document was last updated on march 2, 2012 and follows the w3c specifications (working draft) drafted on april 19, 2011. this specification is more or less abandoned as it didn't get significant traction among browser makers. basic concepts to write content to file, create a filewriter object by calling createwriter(). ...
...12 and follows the w3c specifications (working draft) drafted on april 19, 2011. this specification is more or less abandoned as it didn't get significant traction among browser makers. basic concepts to write content to file, create a filewriter object by calling createwriter(). method overview filewritersync createwriter () raises (file
exception); file file () raises (file
exception); methods createwriter() creates a new filewriter associated with the file that the fileentry represents. void createwriter ( ) raises (file
exception); parameter none. returns filewritersync
exceptions this method can raise a file
exception with the following codes:
exception description not_found_err the file does not exist. invalid_state_err ...
... invalid_state_err the file is no longer valid for some reason other than it having been deleted. ...
...And 2 more matches
HTMLTableElement - Web APIs
lignment-baseline="middle">htmltableelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmltableelement.caption is a htmltablecaptionelement representing the first <caption> that is a child of the element, or null if none is found. when set, if the object doesn't represent a <caption>, a dom
exception with the hierarchyrequesterror name is thrown. if a correct object is given, it is inserted in the tree as the first child of this element and the first <caption> that is a child of this element is removed from the tree, if any. htmltableelement.thead is a htmltablesectionelement representing the first <thead> that is a child of the element, or null if none is found. when set, if the object doe...
... name is thrown. if a correct object is given, it is inserted in the tree as the first child of this element and the first <caption> that is a child of this element is removed from the tree, if any. htmltableelement.thead is a htmltablesectionelement representing the first <thead> that is a child of the element, or null if none is found. when set, if the object doesn't represent a <thead>, a dom
exception with the hierarchyrequesterror name is thrown. if a correct object is given, it is inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element, and the first <thead> that is a child of this element is removed from the tree, if any. htmltableelement.tfoot is a htmltablesectionelement representing the fi...
...first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element, and the first <thead> that is a child of this element is removed from the tree, if any. htmltableelement.tfoot is a htmltablesectionelement representing the first <tfoot> that is a child of the element, or null if none is found. when set, if the object doesn't represent a <tfoot>, a dom
exception with the hierarchyrequesterror name is thrown. if a correct object is given, it is inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element, and the first <tfoot> that is a child of this element is removed from the tree, if any. htmltableelement.rowsread only returns a live htmlcollectio...
...And 2 more matches
Feature-Policy - HTTP
t is allowed to gather information about the amount of light in the environment around the device through the ambientlightsensor interface. autoplay controls whether the current document is allowed to autoplay media requested through the htmlmediaelement interface. when this policy is disabled and there were no user gestures, the promise returned by htmlmediaelement.play() will reject with a dom
exception. the autoplay attribute on <audio> and <video> elements will be ignored. battery controls whether the use of the battery status api is allowed. when this policy is disabled, the promise returned by navigator.getbattery() will reject with a notallowederror dom
exception. camera controls whether the current document is allowed to use video input devices. when this policy is disabled, the promise...
... display-capture controls whether or not the current document is permitted to use the getdisplaymedia() method to capture screen contents. ...
...ethod to capture screen contents. when this policy is disabled, the promise returned by getdisplaymedia() will reject with a notallowederror if permission is not obtained to capture the display's contents. document-domain controls whether the current document is allowed to set document.domain. when this policy is disabled, attempting to set document.domain will fail and cause a securityerror dom
exception to be be thrown. encrypted-media controls whether the current document is allowed to use the encrypted media extensions api (eme). when this policy is disabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a dom
exception. execution-while-not-rendered controls whether tasks should execute in frames while they're not being rendered (e.g. if an iframe is hidde...
...And 2 more matches
Index - HTTP
r, reference, response header, header the content-range response http header indicates where in a full body message a partial message belongs. 28 content-security-policy csp, http, reference, security, header the http content-security-policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. with a few
exceptions, policies mostly involve specifying server origins and script endpoints. this helps guard against cross-site scripting attacks (xss). 29 csp: base-uri csp, directive, document directive, http, security the http content-security-policy base-uri directive restricts the urls which can be used in a document's <base> element. if this value is absent, then any uri is allowed. if t...
...ature-policy: autoplay directive, feature policy, feature-policy, http, reference, autoplay the http feature-policy header autoplay directive controls whether the current document is allowed to autoplay media requested through the htmlmediaelement interface. when this policy is enabled and there were no user gestures, the promise returned by htmlmediaelement.play() will reject with a dom
exception. the autoplay attribute on <audio> and <video> elements will be ignored. 65 feature-policy: camera directive, feature policy, feature-policy, http, reference, camera the http feature-policy header camera directive controls whether the current document is allowed to use video input devices. when this policy is enabled, the promise returned by mediadevices.getusermedia() will r...
...wederror. 66 feature-policy: encrypted-media directive, eme, feature policy, feature-policy, http, reference the http feature-policy header encrypted-media directive controls whether the current document is allowed to use the encrypted media extensions api (eme). when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a dom
exception. 67 feature-policy: fullscreen feature policy, feature-policy, http, fullscreen, header the http feature-policy header fullscreen directive controls whether the current document is allowed to use element.requestfullscreen(). when this policy is enabled, the returned promise rejects with a typeerror. 68 feature-policy: geolocation feature policy, feature-policy...
...And 2 more matches
core/promise - Archive of obsolete content
on on the promise to observe either its fulfillment or rejection. if the promise is rejected and the rejection is not explicitly observed, any derived promises will be implicitly rejected for the same reason. in the add-on sdk we follow commonjs promises/a specification and model a promise as an object with a then method, which can be used to get the eventual return (fulfillment) value or thrown
exception (rejection): foo().then(function success(value) { // ... }, function failure(reason) { // ... }); if foo returns a promise that gets fulfilled with the value, success callback (the value handler) will be called with that value. however, if the returned promise gets rejected, the failure callback (the error handler) will be called with the reason of an error. propagation the then method of...
...led with the value, success callback (the value handler) will be called with that value. however, if the returned promise gets rejected, the failure callback (the error handler) will be called with the reason of an error. propagation the then method of a promise returns a new promise that is resolved with the return value of either handler. ...
... if handler returns a promise, bar will "become" that promise. to be more precise it will be resolved with a resolution value of the returned promise, which will appear and feel as if it was that returned promise. ...
... readasync(url).then(function (value) { throw new error("can't bar."); }, function (error) { // we only get here if `readasync` fails. }); to see why this is, consider the parallel between promises and try/catch. we are try-ing to execute readasync(): the error handler represents a catch for readasync(), while the value han...
Preferences - Archive of obsolete content
ollowing: 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 correct type (for example, getboolvalue() expects a value of type nsiprefbranch.pref_bool), and the preference is not locked, the method returns that value. if there's a value of the wrong type and the preference is not locked, an ns_error_unexpected
exception is thrown. if the preference is locked or if there is no value for that preference in the current tree, the get method checks the default tree. 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). otherwise an ns_error_unexpected excep...
... using prefhasuservalue() nsiprefbranch.prefhasuservalue(preference) checks whether the preference has been changed from the default value. if so, it will return true, otherwise false. in particular, when no default value exists for a preference, prefhasuservalue() indicates whether a preference exists. attempting to read a nonexistent preference using one of the get*pref methods will throw an
exception. using prefhasuservalue() lets you check if the preference exists before attempting to read it. for example: if (prefs.prefhasuservalue("mypref")) { alert(prefs.getcharpref("mypref")); } note that the getcharpref() call may throw error even if the preference exists, for example if it has a different type. as of firefox 54, you can pass a default value as the second argument to any get*pref ...
...ting to read it. for example: if (prefs.prefhasuservalue("mypref")) { alert(prefs.getcharpref("mypref")); } note that the getcharpref() call may throw error even if the preference exists, for example if it has a different type. as of firefox 54, you can pass a default value as the second argument to any get*pref method. the default value will be returned if the preference doesn't exist - no
exception will be thrown. so you could use, for instance: alert(prefs.getcharpref("mypref", "no value stored")); be careful with this technique because prior to firefox 54, the additional (default) value will be ignored and an
exception would still be thrown in this case. using preferences in extensions if you're writing your extension for one of the toolkit applications (firefox, thunderbird, nvu), y...
...sion for one of the toolkit applications (firefox, thunderbird, nvu), you should provide default values for your extension's preferences (see above for information on how to do it). it has the following benefits: you don't have to duplicate default values in various parts of your code. the code for reading preferences is simplified, since you don't need to worry about the get methods throwing
exceptions. javascript wrappers for preferences system there are a few javascript wrappers to make your life easier: http://mozilla.doslash.org/prefutils chrome://global/content/nsusersettings.js https://wiki.mozilla.org/labs/js_modules how to save preferences to save preferences into the default location: var prefservice = components.classes["@mozilla.org/preferences-service;1"] ...
Venkman Introduction - Archive of obsolete content
seen in figure 2. the following section describes these views and their use within the interface as a whole. getting acquainted with venkman's user interface toolbar the toolbar is located at the top of the debugger. the toolbar contains icons for stop, continue, step over, step into, step out, profile, and pretty print commands. these commands should be self explanatory, with the possible
exception of stop, which causes the debugger to stop when the next line of javascript is executed, and the profile button, which can be used to measure execution times for your scripts. when you enable profiling by clicking this button, a green checkmark appears next to the button and profile data for every function is collected, and can be saved by choosing save profile data as... from the profile menu. ...
...ate that the debugger will stop at the next instruction, but doesn't have anywhere to stop yet. this quick stop mode reflects a common scenario in javascript debugging, which is to inspect and debug scripts while they are running, as on a page where elements are moved around dynamically with dhtml. you can also use commands available in the debug menu and from the console to stop at errors or at
exceptions. the continue button to the right of the stop button dismisses the stop mode and specifies that scripts should be executed normally, without pausing as each statement is executed. the pretty print button toggles pretty print mode. while in pretty print mode, the contents of the source view will contain the decompiled source text for the selected function. this is the same text you would get fr...
...o close and re-open any objects you had open to see the change. properties that show up in a bold grey font are defined on an object from the prototype chain, and not on the actual object you are inspecting. if you would like to inspect the object's prototype and parent chains, check the "include ecma properties" menu item in the view's context menu. if a property shows up in a bold red font, an
exception occurred when venkman tried to read the value. the
exception object will appear as the value of the property. icon data type icon data type void (undefined) value null value boolean value string value integer value double value object value function value figure 9. type icons the column pi...
...iew, with the break and fbreak commands. the break command takes a file pattern and line number. any loaded file which matches the file pattern, and contains an executable line at the requested line number will have a breakpoint set. if no loaded files match the file pattern or line number, an error message is printed to the console and the command fails. the fbreak command is identical, with the
exception that if no files match the pattern or line, a "future breakpoint" is recorded. the next time a file is loaded that matches the pattern and line, a breakpoint will be set. in this way, fbreak allows one to set breakpoints in files that are not yet loaded, as well as set breakpoints that are triggered when a file is loaded. the interactive session view another basic view in venkman is the actua...
Implementation Status - Archive of obsolete content
292333; 3.4 extension module unsupported 300760; 3.5 mustunderstand module ...
...-range supported 4.4.17 xforms-out-of-range supported 4.4.18 xforms-scroll-first xforms-scroll-last supported 4.4.19 xforms-submit-done supported 4.5 error indications partial we don't support the xforms-version-
exception event, yet 4.5.1 xforms-binding-
exception supported 4.5.2 xforms-compute-
exception supported 4.5.3 xforms-link-error partial not yet generated by load. 333782; 4.5.4 xforms-link-
exception supported 4.5.5...
... 4.5.1 xforms-binding-
exception supported 4.5.2 xforms-compute-
exception supported 4.5.3 xforms-link-error partial not yet generated by load. ...
... 4.5.3 xforms-link-error partial not yet generated by load. ...
Beginning our React todo list - Learn web development
lg"> what needs to be done? ...
... <button type="button" classname="btn toggle-btn" aria-pressed="false"> <span classname="visually-hidden">show </span> <span>completed</span> <span classname="visually-hidden"> tasks</span> </button> </div> <h2 id="list-heading"> 3 tasks remaining </h2> <ul role="list" classname="todo-list stack-large stack-
exception" aria-labelledby="list-heading" > <li classname="todo stack-small"> <div classname="c-cb"> <input id="todo-0" type="checkbox" defaultchecked={true} /> <label classname="todo-label" htmlfor="todo-0"> eat </label> </div> <div classname="btn-group"> <button type="button" classname="btn">...
...ss will be hidden from sighted users and still available to screen reader users — this is because these words are not needed by sighted users; they are there to provide more information about what the button does for screenreader users that do not have the extra visual context to help them. further down, you can find our <ul> element: <ul role="list" classname="todo-list stack-large stack-
exception" aria-labelledby="list-heading" > the role attribute helps assistive technology explain what kind of element a tag represents. a <ul> is treated like a list by default, but the styles we're about to add will break that functionality. this role will restore the "list" meaning to the <ul> element. if you want to learn more about why this is necessary, you can check out scott o'hara’s article,...
... clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); white-space: nowrap; } [class*="stack"] > * { margin-top: 0; margin-bottom: 0; } .stack-small > * + * { margin-top: 1.25rem; } .stack-large > * + * { margin-top: 2.5rem; } @media screen and (min-width: 550px) { .stack-small > * + * { margin-top: 1.4rem; } .stack-large > * + * { margin-top: 2.8rem; } } .stack-
exception { margin-top: 1.2rem; } /* end global styles */ .todoapp { background: #fff; margin: 2rem 0 4rem 0; padding: 1rem; position: relative; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 2.5rem 5rem 0 rgba(0, 0, 0, 0.1); } @media screen and (min-width: 550px) { .todoapp { padding: 4rem; } } .todoapp > * { max-width: 50rem; margin-left: auto; margin-right: auto; } .todoapp > fo...
Storage access policy: Block cookies from trackers
oss visits to multiple first parties. specifically, 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. dom storage: localstorage: window.localstorage: read and write attempts throw a securityerror
exception. prior to firefox 70: window.localstorage is null. thus, attempts to read and write using this object will throw a typeerror
exception. sessionstorage: read and write attempts are permitted. indexeddb: attempting to access the indexeddb factory object throws a securityerror
exception. messaging and workers: broadcast channel: attempts to create a new broadcastchannel will throw a security...
... dom cache: calls to cachestorage will always reject with a securityerror. ...
... dom cache: calls to cachestorage will always reject with a securityerror. ...
... dom cache: calls to cachestorage will always reject with a securityerror. ...
NetUtil.jsm
be an nsiinputstream based object. asink the output stream to which to copy the data. this must be an nsioutputstream based object. acallback an optional function that will be called when the copy operation is completed. the callback receives a single parameter: the nsresult status code for the copy operation. return value returns the nsiasyncstreamcopier object that is handling the copy.
exceptions thrown this method throws an
exception with the message "must have a source and a sink" if either asource or asink is null. example this example writes a string to a file; it comes from the test suite for the netutil module. var file = cc["@mozilla.org/file/directory_service;1"]. getservice(ci.nsiproperties). get("tmpd", ci.nsifile); file.append("test-file.tmp"); file.c...
... may be specified as an nsiuri, nsifile, nsichannel, nsiinputstream or as a string specifying the url to open. acallback a function that will be called when the open operation is completed. the callback receives three parameters: the input stream containing the data, if any (implementing nsiinputstream), an nsresult status code for the open operation, and a reference to the nsirequest object.
exceptions thrown this method throws an
exception with the message "must have a source and a callback" if either asource or acallback is null. example this example shows the basic code consumers would need to implement to be correct. netutil.asyncfetch(channel, function(ainputstream, aresult) { // check that we had success. if (!components.issuccesscode(aresult)) { // handle error return; ...
...ional] aorigincharset, [optional] abaseuri ); parameters atarget specifies the target of the uri as either a uri string or (starting in gecko 2) as an nsifile. aorigincharset the optional character set for the uri. defaults to utf-8 if not provided. abaseuri the base uri for the spec, specified as an nsiuri. return value returns the nsiuri object representing the specified target.
exceptions thrown this method throws an
exception with the message "must have a non-null string spec or nsifile object" and result code ns_error_invalid_arg if aspec is null. readinputstreamtostring() reads a given number of bytes from an input stream, returning a string containing those bytes. this works even if some of those bytes are zeros, instead of terminating the string at the first zero byte. s...
...at all and the raw bytes will be returned. replacement a character with which to replace any invalid byte sequences in the input stream. if you don't specify a replacement character, any invalid sequences will result in ns_error_illegal_input being thrown. this option only has effect if charset is as well. return value a string containing the bytes read from the input stream.
exceptions thrown ns_error_invalid_arg the specified stream is not an nsiinputstream. ns_base_stream_would_block reading from the specified stream would block the calling thread, and the stream is in non-blocking mode. ns_error_failure there aren't at least acount bytes available to read from the stream. ns_error_illegal_input the input stream has invalid byte sequences, and no replacement charac...
Python binding for NSS
of this are the various callbacks which can be set and their parameters. thus each thread gets it own set of callbacks. many methods/functions provide sane default (keyword) parameters freeing the python programmer from having to specify all parameters yet allowing them to be overriden when necessary. error codes are never returned from methods/functions. python-nss follows the existing python
exception mechanism. any error reported by nss/nspr is converted into a python
exception and raised. the exact error code, error description, and often contextual error information will be present in the
exception object. enumerated constants used in the nss/nspr api's are available in the python module under the exact same name as they appear in the c header files of nss/nspr. convenience functions are ...
...ly shut it down, this is just failsafe. support was added for shutdown callbacks. ...
...ageobjectsigner nss.certusageusercertimport nss.certusageverifyca nss.certusageprotectedobjectsigner nss.certusagestatusresponder nss.certusageanyca nss.ocspmode_failureisverificationfailure nss.ocspmode_failureisnotaverificationfailure internal changes reimplement
exception handling nsprerror is now derived from standard
exception instead of environmenterror. it was never correct to derive from environmenterror but was difficult to implement a new subclassed
exception with it's own attributes, using environmenterror had been expedient. nsprerror now derived from standard
exception, provides: errno (numeric error code) st...
...ed test/run_tests to invoke full test suite. fix bug in test/setup_certs.py, hardcoded full path to libnssckbi.so was causing failures on 64-bit systems, just use the libnssckbi.so basename, modutil will find it on the standard search path. doc/examples/cert_dump.py uses new algorithmid class to dump signature algorithm doc/examples/ssl_example.py now can cleanly shutdown nss.
exception error messages now include pr error text if available. the following classes were replaced signaturealgorithm replaced by new class algorithmid the following classes were added algorithmid pkcs12decodeitem pkcs12decoder the following class methods were added pk11slot.authenticate() pk11slot.get_disabled_reason() pk...
Components.lastResult
components.lastresult returns the numeric nsresult code that was the result code of the last xpcom method called via xpconnect. introduction generally, components.lastresult is only useful for testing the result of xpcom methods that can return interesting 'success' codes. this is because failure result codes get converted by xpconnect into
exceptions that are thrown into the calling javascript method. most interfaces only return one success code -- ns_ok -- so components.lastresult is rarely necessary. 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. this is because many 'components' properties and methods are themselves im...
...var i = foo.bar(); switch (components.lastresult) { case components.results.ns_ok: // ns_ok is good! break; case 5: // do something with 5 here break; case 6: // do something with 6 here break; default: // this was a success code we did not expect. ...
... good! break; case 5: // do something with 5 here break; case 6: // do something with 6 here break; default: // this was a success code we did not expect. bad component! break; } // and so on.... ...
... break; case 6: // do something with 6 here break; default: // this was a success code we did not expect. bad component! break; } // and so on.... ...
Components.utils.reportError
if it is not a javascript error object, the parameter is converted to a string and reported as a new error. this means you can use components.utils.reporterror to report debugging messages to the error console, just like dump() can be used to print messages to the native console. ...
...if it is not a javascript error object, the parameter is converted to a string and reported as a new error. this means you can use components.utils.reporterror to report debugging messages to the error console, just like dump() can be used to print messages to the native console. ...
...e); consoleservice.logstringmessage("my component: " + amessage); } firefox 3: the error console will not display chrome errors by default. to show them, set the preference 'javascript.options.showinconsole' to true, or use nsconsoleservice instead to show a message. ...
...ent: " + amessage); } firefox 3: the error console will not display chrome errors by default. to show them, set the preference 'javascript.options.showinconsole' to true, or use nsconsoleservice instead to show a message. ...
nsIAccessibleEditableText
associatededitor nsieditor returns an editor associated with the accessible. read only. native code only! methods copytext() copies the text range into the clipboard. void copytext( in long startpos, in long endpos ); parameters startpos start offset of the text to be copied into the clipboard. endpos end offset of the text to be copied into the clipboard. ...
...d into the clipboard.
exceptions thrown ns_error_failure indicates the text cannot be copied into the clipboard. cuttext() deletes a range of text and copies it to the clipboard. void cuttext( in long startpos, in long endpos ); parameters startpos start offset of the text to be deleted and copied to clipboard. endpos end offset of the text to be copied into the clipboard.
exceptions thrown ns_error_failure indicates the text cannot be deleted or copied into the clipboard. deletetext() deletes a range of text. void deletetext( in long startpos, in long endpos ); parameters startpos start offset of the text to be deleted. endpos end offset of the text to be deleted.
exceptions thrown ns_error_failure indicates the text cannot be deleted. inserttext...
...arameters startpos start offset of the text to be deleted. endpos end offset of the text to be deleted.
exceptions thrown ns_error_failure indicates the text cannot be deleted. inserttext() inserts text at the specified position. void inserttext( in astring text, in long position ); parameters text text to be inserted. position the offset at which to insert the text.
exceptions thrown ns_error_failure indicates the text cannot be inserted. pastetext() pastes text from the clipboard. void pastetext( in long position ); parameters position the offset at which to insert the text from the system clipboard into the text represented by this object.
exceptions thrown ns_error_failure indicates the text cannot be pasted from the clipboard. setattributes...
...ets font styles, such as italic, bold, and so on. void setattributes( in long startpos, in long endpos, in nsisupports attributes ); parameters startpos the start index of the text whose attributes are modified. endpos the end index of the text whose attributes are modified. attributes the set of attributes that replaces the old list of attributes of the specified text portion.
exceptions thrown ns_error_not_implemented always. the method is not implemented. settextcontents() replaces the text represented by this object with the given text. void settextcontents( in astring text ); parameters text the text that will replace the old text.
exceptions thrown ns_error_failure indicates the text cannot be replaced. ...
nsIComponentManager
(see also nsifactory.createinstance.) void createinstance( in nscidref aclass, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the object instance that is being requested. adelegate the outer object used for aggregation. aiid the interface type to be returned. result the resulting interface pointer.
exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. createinstancebycontractid() creates an instance of the class specified by contractid. void createinstancebycontractid( in string acontractid, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters acontractid the contractid of the obje...
...by contractid. void createinstancebycontractid( in string acontractid, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters acontractid the contractid of the object instance that is being requested. adelegate the outer object used for aggregation. aiid the interface type to be returned. result the resulting interface pointer.
exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. getclassobject() returns the factory object for the class specified by classid. void getclassobject( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the factory that is being requested. aiid the interface type to ...
...at the specified class is not registered. getclassobject() returns the factory object for the class specified by classid. void getclassobject( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the factory that is being requested. aiid the interface type to be returned. result the resulting interface pointer.
exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. getclassobjectbycontractid() returns the factory object for the class specified by contractid. void getclassobjectbycontractid( in string acontractid, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters acontractid the contractid of the factory that is being re...
...ed. getclassobjectbycontractid() returns the factory object for the class specified by contractid. void getclassobjectbycontractid( in string acontractid, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters acontractid the contractid of the factory that is being requested. aiid the interface type to be returned. result the resulting interface pointer.
exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. removebootstrappedmanifestlocation() unregisters the chrome.manifest file previously registered with the addbootstrappedmanifestlocation() method. see addbootstrappedmanifestlocation() for details. void removebootstrappedmanifestlocation( in interface nsilocalfile alocation ); parameters ex...
nsICryptoHMAC
is method may be called any time after init() is called. this call resets the object to its pre-init state. acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. return value a hash of the data that was read by this object. this can be either binary data or base 64 encoded.
exceptions thrown ns_error_not_initialized if init() has not been called. init() initialize the hashing object. this method may be called multiple times with different algorithm types. warning: this approach is not fips compliant. note: this method must be called before any other method on this interface is called. void init( in unsigned long aalgorithm, in nsikeyobject akeyobject ); param...
...ype to be used. this value must be one of the above valid algorithm types. akeyobject object holding a key. to create the key object use for instance: var keyobject = components.classes["@mozilla.org/security/keyobjectfactory;1"] .getservice(components.interfaces.nsikeyobjectfactory) .keyfromstring(components.interfaces.nsikeyobject.hmac, rawkeydata);
exceptions thrown ns_error_invalid_arg if an unsupported algorithm type is passed. reset() reinitialize hmac context to be reused with the same settings (the key and hash algorithm) but on different set of data. void reset(); parameters none. update() void update( [const, array, size_is(alen)] in octet adata, in unsigned long alen ); parameters adata a buffer to calculate the hash ...
...rted algorithm type is passed. reset() reinitialize hmac context to be reused with the same settings (the key and hash algorithm) but on different set of data. void reset(); parameters none. update() void update( [const, array, size_is(alen)] in octet adata, in unsigned long alen ); parameters adata a buffer to calculate the hash over. alen the length of the buffer adata.
exceptions thrown ns_error_not_initialized if init() has not been called. updatefromstream() calculates and updates a new hash based on a given data stream. void updatefromstream( in nsiinputstream astream, in unsigned long alen ); parameters astream an input stream to read from. alen how much to read from the given astream. passing pr_uint32_max indicates that all data avai...
... if init() has not been called. updatefromstream() calculates and updates a new hash based on a given data stream. void updatefromstream( in nsiinputstream astream, in unsigned long alen ); parameters astream an input stream to read from. alen how much to read from the given astream. passing pr_uint32_max indicates that all data available will be used to update the hash.
exceptions thrown ns_error_not_initialized if init() has not been called. ns_error_not_available if the requested amount of data to be calculated into the hash is not available. ...
nsIHttpChannelInternal
ith this load even if normally they would not be. localaddress autf8string the local ip address to which the channel is bound, in the same format produced by pr_netaddrtostring(). this may be either an ipv4 or ipv6 address. note: if network address translation (nat) is in effect, this may not be the same address the remote host thinks it is talking to. ...
...see bug 534698 and bug 526207. read only. proxyinfo nsiproxyinfo get the proxy info in use by the channel. read only. ...
...y time the nsihttpactivityobserver.isactive attribute is false. see bug 534698 and bug 526207. read only. proxyinfo nsiproxyinfo get the proxy info in use by the channel. read only. obsolete since gecko 1.9 remoteaddress autf8string the ip address of the remote host to which this channel is bound, in the same format produced by pr_netaddrtostring(). ...
...see bug 534698 and bug 526207. read only. methods getrequestversion() gets the request's major and minor version numbers. ...
nsIHttpServer
* * @param prefix * the path on the server (beginning and ending with "/") which is to be * handled b...
...th "/") which is to be * handled by handler; this path must not include a query string or hash * component. all requests that start with this prefix will be directed to * the given handler. * @param handler * an object which will handle any requests for the given path, or null to * remove any existing handler; if while the server is running the handler * throws an
exception while responding to a request, an http 500 response * will be returned * @throws ns_error_invalid_arg * if path does not begin with a "/" or does not end with a "/" */ void registerprefixhandler(in string prefix, in nsihttprequesthandler handler); /** * registers a custom error page handler. * * @param code * the error code which is to be handled by handler *...
...*/ void registerprefixhandler(in string prefix, in nsihttprequesthandler handler); /** * registers a custom error page handler. * * @param code * the error code which is to be handled by handler * @param handler * an object which will handle any requests which generate the given status * code, or null to remove any existing handler. if the handler throws an *
exception during server operation, fallback is to the genericized error * handler (the x00 version), then to 500, using a user-defined error * handler if one exists or the server default handler otherwise. fallback * will never occur from a user-provided handler that throws to the same * handler as provided by the server, e.g. a throwing user 404 falls back to * 400, not a server-...
...n string extension, in string type); /** * sets the handler used to display the contents of a directory if * the directory contains no index page. * * @param handler * an object which will handle any requests for directories which * do not contain index pages, or null to reset to the default * index handler; if while the server is running the handler * throws an
exception while responding to a request, an http 500 * response will be returned. an nsifile corresponding to the * directory is available from the metadata object passed to the * handler, under the key "directory". */ void setindexhandler(in nsihttprequesthandler handler); /** represents the locations at which this server is reachable. */ readonly attribute nsihttpserveridentity ...
nsIInputStream
ative code only! unsigned long readsegments(in nswritesegmentfun awriter, in voidptr aclosure, in unsigned long acount); native code only! methods available() determine number of bytes available in the stream. in addition to the number of bytes available in the stream, this method also informs the caller of the current status of the stream. a stream that is closed will throw an
exception when this method is called. that enables the caller to know the condition of the stream before attempting to read from it. if a stream is at end-of-file, but not closed, then this method returns 0 bytes available. note: some nsiinputstream implementations automatically close() when end-of-file is reached; others do not. note: this method should not be used to determine the total size of a str...
... a stream, even if the stream corresponds to a local file. moreover, since a stream may make available more than 2^32 bytes of data, this method is incapable of expressing the entire size of the underlying data source. unsigned long available(); parameters none. return value number of bytes currently available in the stream, or pr_uint32_max if the size of the stream exceeds pr_uint32_max.
exceptions thrown <other-error> if the stream is closed due to some error condition. ns_base_stream_closed if the stream is closed normally. close() close the stream. this method causes subsequent calls to read() and readsegments() to return 0 bytes read to indicate end-of-file. note: the close method may be called more than once, but subsequent calls are ignored. void close(); parameters non...
...m into a buffer. unsigned long read( in charptr abuf, in unsigned long acount ); parameters abuf the buffer into which the data from the stream is copied. acount the size of the buffer, or the maximum number of bytes to copy from the stream. return value this method returns the number of bytes copied from the stream (may be less than acount). it returns 0 to indicate end-of-file.
exceptions thrown <other-error> on failure. ns_base_stream_would_block indicates that reading from the input stream would block the calling thread for indeterminate amount of time. this
exception may only be thrown if isnonblocking() returns true. native code only!readsegments this method provides direct access to the stream's internal buffer. note: a nsiinputstream is not required to implement t...
...ck function that may be called once for each buffer segment contained in the stream. see nswritesegmentfun for more details on this function. aclosure a parameter that is passed to awriter each time it is called. acount the maximum number of bytes to read from the stream. return value the number of bytes read from the stream (may be less than acount). it returns 0 to indicate end-of-file.
exceptions thrown <other-error> on failure. ns_error_not_implemented indicates that the stream does not have an internal buffer that can be accessed directly. ns_base_stream_would_block indicates that reading from the input stream would block the calling thread for indeterminate amount of time. this
exception may only be thrown if isnonblocking() returns true. example consume all data from an in...
nsILocalFile
appendrelativenativepath appends a relative, native character encoding, path to the current path of the nsilocalfile object. void appendrelativenativepath( in acstring relativefilepath ); parameters relativefilepath a native relative path. for security reasons, this cannot contain '..' or cannot start with a directory separator '/'. must be in the native file system character set.
exceptions thrown ns_error_file_unrecognized_path indicates that relativefilepath incorrectly begins with a path separator character or otherwise contains invalid characters. appendrelativepath() appends a relative native path to the current path of the nsilocalfile object. void appendrelativepath( in astring relativefilepath ); parameters relativefilepath a native relative path. for securi...
... begins with a path separator character or otherwise contains invalid characters. appendrelativepath() appends a relative native path to the current path of the nsilocalfile object. void appendrelativepath( in astring relativefilepath ); parameters relativefilepath a native relative path. for security reasons, this cannot contain '..' or cannot start with a directory separator '/' .
exceptions thrown ns_error_file_unrecognized_path indicates that relativefilepath incorrectly begins with a path separator character or otherwise contains invalid characters. getrelativedescriptor() returns a relative file path in an opaque, cross platform format. it is therefore not a native path. acstring getrelativedescriptor( in nsilocalfile fromfile ); parameters fromfile the file from...
...e afile ); parameters afile the file this becomes equivalent to. initwithnativepath() used to set the full path that this nsilocalfile references. all current settings will be reset. void initwithnativepath( in acstring filepath ); parameters filepath a string that specifies a platform-specific, full path to a file or directory. must be in the native file system character set.
exceptions thrown ns_error_file_unrecognized_path indicates that filepath is not an absolute file path or that it contains characters that are invalid for the filesystem. initwithpath() used to set the full path that this nsilocalfile references. all current settings will be reset. void initwithpath( in astring filepath ); parameters filepath a string that specifies a platform-specific, ful...
...nized_path indicates that filepath is not an absolute file path or that it contains characters that are invalid for the filesystem. initwithpath() used to set the full path that this nsilocalfile references. all current settings will be reset. void initwithpath( in astring filepath ); parameters filepath a string that specifies a platform-specific, full path to a file or directory.
exceptions thrown ns_error_file_unrecognized_path indicates that filepath is not an absolute file path or that it contains characters that are invalid for the filesystem. launch() requests that the operating system attempt to open this file. void launch(); parameters none. native code only! load returns the result of pr_loadlibrary() on the file. the caller is responsible for calling pr_...
nsIServiceManager
d of the service. unlike createinstance, this will always return the same object each time it is called with the same arguments. void getservice( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the service that is being requested. aiid the interface type to be returned. result the resulting interface pointer.
exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. getservicebycontractid() this method returns a reference to a particular xpcom service given the contractid of the service. void getservicebycontractid( in string acontractid, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters acontractid the contractid of the...
...tid() this method returns a reference to a particular xpcom service given the contractid of the service. void getservicebycontractid( in string acontractid, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters acontractid the contractid of the service that is being requested. aiid the interface type to be returned. result the resulting interface pointer.
exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. isserviceinstantiated() this method tests whether or not a xpcom service, identified by classid, has been instantiated. boolean isserviceinstantiated( in nscidref aclass, in nsiidref aiid ); parameters aclass the classid of the service that is being tested. aiid the interface type to ...
...class is not registered. isserviceinstantiated() this method tests whether or not a xpcom service, identified by classid, has been instantiated. boolean isserviceinstantiated( in nscidref aclass, in nsiidref aiid ); parameters aclass the classid of the service that is being tested. aiid the interface type to be tested. return value true if the service has already been created.
exceptions thrown ns_error_service_not_available indicates that the service hasn't been instantiated. ns_nointerface indicates that the iid given isn't supported. isserviceinstantiatedbycontractid() this method tests whether or not a xpcom service, identified by contractid, has been instantiated. boolean isserviceinstantiatedbycontractid( in string acontractid, in nsiidref aiid ); parameter...
...stantiatedbycontractid() this method tests whether or not a xpcom service, identified by contractid, has been instantiated. boolean isserviceinstantiatedbycontractid( in string acontractid, in nsiidref aiid ); parameters acontractid the contractid of the service that is being tested. aiid the interface type to be tested. return value true if the service has already been created.
exceptions thrown ns_error_service_not_available indicates that the service hasn't been instantiated. ns_nointerface indicates that the iid given isn't supported. remarks the service manager depends on the repository to find and instantiate factories to obtain services. because services are instantiated lazily, methods are provided to test whether or not a service has already been instantiated. ...
XPCOM Interface Reference
eporternsicryptohmacnsicryptohashnsicurrentcharsetlistenernsicyclecollectorlistenernsidbchangelistenernsidbfolderinfonsidnslistenernsidnsrecordnsidnsrequestnsidnsservicensidomcanvasrenderingcontext2dnsidomchromewindownsidomclientrectnsidomdesktopnotificationnsidomdesktopnotificationcenternsidomelementnsidomeventnsidomeventgroupnsidomeventlistenernsidomeventtargetnsidomfilensidomfileerrornsidomfile
exceptionnsidomfilelistnsidomfilereadernsidomfontfacensidomfontfacelistnsidomgeogeolocationnsidomgeopositionnsidomgeopositionaddressnsidomgeopositioncallbacknsidomgeopositioncoordsnsidomgeopositionerrornsidomgeopositionerrorcallbacknsidomgeopositionoptionsnsidomglobalpropertyinitializernsidomhtmlaudioelementnsidomhtmlformelementnsidomhtmlmediaelementnsidomhtmlsourceelementnsidomhtmltimerangesnsidomjswindow...
...idomnavigatordesktopnotificationnsidomnodensidomofflineresourcelistnsidomorientationeventnsidomparsernsidomprogresseventnsidomserializernsidomsimplegestureeventnsidomstoragensidomstorage2nsidomstorageeventobsoletensidomstorageitemnsidomstoragelistnsidomstoragemanagernsidomstoragewindownsidomuserdatahandlernsidomwindownsidomwindow2nsidomwindowinternalnsidomwindowutilsnsidomxpathevaluatornsidomxpath
exceptionnsidomxpathexpressionnsidomxpathresultnsidomxulcontrolelementnsidomxulelementnsidomxullabeledcontrolelementnsidomxulselectcontrolelementnsidomxulselectcontrolitemelementnsidatasignatureverifiernsidebugnsidebug2nsidevicemotionnsidevicemotiondatansidevicemotionlistenernsidialogcreatornsidialogparamblocknsidictionarynsidirindexnsidirindexlistenernsidirindexparsernsidirectoryenumeratornsidirectoryiter...
...sslistenernsidownloadernsidragdrophandlernsidragservicensidragsessionnsidroppedlinkhandlernsidroppedlinkitemnsidynamiccontainernsieditornsieditorboxobjectnsieditordocshellnsieditorimesupportnsieditorloggingnsieditormailsupportnsieditorobservernsieditorspellchecknsieffectivetldservicensienumeratornsienvironmentnsierrorservicensieventlistenerinfonsieventlistenerservicensieventsourcensieventtargetnsi
exceptionnsiextensionmanagernsiexternalhelperappservicensiexternalprotocolservicensiexternalurlhandlerservicensiftpchannelnsiftpeventsinknsifactorynsifavicondatacallbacknsifaviconservicensifeednsifeedcontainernsifeedelementbasensifeedentrynsifeedgeneratornsifeedpersonnsifeedprocessornsifeedprogresslistenernsifeedresultnsifeedresultlistenernsifeedtextconstructnsifilensifileinputstreamnsifileoutputstreamnsif...
...inapphelpernsiwintaskbarnsiwindowcreatornsiwindowmediatornsiwindowwatchernsiwindowsregkeynsiwindowsshellservicensiworkernsiworkerfactorynsiworkerglobalscopensiworkermessageeventnsiworkermessageportnsiworkerscopensiwritablepropertybagnsiwritablepropertybag2nsixformsmodelelementnsixformsnsinstanceelementnsixformsnsmodelelementnsixmlhttprequestnsixmlhttprequesteventtargetnsixmlhttprequestuploadnsixpc
exceptionnsixpcscriptablensixpconnectnsixslt
exceptionnsixsltprocessornsixsltprocessorobsoletensixulappinfonsixulbrowserwindownsixulbuilderlistenernsixulruntimensixulsortservicensixultemplatebuildernsixultemplatequeryprocessornsixultemplateresultnsixulwindownsixmlrpcclientnsixmlrpcfaultnsizipentrynsizipreadernsizipreadercachensizipwriternsmsgfilterfileattribvaluensmsgfolderflagtypensmsgjunkstatusnsmsgkeynsm...
ArrayType
pe[ length] ); parameters type: it represents the type of the elements or variable which is going to be present in an array length optional it denotes the number of entries present in an array or the number of elements that an array should contain. if you don't specify this parameter, the array's length is unspecified. return value a ctype represents the newly declared array type.
exceptions thrown typeerror type is not a ctype, or type.size is undefined.if the length is specifed but if it is not a valid one,then it is also thrown rangeerror the size of the resulting array can't be represented as both a size_t and as a javascript number. properties property type description elementtype ctype the data type of the elements in an array type. read...
...type array([n]) string tosource() string tostring() arraytype cdata syntax cdata sized_arraytype(); cdata unsized_arraytype(length); sized_arraytype and unsized_arraytype are arraytype ctype. parameters length the number of entries the array type should be able to contain. only for unsized arraytype. return value a cdata representing the newly allocated array.
exceptions thrown typeerror length is not provided for unsized array, or is provided for sized array. arraytype cdata properties property type description length number the length of the array. read only. in addition, each element in the array can be referenced by index using standard bracket notation, such as myarray[index]. properties inherited from cdata ...
...tion, such as myarray[index]. properties inherited from cdata property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror
exception if the value can't be converted. 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 th...
...ement() returns a new cdata object of the appropriate pointer type, whose value points to the specified array element on which the method was called. cdata addressofelement( idx ); parameters idx a numeric value indicating the offset into the array of the element just to return a pointer. if this value isn't a valid javascript number that's also a valid index into the array, a typeerror
exception is thrown. return value a new cdata object pointing to the specified element. the type of the returned object will be determined by ctypes.pointertype(thearraytype.constructor.elementtype)). see also ctype cdata type conversion ...
Int64
a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a hexadecimal number. the string is then converted into the corresponding 64-bit integer value. you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number. return value a new object representing the specified value.
exceptions thrown typeerror the specified value cannot be converted into a 64-bit integer. either it's not a number, string, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. this will also be thrown if the source value is a floating-point number that can't be precisely represented as a 64-bit integer. me...
... number hi(a); int64 join(high, low); number lo(a); string tosource(); string tostring([radix]); methods compare() compares two 64-bit integer values. number compare( a, b ); parameters a the first value to compare. b the second value to compare. return value the returned value is: -1 if a < b, 0 if a == b, and 1 if a > b. ...
... if a < b, 0 if a == b, and 1 if a > b.
exceptions thrown typeerror one or both of the specified values is not a 64-bit integer (either signed or unsigned). hi() returns the high 32 bits of the specified value. number hi( num ); parameters num the value whose high 32 bits are to be returned. return value the high 32 bits of num are returned. this is essentially num >> 32.
exceptions thrown typeerror num is not a 64-bit integer object. lo() returns the low 32 bits of the specified value. number lo( num ); parameters num the int64 value whose low 32 bits are to be returned. return value the low 32 bits of num are returned. this is essentially num & 0xffffffff.
exceptions thrown typeerror num is not a 64-bit integer object. join() creates a 64-bit in...
...() creates a 64-bit integer object whose value is constructed using the specified high and low order 32-bit values. int64 join( high, low ); parameters high the high-order 32 bits of the value to create. low the low-order 32 bits of the value to create. return value a new 64-bit integer object comprised of the two values merged together. the returned value is (high << 32) + low.
exceptions thrown typeerror one or both of the specified numbers is not a javascript number with an integral value. tosource() this method is for internal debugging use only. warning: do not rely on the value returned by this method, as it's subject to change at any time, depending on the debugging needs of the developers. tostring() returns a string representation of the object's numeric value. ...
StructType
of field descriptors, describing all the entries in the structure. if this isn't specified, the structure is considered opaque and you can't access its contents directly. you can call the resulting type's define() method to assign it a non-opaque type later. see opaque structures for further explanation and an example. return value a ctype object describing the newly created struct data type.
exceptions thrown typeerror the name is not a string, or one or more of the fields does not have a defined size. rangeerror the size of the structure, in bytes, cannot be represented both as a size_t and as a javascript number. describing fields the fields array is comprised of field descriptors, one for each field in the structure. each field descriptor contains the field's name and its type, suc...
...ostring() methods define() defines a previously declared opaque type's fields. this lets you convert an opaque structure type into a defined structure type. define( fields ); parameters fields a field specification, as described above. structtype cdata syntax cdata structtype(); structtype is structtype ctype. return value a cdata representing the newly allocated struct.
exceptions thrown error fields are not yet defined. structtype cdata properties every struct object has a getter and a setter for each member field of the structure. properties inherited from cdata property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an u...
...ember field of the structure. properties inherited from cdata property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror
exception if the value can't be converted. 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 ...
...ose value points to the specified field of the structure on which the method was called. see working with strings for more information on how to convert strings. cdata addressoffield( name ); parameters name the name of the field whose address is to be returned. return value a new cdata object of the appropriate pointer type, whose value points to the contents of the specified field.
exceptions thrown typeerror name is not a javascript string, or doesn't name a member field of the structure. see also ctype cdata type conversion ...
UInt64
a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a hexadecimal number. the string is then converted into the corresponding 64-bit integer value. you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number. return value a new object representing the specified value.
exceptions thrown typeerror the specified value cannot be converted into a 64-bit integer. either it's not a number, string, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. this will also be thrown if the source value is a floating-point number that can't be precisely represented as a 64-bit integer. me...
... b); number hi(a); uint64 join(high, low); number lo(a); string tosource(); string tostring([radix]); methods compare() compares two 64-bit integer values. number compare( a, b ); parameters a the first value to compare. b the second value to compare. return value the returned value is -1 if a < b, 0 if a == b, and 1 if a > b. ...
...-1 if a < b, 0 if a == b, and 1 if a > b.
exceptions thrown typeerror one or both of the specified values is not a 64-bit integer (either signed or unsigned). hi() returns the high 32 bits of the specified value. number hi( num ); parameters num the value whose high 32 bits are to be returned. return value the high 32 bits of num are returned. this is essentially num >> 32.
exceptions thrown typeerror num is not a 64-bit integer object. lo() returns the low 32 bits of the specified value. number lo( num ); parameters num the int64 value whose low 32 bits are to be returned. return value the low 32 bits of num are returned. this is essentially num & 0xffffffff.
exceptions thrown typeerror num is not a 64-bit integer object. join() creates a 64-bi...
...n() creates a 64-bit integer object with a value constructed using the specified high and low order 32-bit values. uint64 join( high, low ); parameters high the high-order 32 bits of the value to create. low the low-order 32 bits of the value to create. return value a new 64-bit integer object comprised of the two values merged together. the returned value is (high << 32) + low.
exceptions thrown typeerror one or both of the specified numbers is not a javascript number with an integral value. tosource() this method is for internal debugging use only. warning: do not rely on the value returned by this method, as it's subject to change at any time, depending on the debugging needs of the developers. tostring() returns a string representation of the object's numeric val...
Element.classList - Web APIs
ll compliance (coverage) for all standard methods and properties of element.prototype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. ...
...coverage) for all standard methods and properties of element.prototype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. ...
...implement the barebones domtokenlist livelyness polyfill if (typeof domtoken...
...amespace pollution if(!window.dom
exception) (dom
exception = function(reason){this.message = reason}).prototype = new error; var wsre = /[\11\12\14\15\40]/, wsindex = 0, checkifvalidclasslistentry = function(o, v) { if (v === "") throw new dom
exception( "failed to execute '" + o + "' on 'domtokenlist': the token provided must not be empty." ); if((wsindex=v.search(wsre))!==-1) throw new dom
exception("failed to execute '"+o+"' on 'domtokenlist': " + "the token provided ('"+v[wsindex]+"') contains html space characters, which are not valid in tokens."); } // 2. implement the barebones domtokenlist livelyness polyfill if (typeof domtokenlist !== "function") (function(window){ var document = window.document, object = window.object, hasownprop = object.prototype.hasownproperty; var de...
FileSystemDirectoryEntry - Web APIs
support yesgetdirectory experimentalchrome full support 8edge full support 79firefox full support 50notes full support 50notes notes in firefox, the errorcallback's input parameter is a dom
exception rather than a fileerror object.ie no support noopera no support nosafari full support 11.1webview android full support ≤37chrome android full support 18firefox android ...
...t 11.1webview android full support ≤37chrome android full support 18firefox android full support 50notes full support 50notes notes in firefox, the errorcallback's input parameter is a dom
exception rather than a fileerror object.opera android no support nosafari ios full support 11.3samsung internet android full support yesgetfile experimentalchrome full support 8edge full support ...
... full support yesgetfile experimentalchrome full support 8edge full support 79firefox full support 50notes full support 50notes notes in firefox, the errorcallback's input parameter is a dom
exception rather than a fileerror object.ie no support noopera no support nosafari full support 11.1webview android full support ≤37chrome android full support 18firefox android ...
...t 11.1webview android full support ≤37chrome android full support 18firefox android full support 50notes full support 50notes notes in firefox, the errorcallback's input parameter is a dom
exception rather than a fileerror object.opera android no support nosafari ios full support 11.3samsung internet android full support yesremoverecursively deprecatednon-standardchrome full support 8edge full suppo...
HTMLInputElement - Web APIs
string: returns / sets the element's max attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value. maxlength long: returns / sets the element's maxlength attribute, containing the maximum number of characters (in unicode code points) that the value can have. (if you set this to a negative number, an
exception will be thrown.) min string: returns / sets the element's min attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum (max attribute) value. minlength long: returns / sets the element's minlength attribute, containing the minimum number of characters (in unicode code points) that the value can have. (if you s...
... string: returns / sets the element's min attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum (max attribute) value. minlength long: returns / sets the element's minlength attribute, containing the minimum number of characters (in unicode code points) that the value can have. (if you set this to a negative number, an
exception will be thrown.) pattern string: returns / sets the element's pattern attribute, containing a regular expression that the control's value is checked against. use the title attribute to describe the pattern to help the user. this attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. placeholder string: returns / ...
... constraints. reportvalidity() runs the checkvalidity() method, and if it returns false (for an invalid input or no pattern attribute provided), then it reports to the user that the input is invalid in the same manner as if you submitted a form. htmlinputelement.stepdown() decrements the value by (step * n), where n defaults to 1 if not specified. ...
... htmlinputelement.mozgetfilenamearray() returns an array of all the file names from the input. ...
IDBTransactionSync - Web APIs
onable. it may however be reintroduced in the future if there is enough demand from web developers. the idbtransactionsync interface of the indexeddb api provides a synchronous transaction on a database. when an application creates an idbtransactionsync object, it blocks until the browser is able to reserve the require database objects. method overview void abort() raises (idbdatabase
exception); void commit() raises (idbdatabase
exception); idbobjectstoresync objectstore(in domstring name) raises (idbdatabase
exception); attributes attribute type description db idbdatabasesync the database connection that this transaction is associated with. static boolean if true, this transaction is static; if false, this trans...
...tic boolean if true, this transaction is static; if false, this transaction is dynamic. methods abort() call this method to signal a need to cancel the effects of the operations performed by this transaction. when this method is called, the browser ignores all the changes performed to the objects of this database since this transaction was created. void abort( ) raises (idbdatabase
exception);
exceptions this method can raise an idbdatabase
exception with the following code: non_transient_err if this transaction has already been committed or aborted. 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 trans...
...ception with the following code: non_transient_err if this transaction has already been committed or aborted. 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. void commit( ) raises (idbdatabase
exception);
exceptions this method can raise an idbdatabase
exception with the following codes: non_transient_err if this transaction has already been committed or aborted. recoverable_err if this transaction's scope is dynamic, and the browser cannot commit all of the changes due to another transaction. objectstore() returns an object store that has already been added to the scope of this trans...
...codes: non_transient_err if this transaction has already been committed or aborted. recoverable_err if this transaction's scope is dynamic, and the browser cannot commit all of the changes due to another transaction. objectstore() returns an object store that has already been added to the scope of this transaction. idbobjectstoresync objectstore( in domstring name ) raises (idbdatabase
exception); parameters name the name of the requested object store. returns idbobjectstoresync an object for accessing the requested object store.
exceptions the method can raise an idbdatabase
exception with the following code: not_found_err if the requested object store is not in this transaction's scope. ...
PaymentResponse.retry() - Web APIs
f the user chose to pay by credit card using the basic-card payment method, this is a basiccarderrors object. shippingaddress optional an addresserrors object which contains error messages for any of the fields in the shipping address that failed validation. return value a promise which is resolved when the payment is successfully completed. the promise is rejected with an appropriate
exception value if the payment fails again. typically 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. the loop exits only when the user either cancels the payment request or the reques...
...ith a value of "fail" to indicate failure. if the response's data is valid and acceptable, call complete("success") to finalize the payment and proces it. if show() is rejected, the payment request failed, usually because either there's already one being processed, because the user agent doesn't support any of the specified payment methods, or because of a security issue. see the list of
exceptions for show() for further details. call complete("fail") to close the payment request. async function handlepayment() { const payrequest = new paymentrequest(methoddata, details, options); try { let payresponse = await payrequest.show(); while (payresponse has errors) { /* let the user edit the payment information, wait until they submit */ await response.retry(...
...} async function dopaymentrequest() { const request = new paymentrequest(methoddata, details, options); const response = await request.show(); await recursivevalidate(request, response); await response.complete("success"); } // keep validating until the data looks good! async function re...
...ils, options); try { let payresponse = await payrequest.show(); while (payresponse has errors) { /* let the user edit the payment information, wait until they submit */ await response.retry(); } await payresponse.complete("success"); } catch(err) { /* handle the
exception */ } } examples try { await paymentrequest.retry(errorfields); } catch (dom
exception err) { ... } async function dopaymentrequest() { const request = new paymentrequest(methoddata, details, options); const response = await request.show(); await recursivevalidate(request, response); await response.complete("success"); } // keep validating until the data looks good! async function recursivevalidate(request, response) { const promisestofixthings = []; const errors = aw...
Web APIs
clients clipboard clipboardevent clipboarditem closeevent comment compositionevent constantsourcenode constrainboolean constraindomstring constraindouble constrainulong contentindex contentindexevent convolvernode countqueuingstrategy crashreportbody credential credentialscontainer crypto cryptokey cryptokeypair customelementregistry customevent d domconfiguration domerror dom
exception domhighrestimestamp domimplementation domimplementationlist domlocator dommatrix dommatrixreadonly domobject domparser dompoint dompointinit dompointreadonly domquad domrect domrectreadonly domstring domstringlist domstringmap domtimestamp domtokenlist domuserdata datatransfer datatransferitem datatransferitemlist dedicatedworkerglobalscope delaynode deprecationreportbody deviceligh...
...xt_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic eckeygenparams eckeyimportparams ecdhkeyderiveparams ecdsaparams effecttiming element elementcssinlinestyle elementtraversal errorevent event eventlistener eventsource eventtarget extendableevent extendablemessageevent f featurepolicy federatedcredential fetchevent file fileentrysync fileerror file
exception filelist filereader filereadersync filerequest filesystem filesystemdirectoryentry filesystemdirectoryreader filesystementry filesystementrysync filesystemfileentry filesystemflags filesystemsync focusevent fontface fontfaceset fontfacesetloadevent formdata formdataentryvalue formdataevent fullscreenoptions g gainnode gamepad gamepadbutton gamepadevent gamepadhapticactu...
...nt htmltablecellelement htmltablecolelement htmltableelement htmltablerowelement htmltablesectionelement htmltemplateelement htmltextareaelement htmltimeelement htmltitleelement htmltrackelement htmlulistelement htmlunknownelement htmlvideoelement hashchangeevent headers history hkdfparams hmacimportparams hmackeygenparams i idbcursor idbcursorsync idbcursorwithvalue idbdatabase idbdatabase
exception idbdatabasesync idbenvironment idbenvironmentsync idbfactory idbfactorysync idbindex idbindexsync idbkeyrange idblocaleawarekeyrange idbmutablefile idbobjectstore idbobjectstoresync idbopendbrequest idbrequest idbtransaction idbtransactionsync idbversionchangeevent idbversionchangerequest iirfilternode idledeadline imagebitmap imagebitmaprenderingcontext imagecaptu...
...exarrayobject webkitcssmatrix websocket wheelevent window windowclient windoweventhandlers windoworworkerglobalscope worker workerglobalscope workerlocation workernavigator worklet writablestream writablestreamdefaultcontroller writablestreamdefaultwriter x xdomainrequest xmldocument xmlhttprequest xmlhttprequesteventtarget xmlhttprequestresponsetype xmlserializer xpathevaluator xpath
exception xpathexpression xpathnsresolver xpathresult xrboundedreferencespace xrenvironmentblendmode xreye xrframe xrframerequestcallback xrhandedness xrinputsource xrinputsourcearray xrinputsourceevent xrinputsourceeventinit xrinputsourceschangeevent xrinputsourceschangeeventinit xrpermissiondescriptor xrpermissionstatus xrpose xrreferencespace xrreferencespaceevent xrreferencespaceeventinit xrreference...
HTTP Index - HTTP
ader, header the content-range response http header indicates where in a full body message a partial message belongs. 76 content-security-policy csp, content security policy, http, reference, security, header the http content-security-policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. with a few
exceptions, policies mostly involve specifying server origins and script endpoints. this helps guard against cross-site scripting attacks (xss). 77 csp: base-uri csp, directive, document directive, http, security the http content-security-policy base-uri directive restricts the urls which can be used in a document's <base> element. if this value is absent, then any uri is allowed. if t...
...'s contents. 129 feature-policy: document-domain directive, experimental, feature policy, feature-policy, http, reference, document-domain, header the http feature-policy header document-domain directive controls whether the current document is allowed to set document.domain. when this policy is enabled, attempting to set document.domain will fail and cause a securityerror dom
exception to be be thrown. 130 feature-policy: encrypted-media directive, eme, feature policy, feature-policy, http, reference the http feature-policy header encrypted-media directive controls whether the current document is allowed to use the encrypted media extensions api (eme). when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject w...
... thrown. 130 feature-policy: encrypted-media directive, eme, feature policy, feature-policy, http, reference the http feature-policy header encrypted-media directive controls whether the current document is allowed to use the encrypted media extensions api (eme). when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a dom
exception. 131 feature-policy: fullscreen feature policy, feature-policy, http, fullscreen, header the http feature-policy header fullscreen directive controls whether the current document is allowed to use element.requestfullscreen(). when this policy is enabled, the returned promise rejects with a typeerror. 132 feature-policy: geolocation feature policy, feature-poli...
...mediadevices.getusermedia() will reject with a notallowederror. 138 feature-policy: midi directive, feature policy, feature-policy, http, midi, reference the http feature-policy header midi directive controls whether the current document is allowed to use the web midi api. when this policy is enabled, the promise returned by navigator.requestmidiaccess() will reject with a dom
exception. 139 feature-policy: oversized-images directive, feature-policy, http, reference the http feature-policy header oversized-images directive controls whether the current document is allowed to download and display large images. 140 feature-policy: payment directive, feature policy, feature-policy, http, payment request api, payments api, reference the http ...
Error - JavaScript
evalerror creates an instance representing an error that occurs regarding the global function eval(). internalerror creates an instance representing an error that occurs when an internal error in the javascript engine is thrown. e.g. ...
... evalerror creates an instance representing an error that occurs regarding the global function eval(). internalerror creates an instance representing an error that occurs when an internal error in the javascript engine is thrown. e.g. ...
... evalerror creates an instance representing an error that occurs regarding the global function eval(). internalerror creates an instance representing an error that occurs when an internal error in the javascript engine is thrown. e.g. "too much recursion". ...
...d: try { foo.bar() } catch (e) { if (e instanceof evalerror) { console.error(e.name + ': ' + e.message) } else if (e instanceof rangeerror) { console.error(e.name + ': ' + e.message) } // ... etc } custom error types you might want to define your own error types deriving from error to be able to throw new myerror() and use instanceof myerror to check the kind of error in the
exception handler. this results in cleaner and more consistent error handling code. see "what's a good way to extend error in javascript?" on stackoverflow for an in-depth discussion. es6 custom error class versions of babel prior to 7 can handle customerror class methods, but only when they are declared with object.defineproperty(). otherwise, old versions of babel and other transpilers will not cor...
passwords - Archive of obsolete content
namefield string the value of the name attribute for the user name input field in a form. passwordfield string the value of the name attribute for the password input field in a form. onerror function the callback function that is called if the function failed. the callback is passed an error containing a reason of a failure: this is an nsi
exception object. store(options) this function is used to store a credential in the password manager. it takes an options object as an argument: this contains all the properties for the new credential. as different sorts of credentials contain different properties, the appropriate options differ depending on the sort of credential being stored. to store an add-on credential: require("sdk/pa...
...e name attribute for the password input in a form. omitted for add-on credentials and http authentication credentials. oncomplete function the callback function that is called once the function completes successfully. onerror function the callback function that is called if the function failed. the callback is passed an error argument: this is an nsi
exception object. remove(options) removes a stored credential. you supply it all the properties of the credential to remove, along with optional oncomplete and onerror callbacks. because you must supply all the credential's properties, it may be convenient to call search first, and use its output as the input to remove. for example, to remove all of joe's stored credentials: require("sdk/pass...
...me attribute for the password input in a form. omitted for add-on credentials and http authentication credentials. oncomplete function the callback function that is called once the function has completed successfully. onerror function the callback function that is called if the function failed. the callback is passed an error argument: this is an nsi
exception object. ...
console/traceback - Archive of obsolete content
ts a stack frame and has the following keys: filename the name of the file that the stack frame takes place in. lineno the line number is being executed at the stack frame. funcname the name of the function being executed at the stack frame, or null if the function is anonymous or the stack frame is being executed in a top-level script or module. see nsi
exception for more information. globals functions from
exception(
exception) attempts to extract the traceback from
exception. parameters
exception :
exception exception where
exception is an nsi
exception. returns traceback : json representation of the traceback or null if not found. get() returns json : returns the json representation of the stack at the point that this function is called. form...
...re information. globals functions from
exception(
exception) attempts to extract the traceback from
exception. parameters
exception :
exception exception where
exception is an nsi
exception. returns traceback : json representation of the traceback or null if not found. get() returns json : returns the json representation of the stack at the point that this function is called. format(tbor
exception) given a json representation of the stack or an
exception instance, returns a formatted plain text representation of it, similar to python's formatted stack tracebacks. if no argument is provided, the stack at the point this function is called is used. ...
...) returns json : returns the json representation of the stack at the point that this function is called. format(tbor
exception) given a json representation of the stack or an
exception instance, returns a formatted plain text representation of it, similar to python's formatted stack tracebacks. ...
io/text-streams - Archive of obsolete content
ring text will be written to outputstream using the character encoding named by this value. if not specified, "utf-8" is assumed. see nsicharsetconvertermanager.idl for documentation on how to determine other valid values for this. textreader methods close() closes both the stream and its backing stream. read(numchars) reads and returns a string from the stream. if the stream is closed, an
exception is thrown. parameters numchars : number the number of characters to read. if not given, the remainder of the stream is read. returns string : the string read. if the stream is at the end, the empty string is returned. properties closed true if the stream is closed. textwriter methods close() flushes the backing stream's buffer and closes both the stream and the backing stream. if the ...
...hars : number the number of characters to read. if not given, the remainder of the stream is read. returns string : the string read. if the stream is at the end, the empty string is returned. properties closed true if the stream is closed. textwriter methods close() flushes the backing stream's buffer and closes both the stream and the backing stream. if the stream is already closed, an
exception is thrown. flush() flushes the backing stream's buffer. write(str) writes a string to the stream. if the stream is closed, an
exception is thrown. parameters str : string the string to write. writeasync(str, callback) writes a string on a background thread. after the write completes, the backing stream's buffer is flushed, and both the stream and the backing stream are closed, also on th...
... parameters str : string the string to write. callback : callback callback, if given, must be a function. it's called as callback(error) when the write completes. error is an error object or undefined if there was no error. ...
XPCOM Objects - Archive of obsolete content
have to worry about queryinterface. but in this case we need to change the interface to nsiprefbranch2, which is the one that includes the method that adds a preference observer. then we change it back, because after that we only need to get and set preferences, and those methods are in nsiprefbranch. trying to access methods or attributes without having the right interface set will result in an
exception being thrown. passing parameters passing parameters to xpcom methods is no different from other js objects, with some
exceptions. in general, you can rely on javascript's ability to transform values to the correct type, but it's usually best to pass the right type in the first place. this section is a quick guide on how to read xpcom documentation, which basically amounts to understanding the s...
...cess constants through a reference of the component, or directly from the interface: // these are equivalent. max = ci.xsihellocounter.max_count; max = counterreference.max_count; the implementation file, xshellocounter.js, is much longer. we'll analyze it piece by piece. const cc = components.classes; const ci = components.interfaces; const cr = components.results; const ce = components.
exception; you should be familiar with this already, although there are a couple of additions, components.results and components.
exception. they'll be used further ahead. const class_id = components.id("{37ed5d2a-e223-4386-9854-b64fd38932bf}"); const class_name = "hello world counter"; const contract_id = "@xulschool.com/counter;1"; these constants are used at the bottom, in the component registra...
...tes must have the same names as their idl counterparts, and that the queryinterface method is implemented: queryinterface : function(aiid) { if (!aiid.equals(ci.xsihellocounter) && !aiid.equals(ci.nsisupports)) { throw cr.ns_error_no_interface; } return this; } the method is very simple, it validates that the caller is requesting a supported interface, otherwise it throws an
exception. the rest of the code looks long and complicated, but it is pretty much the same for all components, so you shouldn't worry too much about it. all you have to do to use it in other components is copy it and change some names. the purpose of this code is to register the component so that you can get references to it just like all other firefox components. it is better read from bottom to top. ...
Index of archived content - Archive of obsolete content
vements in firefox 3 download manager preferences drag and drop drag and drop example drag and drop javascript wrapper drag and drop events editor embedding guide embedding faq embedding mozilla in a java application using javaxpcom error console
exception logging in javascript existing content extension frequently asked questions external cvs snapshots in mozilla-central fast graphics performance with html firefox block and line layout cheat sheet content states and the style system disabling interruptible reflow document loadi...
... e4x tutorial accessing xml children descendants and filters introduction namespaces the global xml object iterator liveconnect liveconnect overview liveconnect reference js
exception jsobject msx emulator (jsmsx) old proxy api parallelarray properly using css and javascript in xhtml documents examples reference server-side javascript back to the server: server-...
... npn_invokedefault npn_memalloc npn_memflush npn_memfree npn_pluginthreadasynccall npn_posturl npn_posturlnotify npn_releaseobject npn_releasevariantvalue npn_reloadplugins npn_removeproperty npn_requestread npn_retainobject npn_set
exception npn_setproperty npn_setvalue npn_setvalueforurl npn_status npn_utf8fromidentifier npn_useragent npn_version npn_write npobject npp nppvariable npp_destroy npp_destroystream npp_getvalue npp_handleevent npp_n...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
compilation options mentioned above, i now get the following error message while stating thunderbird with autoconfig (autoconf.js having pref('general.config.filename','thunderbird.cfg'); ) and thunderbird.cfg calling getldap* functions to retrieve cn and mail address of the current user. netscape.cfg/autoconfig failed. please contact your system administrator. error: getldapattibutes failed: [
exception... "component returned failure code: 0xc1f30001 (ns_error_not_initialized) [nsildapurl.spec]" nsresult: "0xc1f30001 (ns_error_not_initialized)" location: "js frame :: file:////usr/lib/thunderbird-3.0b2/defaults/autoconfig/prefcalls.js :: getldapattributes :: line 174" data: no] bug 295329 had been re-opened . autoconfig option and ldap support in thunderbird 1.5.x fortunately, autoconfig...
... // getldapattributes("ldap2.int-evry.fr","ou=people,dc=int-evry,dc=fr","uid=" + env_user,"uid,cn,mail,labeleduri"); // close the try, and call the catch() } catch(e) {displayerror("lockedpref", e);} if ldap call are uncommented in the preference file above, then i get a popup with: netscape.cfg/autoconfig failed. please contact your system administrator. error: getldapattibutes failed: [
exception... "could not convert javascript argument arg 0 [nsisupports.queryinterface]" nsresult: "0x80570009 (ns_error_xpc_bad_convert_js)" location: "js frame :: prefcalls.js :: getldapattributes :: line 177" data: no] autoconfig (pref) and ldap support in packages add ldap support in firefox 1.5 a least from firefox 1.5, autoconfig is compiled by default (cf. browser, moz_extensions_default="pref.
...buildconfig (don't know the equivalent for thunderbird! ...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
it implements the iappfilelocprovider interface, and tells xpcom where to find certain files and directories. if your code cannot find the gre and keeps throwing fi...
...versionrange[] range = new greversionrange[1]; range[0] = new greversionrange("1.8.0", true, "1.9", false); // work with trunk nightly version 1.9a1 ^^ try { file grepath = mozilla.getgrepathwithproperties(range, null); locationprovider locprovider = new locationprovider(grepath); mozilla.initembedding(grepath, grepath, locprovider); } catch (filenotfound
exception e) { // this
exception is thrown if gregrepathwithproperties cannot find a gre } catch (xpcom
exception e) { // this
exception is thrown if initembedding failed } locationprovider is a class provided by the java application. it implements the iappfilelocprovider interface, and tells xpcom where to find certain files and directories. if your code cannot find the gre and keeps throwing filenotfound
exceptions durin...
...ceptions 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. once the java application is done using mozilla, it needs to terminate the embedding process: try { mozilla.termembedding(); } catch (xpcom
exception e) { // this
exception is thrown if termembedding failed } working with xpcom objects now that mozilla is embedded, the java application can work with xpcom objects. the mozilla class provides several methods to facilitate this, such as getservicemanager, getcomponentmanager, and newlocalfile. in addition to retrieving and calling methods on xpcom objects, javaxpcom allows the java applica...
Componentizing our React app - Learn web development
browser. our todo component is complete, at least for now; now we can use it. 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. your <ul> should read like this: <ul role="list" classname="todo-list stack-large stack-
exception" aria-labelledby="list-heading" > <todo /> <todo /> <todo /> </ul> when you look back at your browser, you'll notice something unfortunate: your list now repeats the first task three times! we don't only want to eat; we have other things to — well — to do. next we'll look at how we can make different component calls render unique content. make a unique <todo /> components are po...
...ng else: array.prototype.map(). above the return statement of app(), make a new const called tasklist and use map() to transform it. let's start by turning our tasks array into something simple: the name of each task: const tasklist = props.tasks.map(task => task.name); let’s try replacing all the children of the <ul> with tasklist: <ul role="list" classname="todo-list stack-large stack-
exception" aria-labelledby="list-heading" > {tasklist} </ul> this gets us some of the way towards showing all the components again, but we’ve got more work to do: the browser currently renders each task's name as unstructured text. we’re missing our html structure — the <li> and its checkboxes and buttons! to fix this, we need to return a <todo /> component from our map() function — remembe...
...filterbutton from "./components/filterbutton"; import todo from "./components/todo"; function app(props) { const tasklist = props.tasks.map(task => ( <todo id={task.id} name={task.name} completed={task.completed} key={task.id} /> ) ); return ( <div classname="todoapp stack-large"> <form /> <div classname="filters btn-group stack-
exception"> <filterbutton /> <filterbutton /> <filterbutton /> </div> <h2 id="list-heading">3 tasks remaining</h2> <ul role="list" classname="todo-list stack-large stack-
exception" aria-labelledby="list-heading" > {tasklist} </ul> </div> ); } export default app; with this in place, we’re almost ready to tackle s...
Examples
eturn 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. if the file existence check fails, for example because access is denied, promise is rejected with an os.file.error instance. this state will propagate to newpomise, and components.utils.reporterror will report all the details of the
exception to the console. using a promise returned by a function (compact) the same code as the previous example is usually written with a more compact syntax: components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); os.file.exists(path).then(exists => { console.log(exists ? "you have file.txt in your temporary directory." ...
...ypromise.then( function(asuccessreason) { alert('mypromise was succesful and reason was = "' + asuccessreason + '"'); }, function(arejectreason) { alert('mypromise failed for reason = "' + uneval(arejectreason) + '"'); } ); function myuserdefinedpromise() { return 'i didnt do a promise.resolve so this will not understand that mypromise is a promise'; } // creates this error: /*
exception: mypromise.then is not a function @scratchpad/5:8:1 wca_evalwithdebugger@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:1069:7 wca_onevaluatejs@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:734:9 dsc_onpacket@resource://gre/modules/commonjs/toolkit/loader.js -> reso...
...eaftertimeout(avalue, atimeout) { let deferred = promise.defer(); try { // an asynchronous operation will trigger the resolution of the promise. // in this example, we don't have a callback that triggers a rejection. settimeout(function () { deferred.resolve('rawr my success value'); }, atimeout); } catch (ex) { // generally, functions returning promises propagate
exceptions through // the returned promise, though they may also choose to fail early. deferred.reject(ex); } // we don't return the deferred to the caller, but only the contained // promise, so that the caller cannot accidentally change its state. return deferred.promise; } // this code uses the promise returned be the function above. let promise = promisevalueaftertimeout("value", 1000)...
Promise.jsm
filled, when and if the final value becomes available. a fulfillment value becomes permanently associated with the promise. this may be any value, including undefined. rejected, if an error prevented the final value from being determined. a rejection reason becomes permanently associated with the promise. this may be any value, including undefined, though it is generally an error object, like in
exception handling. 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. in this case, the state of the promise can be observed but not directly controlled. to observe the state of a promise, its then method must be used. this method registers callback functions that are called as soon as the promise is either fulfille...
...e observed but not directly controlled. to observe the state of a promise, its then method must be used. 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. see the documentation of the then method for details. promises may also be created using the new promise() constructor. method overview deferred defer(); obsolete since gecko 30 promise resolve([optional] avalue); promise reject([optional] areason); methods defe...
.... it will eventually assume the same state as the provided promise. return value a promise that can be pending, fulfilled, or rejected. reject() creates a new promise rejected with the specified reason. promise reject( areason ); parameters areason optional the rejection reason for the returned promise. although the reason can be undefined, it is generally an error object, like in
exception handling. note: this argument should not be a promise. specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. return value a rejected promise. examples see the examples page. ...
NSS API Guidelines
ct secmyopaquedatastr { unsigned long myprivatedata1; unsigned long myprivatedata2; char *myname; }; the second task is to determine if individual data fields, within the data structure, are part of the api. one example may be the peercert field, in an ssl data structure. accessor functions, for these data elements, should be added to the api. there can be legitimate
exceptions to this 'make everything opaque' rule. for example, in container structures, such as secitem, or maybe linked list data structures. these data structures need to be examined on a case by case basis, to determine if they are truly stable and will not change in future release it is necessary for the callers of the api to know the size of these structures, as they may allocate new ones and pass...
...ly called by a destroy function. finally, error logging should be added an documented when debug is turned on. interfaces for these are in nspr. thread safety code developed using the nss apis needs to make use of thread safety features. first to examine is object creation and deletion. object creation is usually not a problem. no other threads have access to allocated memory just created.
exceptions to this include objects which are created on the fly, or as global objects. deletion, on the other hand, may be trickier. threads may be referencing the object at the same time a another thread tries to delete it. the semantics depend on the way the application uses the object, also how and when the application wants to destroy it. for some data structures, this problem can be removed by protec...
...bal data, particularly if they may be called multiple times, to provide different semantics for different operations. for example, the following should be avoided : sec_setkey(keyforoperation); sec_encrypt(data,length); instead, a context handle should be created, and the sec_setkey() function, above, made on that handle. fortunately most of the existing api has the correct semantics. the
exception to this global effects rule may be functions which set global state for an application at initialization time. methods/functions design init, shutdown functions if a layer has some global initialization tasks, which need to be completed before the layer can be used, that layer should supply an initialization function of the form layer_init(). if an initialization function is supplied, a...
Rhino shell
output property. err - the process error output instead of java.lang.system.err. if it is not instance of java.io.outputstream, the process error output is read, converted to a string, appended to the err property value converted to string and put as the new value of the err property. seal(object) seal the specified object so any attempt to add, delete or modify its properties would throw an
exception. serialize(object, filename) serialize the given object to the specified file. spawn(functionorscript) run the given function or script in a different thread. sync(function) creates a synchronized function (in the sense of a java synchronized method) from an existing function. the new function synchronizes on the this object of its invocation. quit() quit shell. the shell will also quit i...
...: 'sort output:\n'} js> runcommand("sort", opt) 0 js> print(opt.output) sort output: a b c js> var opt={input: "c\na\nb", output: 'sort output:\n', err: ''} js> runcommand("sort", "--bad-arg", opt) 2 js> print(opt.err) /bin/sort: unrecognized option `--bad-arg' try `/bin/sort --help' for more information. ...
...s> runcommand("sort", opt) 0 js> print(opt.output) sort output: a b c js> var opt={input: "c\na\nb", output: 'sort output:\n', err: ''} js> runcommand("sort", "--bad-arg", opt) 2 js> print(opt.err) /bin/sort: unrecognized option `--bad-arg' try `/bin/sort --help' for more information. ...
JSErrorReport
code line buffer. this is the buffer that contains the original data. uctokenptr const char16_t * pointer to the error token in *uclinebuf. flags unsigned the logical or of zero or more of the following flags: jsreport_warning this "error" is really only a warning. it will not cause the current operation to fail. jsreport_
exception an
exception is being raised. a jserrorreporter might choose to ignore a jserrorreport that has this flag set, since the
exception may be caught and handled by javascript code. jsreport_strict this error is only being reported because the engine is in strict mode. jsreport_strict_mode_error this condition is an error in strict mode code,...
...uf to point at the buffer before your application executes a script. for unicode scripts, define a second buffer that holds the unicode version of the text the generated the error. for application that do not use unicode, set uclinebuf and uctokenptr to null. macros name description jsreport_is_warning(flags) returns true if flags has jsreport_warning. jsreport_is_
exception(flags) returns true if flags has jsreport_
exception. jsreport_is_strict(flags) returns true if flags has jsreport_strict. jsreport_is_strict_mode_error(flags) returns true if flags has jsreport_strict_mode_error. see also mxr id search for jserrorreport js_reporterror js_reportwarning js_reportoutofmemory js_seterrorreporter js_reporterrornumber js_reporte...
... returns true if flags has jsreport_strict. jsreport_is_strict_mode_error(flags) returns true if flags has jsreport_strict_mode_error. see also mxr id search for jserrorreport js_reporterror js_reportwarning js_reportoutofmemory js_seterrorreporter js_reporterrornumber js_reporterrornumberuc js_reporterrorflagsandnumber js_reporterrorflagsandnumberuc js_reportpending
exception ...
JSAPI reference
ction added in spidermonkey 17 js_decompilefunction js_decompilefunctionbody js_compilefunction obsolete since jsapi 36 js_compilefunctionforprincipals obsolete since jsapi 28 js_compileucfunction obsolete since jsapi 36 js_compileucfunctionforprincipals obsolete since jsapi 28 error handling struct jserrorformatstring added in spidermonkey 17 class jserrorreport class js::autosave
exceptionstate added in spidermonkey 31 enum jsexntype added in spidermonkey 17 js_reporterror js_reportwarning js_reporterrornumber js_reporterrornumberuc js_reporterrorflagsandnumber js_reporterrorflagsandnumberuc js_reporterrornumberucarray added in spidermonkey 24 js_reportoutofmemory js_reportallocationoverflow added in spidermonkey 1.8 js_geterrorreporter js_seterrorreporterobsolete since...
...nkey 31 enum jsexntype added in spidermonkey 17 js_reporterror js_reportwarning js_reporterrornumber js_reporterrornumberuc js_reporterrorflagsandnumber js_reporterrorflagsandnumberuc js_reporterrornumberucarray added in spidermonkey 24 js_reportoutofmemory js_reportallocationoverflow added in spidermonkey 1.8 js_geterrorreporter js_seterrorreporterobsolete since jsapi 52 js_errorfrom
exception js_geterrorprototype jsreport_is_
exception jsreport_is_strict jsreport_is_warning jsreport_is_strict_mode_error the following functions allow c/c++ functions to throw and catch javascript
exceptions: js::createerror added in spidermonkey 38 js_is
exceptionpending js_getpending
exception js_setpending
exception js_clearpending
exception js_throwstopiteration added in spidermonkey 1.8 j...
...s_strict jsreport_is_warning jsreport_is_strict_mode_error the following functions allow c/c++ functions to throw and catch javascript
exceptions: js::createerror added in spidermonkey 38 js_is
exceptionpending js_getpending
exception js_setpending
exception js_clearpending
exception js_throwstopiteration added in spidermonkey 1.8 js_isstopiteration added in spidermonkey 31 typedef js
exceptionstate js_save
exceptionstate js_restore
exceptionstate js_drop
exceptionstate these functions translate errors into
exceptions and vice versa: js_reportpending
exception js_errorfrom
exception js_throwreportederror obsolete since jsapi 29 values and types typedef jsval js::value js::value constructors: js::nullvalue added in spidermonkey 24 js::undefinedvalue added in spiderm...
Secure Development Guidelines
ed write to un-initialized file descriptor checking return values check all return values—no matter how unlikely the api failure for example: close() can fail and leak file descriptor setuid() can fail and privileges don’t get dropped snprintf() can fail and result in return value -1 tmp = realloc(tmp, size) — realloc could fail and leak tmp writing secure code:
exception handling double freeing pointers double frees can occur in
exception handling they free data in try block and then free it again in the catch block this is a common issue double freeing pointers char *ptr1 = null, *ptr2 = null; try { ptr1 = new char[1024]; do_something(); delete ptr1; do_something_else(); ptr2 = new char[-1] // oom } catch (...) { delete p...
...ees can occur in
exception handling they free data in try block and then free it again in the catch block this is a common issue double freeing pointers char *ptr1 = null, *ptr2 = null; try { ptr1 = new char[1024]; do_something(); delete ptr1; do_something_else(); ptr2 = new char[-1] // oom } catch (...) { delete ptr1; delete ptr2; } new will throw an
exception — ptr1 is already freed in the try block then freed again in the catch block freeing un-initialized data free data in the catch block assumption is that it’s initialized in the try block if the try block throws before the variable is initialized, the catch block will operate on un-intialized data freeing un-initialized data example: int main(){ char *ptr; try { ...
... delete p; } catch (...) { ... } } memory leaks: prevention any acquired resource in a try block should be freed in a catch block (if the try block throws before the resource is freed) might be helpful to initialize variables null for pointers -1 for file descriptors ...
An Overview of XPCOM
n simple class inheritance, for example, you'd like to be able ask the shape if it's a circle and to be able to use it like a circle if it is. in xpcom, this is what the queryinterface feature of the nsisupports interface is for: it allows clients to find and access different interfaces based on their needs. in c++, you can use a fairly advanced feature known as a dynamic_cast<>, which throws an
exception if the shape object is not able to be cast to a circle. but enabling
exceptions and rtti may not be an option because of performance overhead and compatibility on many platforms, so xpcom does things differently.
exceptions in xpcom c++
exceptions are not supported directly by xpcom. instead all
exceptions must be handled within a given component, before crossing interface boundaries. in xpcom...
... instead of leveraging c++ rtti, xpcom uses the special queryinterface method that casts the object to the right interface if that interface is supported. every interface is assigned an identifier that gets generated from a tool commonly named "uuidgen". this universally unique identifier (uuid) is a unique, 128-bit number. ...
... ns_imethod method declaration return type. xpcom method declarations should use this as their return type. ns_imethodimp method implementation return type. xpcom method implementations should use this as their return type. ns_imethodimp_(type) special case implementation return type. some methods such as addref and release do not return the default return type. this
exception is regrettable, but required for com compliance. ns_import forces the method to be resolved internally by the shared library. ns_export forces the method to be exported by the shared library. reference counting these macros manage reference counting. ns_addref calls addref on an nsisupports object. ns_if_addref same as above but checks for ...
mozIStorageService
r_file_corrupted. note: the connection object returned by this function is not threadsafe. you must use it only from the thread you created it from. mozistorageconnection opendatabase( in nsifile adatabasefile ); parameters adatabasefile an nsifile indicating the database file to open. return value a mozistorageconnection representing the connection to the opened database file.
exceptions thrown ns_error_failure an error occurred attempting to open the database. ns_error_file_corrupted the database file is corrupted, or contains virtual tables and is not compatible with this method. ns_error_out_of_memory allocating a new storage object failed. openspecialdatabase() opens a connection to a named special database storage that identifies ...
... you should only access the profile database from the main thread since other callers may also be using it. mozistorageconnection openspecialdatabase( in string astoragekey ); parameters astoragekey a string key identifying the type of storage requested. valid values are "profile" and "memory". return value a new mozistorageconnection providing access to the requested database.
exceptions thrown ns_error_invalid_arg if astoragekey is invalid. openunshareddatabase() opens a database connection to the specified file without using a shared cache. 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...
...atabase. note: the connection object returned by this function is not threadsafe. you must use it only from the thread you created it from. mozistorageconnection openunshareddatabase( in nsifile adatabasefile ); parameters adatabasefile an nsifile indicating the database file to open. return value a mozistorageconnection representing the connection to the opened database file.
exceptions thrown ns_error_failure an error occurred attempting to open the database. ns_error_file_corrupted the database file is corrupted, or contains virtual tables and is not compatible with this method. ns_error_out_of_memory allocating a new storage object failed. see also storage mozistorageconnection ...
nsIArray
element); void queryelementat(in unsigned long index, in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result); attributes attribute type description length unsigned long the number of elements in the array. read only. methods enumerate() enumerate the array. nsisimpleenumerator enumerate(); parameters none. return value a new enumerator positioned at the start of the array.
exceptions thrown ns_error_failure if the array is empty (to make it easy to detect errors). ns_error_out_of_memory if there is not enough memory to complete the operation. indexof() get the position of a specific element. note that since null is a valid input,
exceptions are used to indicate that an element is not found. unsigned long indexof( in unsigned long startindex, in nsisupports element ); ...
...input,
exceptions are used to indicate that an element is not found. unsigned long indexof( in unsigned long startindex, in nsisupports element ); parameters startindex the initial element to search in the array. to start at the beginning, use 0 as the startindex. element the element you are looking for. return value a number >= startindex which is the position of the element in the array.
exceptions thrown ns_error_failure if the element was not in the array. queryelementat() retrieve a specific element of the array, and queryinterface it to the specified interface. null is a valid result for this method, but
exceptions are thrown in other circumstances. void queryelementat( in unsigned long index, in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result ); parameters index ...
... queryinterface it to the specified interface. null is a valid result for this method, but
exceptions are thrown in other circumstances. void queryelementat( in unsigned long index, in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result ); parameters index position of element. uuid the iid of the requested interface. result the object, queryinterface'd to the requested interface.
exceptions thrown ns_error_illegal_value when index > length-1. see also nsimutablearray ...
nsIChannelEventSink
.e. it was not initiated by the remote server, but is specific to the channel implementation. the new uri may be identical to the old one. methods asynconchannelredirect() called when a redirect occurs. this may happen due to an http 3xx status code. this method notifies the sink that a redirect is about to happen, but also to gives the sink the right to veto the redirect by throwing an
exception or passing a failure code in the callback. note: vetoing the redirect simply means that newchannel will not be opened. it is important to understand that oldchannel will continue loading as if it received a response of http 200, which includes notifying observers and possibly display or process content attached to the http response. if the sink wants to prevent this loading it must explicitly dea...
... e.g. by calling oldchannel->cancel() there is a certain freedom in implementing this method: if the return-value indicates success, a callback on callback is required. this callback can be done from within asynconchannelredirect() (effectively making the call synchronous) or at some point later (making the call asynchronous). if the return value indicates that an error occurred, in which case an
exception is thrown, the redirect is vetoed and no callback must be done. void asynconchannelredirect( in nsichannel oldchannel, in nsichannel newchannel, in unsigned long flags, in nsiasyncverifyredirectcallback callback ); parameters oldchannel the channel that's being redirected. newchannel the new channel. this channel is not opened yet. flags flags indicating the type...
...rectcallback callback ); parameters oldchannel the channel that's being redirected. newchannel the new channel. this channel is not opened yet. flags flags indicating the type of redirect. a bitmask consisting of flags from above. one of redirect_temporary and redirect_permanent will always be set. callback object to inform about the async result of this method.
exceptions thrown this method can throw any
exception; if an
exception occurs, the load will be canceled, and no network requests will occur for the new channel. the redirect will be canceled. onchannelredirect() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) called when a redirect occurs. this may happen due to an http 3xx status code. void onchannelredire...
nsIDOMMozNetworkStatsManager
ptions. networkstatsgetoptions is a dictionary object providing filtering options. return value an nsidomdomrequest object. if successful, the request result is an nsidommoznetworkstats object describing the network statistics. if network stats are not available for some dates, then rxbytes and txbytes are undefined for those dates. if the filtering start date is greater than the end date, an
exception is thrown.
exceptions thrown ns_error_invalid_arg the filtering start date is greater than the end date. ns_error_not_implmented both appmanifesturl and servicetype are specified at the same time in the networkstatsgetoptions dictionary. invalidnetwork the network must be in the return of getavailablenetworks. addalarm() install an alarm on a network. when total data usage reaches thr...
...kind of origin is available, the moznetworkstatsmanager.getavailablenetworks method returns an array of interfaces. threshold the total data usage threshold in bytes. options optional filtering options. networkstatsalarmoptions is a dictionary object providing filtering options. return value an nsidomdomrequest object. if successful, the result field of the domrequest keeps the alarm id.
exceptions thrown invalidnetwork the network must be in the return of getavailablenetworks. getallalarms() obtain all alarms for those networks returned by getavailablenetworks. if a network is provided, only retrieves the alarms for that network. nsidomdomrequest getallalarms([optional] in nsisupports network); parameters network optional the origin of the data. it can specify wifi, mobile, o...
...etwork optional the origin of the data. it can specify wifi, mobile, or null. if null, data measurement from both origins are merged. to know in advance which kind of origin is available, the moznetworkstatsmanager.getavailablenetworks method returns an array of interfaces. return value an alarm object with the same fields as that in the system message; alarmid, network, threshold, and data.
exceptions thrown invalidnetwork the network must be in the return of getavailablenetworks. removealarms() remove all network alarms. if an alarmid is provided, then only that alarm is removed. nsidomdomrequest removealarms([optional] in long alarmid); parameters alarmid id of an alarm, like the one returned by addalarm. return value an nsidomdomrequest object. clearstats() remove all st...
nsIFocusManager
native code only! attributes attribute type description activewindow nsidomwindow the most active (frontmost) window, or null if no window that is part of the application is active. setting the activewindow raises it, and focuses the current child window's current element, if any. setting this to null or to a non-top-level window throws an ns_error_invalid_arg
exception. focusedelement nsidomelement the element that is currently focused. this will always be an element within the document loaded in focusedwindow or null if no element in that document is focused. read only. focusedwindow nsidomwindow the child window within the activewindow that is focused. this will always be activewindow, a child window of activewindow or null if no...
... move focus to a link at the position of the caret. this is a special value used to focus links as the caret moves over them in caret browsing mode. methods clearfocus() clears the focused element within awindow. if the current focusedwindow is a descendant of awindow, sets the current focusedwindow to awindow. void clearfocus( in nsidomwindow awindow ); parameters awindow
exceptions thrown ns_error_invalid_arg if awindow is null. native code only!contentremoved obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. called when content has been removed. void contentremoved( in nsidocument adoc...
...n value may be the element within a child descendant window that is focused. if false, then the return value will be the frame element if the focus is in a child frame. afocusedwindow will be set to the currently focused descendant window of awindow, or to awindow if adeep is false. this will be set even if no element is focused. return value the currently focused element within awindow.
exceptions thrown ns_error_invalid_arg if awindow is null. getlastfocusmethod() pruint32 getlastfocusmethod( in nsidomwindow window ); parameters window if null, then the current focusedwindow will be used by default. this has the result of retrieving the method that was used to focus the currently focused element. return value the method that was used to focus the element in window.
nsIJumpListBuilder
optional); boolean commitlistbuild(); boolean deleteactivelist(); boolean initlistbuild(in nsimutablearray removeditems); attributes attribute type description available short indicates whether jump list taskbar features are supported by the current host. read only. islistcommitted boolean jumplist management. indicates if a commit has already occurred in this session. read only.
exceptions thrown ns_error_not_available on all calls if taskbar functionality is not supported by the operating system. maxlistitems short the maximum number of jump list items the current desktop can support. read only. constants constant value description jumplist_category_tasks 0 tasks are common actions performed by users within the application. a task can be represented by an applicatio...
...adds a list and if required, a set of items for the list. boolean addlisttobuild( in short acattype, in nsiarray items, optional in astring catname optional ); parameters acattype the type of list to add. items optional an array of nsijumplistitem items to add to the list. catname optional for custom lists, the title of the list. return value true if the operation completed successfully.
exceptions thrown ns_error_unexpected on internal errors. ns_error_illegal_value if an item is added that was removed since the last commit. ns_error_invalid_arg if incorrect parameters are passed for a particular category or item type. commitlistbuild() commits the current jump list build to the taskbar. boolean commitlistbuild(); parameters none. return value true if the operation completed successful...
...mp list build to the taskbar. boolean commitlistbuild(); parameters none. return value true if the operation completed successfully. deleteactivelist() deletes any currently applied taskbar jump list for this application. common uses would be the enabling of a privacy mode and uninstallation. boolean deleteactivelist(); parameters none. return value true if the operation completed successfully.
exceptions thrown ns_error_unexpected on internal errors. initlistbuild() initializes a jump list build and returns a list of items the user removed since the last time a jump list was committed. removed items can become state after initlistbuild is called, lists should be built in single-shot fashion. boolean initlistbuild( in nsimutablearray removeditems ); parameters removeditems a list of items t...
nsIMimeHeaders
headerssize); attributes attribute type description allheaders string read only. ...
... attribute type description allheaders string read only. ...
... missing description getallofthem missing description return value missing description
exceptions thrown missing
exception missing description initialize() void initialize( [const] in string allheaders, in long allheaderssize ); parameters allheaders insert the complete message content allheaderssize length of the passed in content
exceptions thrown missing
exception missing description remarks see also ...
nsIMsgRuleAction
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgfilter.idl [scriptable, uuid(190a2a18-d245-473a-a402-9f0814598c7f)] interface nsimsgruleaction : nsisupports { attribute nsmsgruleactiontype type; // target priority.. throws an
exception if the action is not priority attribute nsmsgpriorityvalue priority; // target folder.. throws an
exception if the action is not move to folder attribute acstring targetfolderuri; // target label. ...
...[scriptable, uuid(190a2a18-d245-473a-a402-9f0814598c7f)] interface nsimsgruleaction : nsisupports { attribute nsmsgruleactiontype type; // target priority.. throws an
exception if the action is not priority attribute nsmsgpriorityvalue priority; // target folder.. throws an
exception if the action is not move to folder attribute acstring targetfolderuri; // target label. ...
...{ attribute nsmsgruleactiontype type; // target priority.. throws an
exception if the action is not priority attribute nsmsgpriorityvalue priority; // target folder.. throws an
exception if the action is not move to folder attribute acstring targetfolderuri; // target label. ...
nsIMutableArray
eelementat(in unsigned long index); void replaceelementat(in nsisupports element, in unsigned long index, in boolean weak); methods appendelement() append an element at the end of the array. void appendelement( in nsisupports element, in boolean weak ); parameters element the element to append. weak whether or not to store the element using a weak reference.
exceptions thrown ns_error_failure when a weak reference is requested, but the element does not support nsiweakreference. clear() clear the entire array, releasing all stored objects. void clear(); parameters none. insertelementat() insert an element at the given position, moving the element currently located in that position, and all elements in higher position, up by one. void insertelementat(...
...: if the position is lower than the current length of the array, the elements at that position and onwards are bumped one position up. if the position is equal to the current length of the array, the new element is appended. an index lower than 0 or higher than the current length of the array is invalid and will be ignored. weak whether or not to store the element using a weak reference.
exceptions thrown ns_error_failure when a weak reference is requested, but the element does not support nsiweakreference. removeelementat() remove an element at a specific position, moving all elements stored at a higher position down one. to remove a specific element, use nsiarray.indexof() to find the index first, then call removeelementat. void removeelementat( in unsigned long index ); par...
...ting element will be replaced. if the position is equal to the current length of the array, the new element is appended. if the position is higher than the current length of the array, empty elements are appended followed by the new element at the specified position. an index lower than 0 is invalid and will be ignored. weak whether or not to store the new element using a weak reference.
exceptions thrown ns_error_failure when a weak reference is requested, but the element does not support nsiweakreference. see also nsiarray ...
nsIScriptableInputStream
currently available in the stream. note: this method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. moreover, since a stream may make available more than 2^32 bytes of data, this method is incapable of expressing the entire size of the underlying data source. unsigned long available(); parameters none. return value the number of bytes.
exceptions thrown ns_base_stream_closed if called after the stream has been closed. close() closes the stream. note: the close method may be called more than once, but subsequent calls are ignored. void close(); parameters none. init() wrap the given nsiinputstream with this nsiscriptableinputstream. note: the init method may be called more than once, allowing a nsiscriptableinputstream instance...
...articular, some bindings may convert the byte values into unicode code points, by assuming the byte values are encoded as iso-latin-1. this is the case for the javascript bindings. string read( in unsigned long acount ); parameters acount the maximum number of bytes to read from the stream. return value the data read as a string, which will be an empty string if the stream is at eof.
exceptions thrown ns_error_not_initialized if init() was not called. ns_base_stream_closed if called after the stream has been closed. ns_base_stream_would_block indicates that reading from the input stream would block the calling thread for an indeterminate amount of time. this
exception may only be thrown if nsiinputstream.isnonblocking() returns true. readbytes() read data from...
... ns_base_stream_would_block if reading from the input stream would block the calling thread (non-blocking mode only). remarks this interface provides javascript with a way to read ascii text from a nsiinputstream. ...
nsISessionStore
cription canrestorelastsession boolean is it possible to restore the previous session. will always be false when in private browsing mode. methods deletetabvalue() deletes a value from a specified tab. void deletetabvalue( in nsidomnode atab, in astring akey ); parameters atab the tab for which to delete the value. akey the key whose value is to be deleted.
exceptions thrown this method throws a ns_error_illegal_value
exception if the key doesn't exist. deletewindowvalue() deletes a value from a specified window. void deletewindowvalue( in nsidomwindow awindow, in astring akey ); parameters awindow the window in which to delete the value. akey the key whose value is to be deleted. duplicatetab() duplicates a specified tab as thoroughly as p...
...window awindow, in unsigned long aindex ); parameters awindow is the browser window associated with the closed tab. aindex is the index of the closed tab to be removed (fifo ordered). return value forgetclosedwindow() nsidomnode forgetclosedwindow( in unsigned long aindex ); parameters aindex is the index of the closed window to be removed (fifo ordered). return value
exceptions thrown ns_error_invalid_arg when aindex does not map to a closed window. getbrowserstate() returns the current state of all of windows and all of their tabs. astring getbrowserstate(); parameters none. return value a json string representing the current state of all windows in the web browser. getclosedtabcount() returns the number of restorable tabs for a given window. unsigned ...
...fied window in the web browser. astring getwindowstate( in nsidomwindow awindow ); parameters awindow the browser window whose state is to be returned. see #note on windows. return value a json string representing a session state that contains only the window specified by awindow. 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". getwindowvalue() returns the string value associated with a given key for a window. astring getwindowvalue( in nsidomwindow awindow, in astring akey ); parameters awindow the window from which the value is to be retrieved. akey the key whose corresponding value is to be retrieved. return value the string value that was previously assigned t...
nsIThread
l, 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). when this function returns, the thread will be shut down and will no longer be available to receive events. void shutdown() parameters none.
exceptions thrown ns_error_unexpected shutdown() was erroneously called from within the thread itself, the thread was not created with the thread manager's nsithreadmanager.newthread() method, or the thread is already in the process of being shut down. haspendingevents() determines whether or not the thread has events that are ready to be processed. note: this method must be called from within the ...
...thod must be called from within the thread itself, and not from another thread. boolean haspendingevents() parameters none. return value true if there are pending events at the time the function was called. since other threads may add events to the current thread, it's possible that by the time this method returns, the event queue may no longer be empty, even if a false result is reported.
exceptions thrown ns_error_unexpected the method was called when this thread wasn't the current thread. processnextevent() processes the next pending event. if there aren't any pending events, this method may wait -- depending on the value of the maywait parameter -- until an event is dispatched to the thread. this method is re-entrant but may only be called if this thread is the current thread. ...
... to find and fix. consider use asynchronous callbacks instead. boolean processnextevent( in boolean maywait ); parameters maywait if true, this method blocks until an event is available to process if the event queue is empty. if false, this method returns immediately if the queue is empty. return value returns true if an event was processed, or false if there were no pending events.
exceptions thrown ns_error_unexpected this method was called when this thread wasn't the current thread. see also the thread manager nsithreadmanager nsithreadpool nsithreadinternal nsithreadobserver nsithreadeventfilter ...
nsIToolkitProfileService
n where the profile directory is located. nsitoolkitprofile createprofile( in nsilocalfile arootdir, in autf8string aname ); parameters arootdir the profile directory. may be null, in which case a suitable default will be chosen based on the profile name. aname the name to give the new profile. return value an nsitoolkitprofile object representing the newly-created profile.
exceptions thrown ns_error_unexpected an unexpected error condition occurred. ns_error_file_not_directory one of the specified directory files is not actually a directory. ns_error_out_of_memory unable to allocate the new profile object. flush() flushes the profile list to disk. the profile list file is constructed in memory, then written out as one large chunk, in order to reduce...
..._directory one of the specified directory files is not actually a directory. ns_error_out_of_memory unable to allocate the new profile object. flush() flushes the profile list to disk. the profile list file is constructed in memory, then written out as one large chunk, in order to reduce the risk of the profile list file being corrupted by disk errors. void flush(); parameters none.
exceptions thrown ns_error_out_of_memory an error occurred trying to allocate the memory buffer used to construct the profile list. ns_error_unexpected an error occurred writing the profile list file to disk. getprofilebyname() gets a profile, given the profile's name. nsitoolkitprofile getprofilebyname( in autf8string aname ); parameters aname the profile name to find. retur...
...llocate the memory buffer used to construct the profile list. ns_error_unexpected an error occurred writing the profile list file to disk. getprofilebyname() gets a profile, given the profile's name. nsitoolkitprofile getprofilebyname( in autf8string aname ); parameters aname the profile name to find. return value an nsitoolkitprofile object describing the specified profile.
exceptions thrown ns_error_failure no matching profile was found. lockprofilepath() locks an arbitrary path as a profile. if the path does not exist, it is created and the defaults copied from the application directory. nsiprofilelock lockprofilepath( in nsilocalfile adirectory, in nsilocalfile atempdirectory ); parameters adirectory the directory to lock as a profile directory. ...
nsIWebBrowserPersist
a nsilocalfile object or an nsiuri object with a file scheme. aoutputcontenttype the desired mime type format to save the document and all sub-documents into or nsnull to use the default behavior. aencodingflags flags to pass to the encoder. awrapcolumn for text documents, indicates the desired width to wrap text at. parameter is ignored if wrapping is not specified by the encoding flags.
exceptions thrown ns_error_invalid_arg one or more arguments was invalid. saveuri() as of firefox 26, this method should no longer be used from add-on code. please use downloads.createdownload() instead. as of firefox 36, a new parameter areferrerpolicy was added as the fourth argument, changing the number of parameters from 7 to 8 and shifting the order of the parameters in a backwards incompatib...
...anent cache, etc.) null must only be passed in the event that no such relevant context exists (ie. the uri being saved is unrelated to any current browsing session). important: if you think that you should be passing null here, you are almost certainly wrong. null should be passed only when no plausible privacy context exists for the uri to be saved, which is an exceedingly rare corner case. ...
...assed only when no plausible privacy context exists for the uri to be saved, which is an exceedingly rare corner case.
exceptions thrown ns_error_invalid_arg one or more arguments was invalid. saveprivacyawareuri() save the specified uri to file, explicitly dictating whether the operation should be considered private for the purposes of network requests, caching, etc. all arguments and
exceptions are identical to saveuri, with the
exception of aisprivate which is used to indicate the private nature of the operation. example function downloadfile(httploc, sourcewindow) { try { //new obj_uri object var obj_uri = components.classes["@mozilla.org/network/io-service;1"].getservice(components.interfaces.nsiioservice).newuri(httploc, null, null); //new file object var obj_t...
nsIWebProgress
to this article. last changed in gecko 1.8.0 inherits from: nsisupports method overview void addprogresslistener(in nsiwebprogresslistener alistener, in unsigned long anotifymask); void removeprogresslistener(in nsiwebprogresslistener alistener); attributes attribute type description domwindow nsidomwindow the dom window associated with this nsiwebprogress instance. read only.
exceptions thrown ns_error_failure indicates that there is no associated dom window. isloadingdocument prbool indicates whether or not a document is currently being loaded in the context of this nsiwebprogress instance. read only. constants the following flags may be combined to form the anotifymask parameter for the addprogresslistener() method. they limit the set of events that are delivered to a...
... notifications. methods addprogresslistener() registers a listener to receive web progress events. void addprogresslistener( in nsiwebprogresslistener alistener, in unsigned long anotifymask ); parameters alistener the listener interface to be called when a progress event occurs. this object must also implement nsisupportsweakreference. anotifymask the types of notifications to receive.
exceptions thrown ns_error_invalid_arg indicates that alistener was either null or that it does not support weak references. ns_error_failure indicates that alistener was already registered. removeprogresslistener() removes a previously registered listener of progress events. void removeprogresslistener( in nsiwebprogresslistener alistener ); parameters alistener the listener interface previously reg...
...listener was either null or that it does not support weak references. ns_error_failure indicates that alistener was already registered. removeprogresslistener() removes a previously registered listener of progress events. void removeprogresslistener( in nsiwebprogresslistener alistener ); parameters alistener the listener interface previously registered with a call to addprogresslistener().
exceptions thrown ns_error_failure indicates that alistener was not registered. ...
nsIXULTemplateQueryProcessor
ariable avar would be 7, assuming the query processor considers the syntax '+2' to mean add two to the reference. void addbinding( in nsidomnode arulenode, in nsiatom avar, in nsiatom aref, in astring aexpr ); parameters arulenode rule to add the binding to. avar variable that will be bound. aref variable that holds reference value. aexpr expression used to compute the value to assign.
exceptions thrown ns_error_unexpected if generateresults() has already been called. compareresults() compare two results to determine their order, used when sorting results. this method should return -1 when the left result is less than the right, 0 if both are equivalent, and 1 if the left is greater than the right. the comparison should only consider the values for the specified variable. if the compar...
...y with different values for aref. nsisimpleenumerator generateresults( in nsisupports adatasource, in nsixultemplateresult aref, in nsisupports aquery ); parameters adatasource datasource for the data. aref context reference value used as a starting point. aquery the compiled query returned from query compilation. return value an enumerator of nsixultemplateresult objects as the results.
exceptions thrown ns_error_invalid_arg if aquery is invalid. getdatasource() retrieve the datasource to use for the query processor. the list of datasources in a template is specified using the datasources attribute as a space separated list of uris. this list is processed by the builder and supplied to the query processor in the adatasources array as a list of nsiuri objects or nsidomnode objects. this ...
... whenever the template is rebuilt. this method must be called once before any of the other query processor methods except for translateref(). void initializeforbuilding( in nsisupports adatasource, in nsixultemplatebuilder abuilder, in nsidomnode arootnode ); parameters adatasource datasource for the data. abuilder the template builder. arootnode the root node the builder is attached to.
exceptions thrown ns_error_invalid_arg if the datasource is not supported. ns_error_unexpected if generateresults() has already been called. translateref() translate a ref attribute string into a result. this is used as the reference point by the template builder when generating the first level of content. for recursive generation, the result from the parent generation phase will be used directly as the ...
nsIAbCard/Thunderbird3
his will be removed from the interface at a later date. methods getproperty() returns a property for the given name. nsivariant getproperty(in autf8string name, in nsivariant defaultvalue); parameters name the case-sensitive name of the property to get. defaultvalue the value to return if the property does not exist. return value the value of the attribute asked for.
exceptions thrown ns_error_not_available<tt> if the named property does not exist. <tt>ns_error_cannot_convert_data if the property cannot be converted to the desired type. getpropertyasastring() getpropertyasautf8string() getpropertyasuint32() getpropertyasbool() [noscript] astring getpropertyasastring(in string name); [noscript] autf8string getpropertyasautf8string(in string name); [noscri...
...rue is a non-zero value), so that false will be converted to a string of 0 and not false<code>. these functions are marked <code>[noscript] since xpcconnect performs automatic type conversion on nsivariant such that they are not needed for scripts, only for c++ callers. parameters name the case-sensitive name of the property to get. return value the value of the attribute asked for.
exceptions thrown ns_error_not_available<tt> if the named property does not exist. <tt>ns_error_cannot_convert_data if the property cannot be converted to the desired type. [noscript] astring getpropertyasastring(in string name); [noscript] autf8string getpropertyasautf8string(in string name); [noscript] pruint32 getpropertyasuint32(in string name); [noscript] boolean getpropertyasbool(in strin...
...leteproperty(in autf8string name); parameters name the case-sensitive name of the property to set. translateto() translates a card into a specific format. the following types are supported: base64xml xml vcard autf8string translateto(in autf8string atype); parameters atype the type of item to translate the card into. return value a string containing the translated card.
exceptions thrown ns_error_illegal_value type not recognized. copy() this function will copy all values from one card to another. void copy(in nsiabcard srccard) parameters srccard the source card to copy values from. equals() returns true if this card is equal to the other card. the default implementation defines equal as this card pointing to the same object as acard. another implementat...
XPIDL
be thrown in script contexts and native contexts lack the set method, by using the "readonly" keyword. to native code, on attribute declared 'attribute type foo;' is syntactic sugar for the declaration of two methods 'type getfoo();' and 'void setfoo(in type foo);'. if foo were declared readonly, the latter method would not be present. attributes support all of the properties of methods with the
exception of optional_argc, as this does not make sense for attributes. there are some special rules for attribute naming. as a result of vtable munging by the msvc++ compiler, an attribute with the name `iid' is forbidden. in addition, any attribute whose name matches the regex /^[a-z]{2,3}i[a-z][a-z]/ is emitted with a warning, as its name looks like an nsiinterface or a moziinterface declaration. also ...
...a scriptable interface and it lacks a noscript or notxpcom property. any method that is not scriptable can only be accessed by native code. however, scriptable methods must contain parameters and a return type that can be translated to script: any native type, save those declared with an nsid, utf8string, cstring, astring, or jsval property, may not be used in a scriptable method or attribute. an
exception to the above rule is if the parameter has the iid_is property (a special case for some queryinterface-like operations). in general, this means that the only usable native types are those declared in nsrootidl.idl (see above). methods and attributes are mangled on conversion to native code. if a method is declared notxpcom, the mangling of the return type is prevented, so it is called mostly as i...
...ler. if optional_argc is present, then an additional uint8_t _argc method is added at the end which receives the number of optional arguments that were actually used (obviously, you need to have an optional argument in the first place). note that if both properties are set, the jscontext *cx is added first, followed by the uint8_t _argc, and then ending with return value parameter. finally, as an
exception to everything already mentioned, for attribute getters and setters the jscontext *cx comes before any other arguments. another native-only property is nostdcall. normally, declarations are made in the stdcall abi on windows to be abi-compatible with com interfaces. any non-scriptable method or attribute with nostdcall instead uses the thiscall abi convention. methods without this property genera...
PointerType
pointertype represents c pointer. syntax returns a new ctype object describing a new pointer data type. ctype pointertype( type ); parameters type specifies the type to which the pointer type points. this can be any ctype object to declare the new type as a pointer to that type. return value a ctype object describing the newly created data type.
exceptions thrown typeerror thrown if the parameter isn't a ctype. examples creating a type "pointer to 32-bit integer" looks like this: var intptrtype = new ctypes.pointertype(ctypes.int32_t); properties property type description targettype ctype the type of object the pointer points to. read only. properties inherited from ctype these properties are available on all ctype objects. ...
... ctype. return value a cdata representing the newly allocated pointer. pointertype cdata properties property type description contents cdata reading this property returns a cdata object referring to the pointed-to contents of the object. writing to this value writes the c conversion of the data into the pointed-to memory. ...
... pointertype cdata method_overview bool isnull() methods inherited from cdata cdata address() string tosource() string tostring() pointertype cdata methods isnull() determines whether or not the pointer's value is null. bool isnull(); parameters none. ...
Debugger.Environment - Firefox Developer Tools
the identifier with a variable, independently of its outer environments. we say an identifier isin scope in an environment if the identifier is bound in that environment or any enclosing environment. 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. spidermonkey creates exactly one debugger.environment instance for each environment it presents via a given debugger instance: if the debugger encounters the same environment through two different routes (perhaps two functions have closed over the same environment), spidermonkey presents the same debugger.environment instance to the debugger each time. this means that the debugger can use the =...
... unable to produce its value, it returns an ordinary javascript object (not a debugger.object instance) whose optimizedout property is true. this is not an invocation function; if this call would cause debuggee code to run (say, because the environment is a "with" environment, andname refers to an accessor property of the with statement’s operand), this call throws a debugger.debuggeewouldrun
exception. setvariable(name,value) storevalue as the value of the variable bound toname in this environment.name must be a string that is a valid ecmascript identifier name;value must be a debuggee value. if this environment binds no variable namedname, throw a referenceerror. this is not an invocation function; if this call would cause debuggee code to run, this call throws a debugger.debuggeewo...
...tvariable(name,value) storevalue as the value of the variable bound toname in this environment.name must be a string that is a valid ecmascript identifier name;value must be a debuggee value. if this environment binds no variable namedname, throw a referenceerror. this is not an invocation function; if this call would cause debuggee code to run, this call throws a debugger.debuggeewouldrun
exception. find(name) return a reference to the innermost environment, starting with this environment, that bindsname. ifname is not in scope in this environment, return null.name must be a string whose value is a valid ecmascript identifier name. source metadata generated from file: js/src/doc/debugger/debugger.environment.md watermark: sha256:3d6f67939e351803d5d7fe201ed38c4aaf766caf032f255...
Web Console remoting - Firefox Developer Tools
t. the pageerror packet is: { "from": "conn0.console9", "type": "pageerror", "pageerror": { "errormessage": "referenceerror: foo is not defined", "sourcename": "http://localhost/~mihai/mozilla/test.js", "linetext": "", "linenumber": 6, "columnnumber": 0, "category": "content javascript", "timestamp": 1347294508210, "error": false, "warning": false, "
exception": true, "strict": false, "private": false, } } the packet is similar to nsiscripterror - for simplicity. we only removed several unneeded properties and changed how flags work. the private flag tells if the error comes from a private window/tab (added in firefox 24). starting with firefox 24 the errormessage and linetext properties can be long string actor grips if the string is ver...
... node is currently selected in the inspector, if any. this nodeactor can then be referred to by the $0 jsterm helper. the response packet: { "from": "conn0.console9", "input": "document", "result": { "type": "object", "classname": "htmldocument", "actor": "conn0.consoleobj20" "extensible": true, "frozen": false, "sealed": false }, "timestamp": 1347306273605, "
exception": null, "
exceptionmessage": null, "helperresult": null }
exception holds the json-ification of the
exception thrown during evaluation.
exceptionmessage holds the
exception.tostring() result. result has the result objectactor instance. helperresult is anything that might come from a jsterm helper result, json stuff (not content objects!). in firefox 23: we renamed the error and error...
...essage": null, "helperresult": null }
exception holds the json-ification of the
exception thrown during evaluation.
exceptionmessage holds the
exception.tostring() result. result has the result objectactor instance. helperresult is anything that might come from a jsterm helper result, json stuff (not content objects!). in firefox 23: we renamed the error and errormessage properties to
exception and
exceptionmessage respectively, to avoid conflict with the default properties used when protocol errors occur. autocomplete and more the autocomplete request packet: { "to": "conn0.console9", "type": "autocomplete", "text": "d", "cursor": 1 } the response packet: { "from": "conn0.console9", "matches": [ "decodeuri", "decodeuricomponent", "defaultstatus", "dev...
AudioNode.disconnect() - Web APIs
disconnected from, with any other, optional, parameters (output and/or input) further limiting which inputs and/or outputs should be disconnected. if this value is an audioparam, then the connection to that audioparam is terminated, and the node's contributions to that computed parameter become 0 going forward once the change takes effect. if no matching connection is found, an invalidaccesserror
exception is thrown. output optional an index describing which output from the current audionode is to be disconnected. the index numbers are defined according to the number of output channels (see audio channels). if this parameter is out-of-bound, an indexsizeerror
exception is thrown. input optional an index describing which input into the specified destination audionode is to be disconnected. the i...
... invalidaccesserror the node on which disconnect() was called isn't connected to the specified destination node. ...
... invalidaccesserror the node on which disconnect() was called isn't connected to the specified destination node. ...
Console.error() - Web APIs
parameters obj1 ... objn a list of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output. ...
... parameters obj1 ... objn a list of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output. ...
... parameters obj1 ... objn a list of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output. ...
HTMLMediaElement.setSinkId() - Web APIs
the htmlmediaelement.setsinkid() method sets the id of the audio device to use for output and returns a promise. this only works when the application is authorized to use the specified device. syntax htmlmediaelement.setsinkid(sinkid).then(function() { ... }) returns a promise that resolves to undefined. parameters sinkid the mediadeviceinfo.deviceid of the audio output device. ...
...element.setsinkid() method sets the id of the audio device to use for output and returns a promise. this only works when the application is authorized to use the specified device. syntax htmlmediaelement.setsinkid(sinkid).then(function() { ... }) returns a promise that resolves to undefined. parameters sinkid the mediadeviceinfo.deviceid of the audio output device. ...
... the audio device to use for output and returns a promise. this only works when the application is authorized to use the specified device. syntax htmlmediaelement.setsinkid(sinkid).then(function() { ... }) returns a promise that resolves to undefined. parameters sinkid the mediadeviceinfo.deviceid of the audio output device. ...
HTMLTableSectionElement - Web APIs
the valign attribute and can have one of the following values: "top", "middle", "bottom", or "baseline". methods inherits methods from its parent, htmlelement. htmltablesectionelement.deleterow() removes the cell at the given position in the section. ...
... specifications specification status comment html living standardthe definition of 'htmltablesectionelement' in that specification. living standard html5the definition of 'htmltablesectionelement' in that specification. recommendation the parameter of insertcell is now optional. ...
...ectionelement' in that specification. living standard html5the definition of 'htmltablesectionelement' in that specification. recommendation the parameter of insertcell is now optional. document object model (dom) level 2 html specificationthe definition of 'htmltablesectionelement' in that specification. obsolete the methods insertrow and deleterow can raise
exceptions. document object model (dom) level 1 specificationthe definition of 'htmltablesectionelement' in that specification. obsolete initial definition. ...
Working with the History API - Web APIs
oo.html, and the document will get a popstate event, this time with a null state object. here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event. 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. clicking the browser's back button (still) does. the pushstate() method pushstate() takes three parameters: a state object; a title (currently ignored); and (optionally), a url. let's examine each of these three parameters in more detail. state object the state object is a javascript object which i...
...ate object. the state object can be anything that can be serialized. because firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. if you pass a state object whose serialized representation is larger than this to pushstate(), the method will throw an
exception. if you need more space than this, you're encouraged to use sessionstorage and/or localstorage. title all browsers but safari currently ignore this parameter, although they may use it in the future. passing the empty string here should be safe against future changes to the method. alternatively, you could pass a short title for the state to which you're moving. url the new history entry...
...given by this parameter. 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. the new url does not need to be absolute; if it's relative, it's resolved relative to the current url. the new url must be of the same origin as the current url; otherwise, pushstate() will throw an
exception. this parameter is optional; if it isn't specified, it's set to the document's current url. note: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) through gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2), the passed object is serialized using json. starting in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3), the object is serialized using the structured clone algori...
IDBCursorSync - Web APIs
you can have only one instance of idbcursorsync representing a cursor, but you can have an unlimited number of cursors at the same time. operations are performed on the underlying index or object store. it enables an application to synchronously process all the records in the cursor's range. method overview bool continue (in optional any key); void remove () raises (idbdatabase
exception); attributes attribute type description count readonly unsigned long long the total number of objects that share the current key. direction readonly unsigned short the direction of traversal of the cursor. see constants for possible values. key readonly any the key for the record at the cursor's position. value an...
... long the total number of objects that share the current key. direction readonly unsigned short the direction of traversal of the cursor. see constants for possible values. key readonly any the key for the record at the cursor's position. value any the value for the record at the cursor's position. setting this attribute can raise an idbdatabase
exception with the following codes: data_err if the underlying object store uses in-line keys and the property at the key path does not match the key in this cursor's position. not_allowed_err if the underlying index or object store does not support updating the record because it is open in the read_only or snapshot_read mode, or if an index record cannot be changed because the un...
...arameter. if no key is specified, advance to the immediate next position. returns false if the cursor has reached the end of its range; otherwise returns true. bool continue ( in optional any key ); parameters key the key to which to move the cursor's position. remove() deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (database
exception);
exceptions this method can raise an idbdatabase
exception with the following code: not_allowed_err if the underlying index or object store does not support updating the record because it is open in the read_only or snapshot_read mode. ...
IDBFactorySync - Web APIs
its need was questionable. it may however be reintroduced in the future if there is enough demand from web developers. the idbfactorysync interface of the indexeddb api provide a synchronous means of accessing the capabilities of indexed databases. ...
...a valid name is any string including the empty string. ...
...tabase with the specified name, it uses that one; otherwise, it creates the database using the specified name and description. idbdatabasesync open ( in domstring name, in domstring description ) raises (idbdatabase
exception); parameters name the name for the database. description the description for the database. returns idbdatabasesync an object to access the open database.
exceptions this method can raise an idbdatabase
exception with the following codes: non_transient_err if the name parameter is not valid. a valid name is any string including the empty string. unknown_err if an error occurs while the database is being opened. ...
IDBRequest.error - Web APIs
the error read-only property of the idbrequest interface returns the error in the event of an unsuccessful request. note: this feature is available in web workers. syntax var myerror = request.error; value a domerror containing the relevant error. in chrome 48+/firefox 58+ this property returns a dom
exception because domerror has been removed from the dom standard. the following error codes are returned under certain conditions: error explanation aborterror if you abort the transaction, then all requests still in progress receive this error. constrainterror if you insert data that doesn't conform to a constraint. it's an
exception type for creating stores and indexes. you get this error, for example, if you try to add a new key that already exists in...
... unknownerror if the operation failed for reasons unrelated to the database itself. a failure due to disk io errors is such an example. noerror if the request succeeds. versionerror if you try to open a database with a version lower than the one it already has. in addition to the error codes sent to the idbrequest object, asynchronous operations can also raise
exceptions. the list describes problems that could occur when the request is being executed, but you might also encounter other problems when the request is being made. for example, if the the request failed and the result is not available, the invalidstateerror
exception is thrown. example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (...
...a android full support 14safari ios full support 8samsung internet android full support 1.5 full support 1.5 no support 1.5 — 7.0prefixed prefixed implemented with the vendor prefix: webkitdom
exception value instead of domerrorchrome full support 48edge full support ≤18firefox full support 58ie no support noopera full support yessafari no support ...
IDBRequest - Web APIs
operations immediately return an idbrequest instance. each request has a readystate that is set to the 'pending' state; this changes to 'done' when the request is completed or fails. when the state is set to done, every request returns a result and an error, and an event is fired on the request. when the state is still pending, any attempt to access the result or error raises an invalidstateerror
exception. ...
... the interface idbopendbrequest is derived from idbrequest. note: this feature is available in web workers. ...
...="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="201" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">idbrequest</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties also inherits properties from eventtarget. idbrequest.error read only returns a dom
exception in the event of an unsuccessful request, indicating what went wrong. idbrequest.result read only returns the result of the request. if the the request failed and the result is not available, an invalidstateerror
exception is thrown. idbrequest.source read only the source of the request, such as an idbindex or an idbobjectstore. if no source exists (such as when calling idbfactory.open),...
LocalFileSystemSync - Web APIs
ed (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. method overview filesystemsync requestfilesystemsync (in unsigned short type, in long long size) raises file
exception; entrysync resolvelocalfilesystemsyncurl (in domstring url) raises file
exception; constants constant value description temporary 0 transient storage that can be be removed by the browser at its discretion. persistent 1 storage that stays in the browser unless the user or the app expunges it. methods requestfilesys...
...l method, window.requestfilesystemsync(). [ research ] filesystemsync requestfilesystemsync( in unsigned short type, in unsigned long long size ); parameters type the storage type of the file system. the values can be either temporary or persistent. size the storage space—in bytes—that you need for your app. returns filesystemsync an object that represents the file system.
exceptions this method can raise an file
exception with the following code:
exception description security_error the application does not have permission to access the file system interface. for example, you cannot run from file://. for more details, see the article on basic concepts. resolvelocalfilesystemsyncurl() allows the user to look up the entry for a file or directo...
...t run from file://. for more details, see the article on basic concepts. resolvelocalfilesystemsyncurl() allows the user to look up the entry for a file or directory referred to by a local url. void resolvelocalfilesystemurl( in domstring url ); parameter url the url of a local file in the file system. returns entrysync an object that represents entries in the file system.
exceptions this method can raise a file
exception with the following codes:
exception description encoding_err the syntax of the url was invalid. not_found_err the url was structurally correct, but refers to a resource that does not exist. security_err the application does not have permission to access the file system interface. browser compatibil...
MediaRecorder.onerror - Web APIs
the mediarecorder interface's onerror event handler is called by the mediastream recording api when an error occurs. you can provide an event handler to deal with errors that occur while creating or using a media recorder. the error object is of type mediarecordererrorevent, and its error property contains a dom
exception object that describes the error that occurred. 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 specifically possible when using the mediastream recording api; to determine which occurred, check the value of mediarecordererrorevent.error.name. invalidstateerror an attempt was made to stop or pause or an i...
... general errors that might occur, the following errors are specifically possible when using the mediastream recording api; to determine which occurred, check the value of mediarecordererrorevent.error.name. invalidstateerror an attempt was made to stop or pause or an inactive recorder, start or resume an active recorder, or otherwise manipulate the mediarecorder while in the wrong state. this
exception can also occur when a request is made on a source that has been deleted or removed. securityerror the mediastream is configured to disallow recording. this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device. this also happens when a mediastreamtrack within the stream is marked as isolated due to the peeridentity const...
...a, and finally a stop event is sent. these errors may occur either directly because of a call to a mediarecorder method, or indirectly due to a problem arising during the recording process. example this example creates a new mediarecorder instance and starts recording using the user agent's default media format. it returns either the mediarecorder or the name of the error that occurred if any
exceptions are thrown during the setup process. function recordstream(stream) { let recorder = null; let bufferlist = []; try { recorder = new mediarecorder(stream); } catch(err) { return err.name; /* return the error name */ } recorder.ondataavailable = function(event) { bufferlist.push(event.data); }; recorder.onerror = function(event) { let error = event.error; ...
Node.removeChild() - Web APIs
r code, via the oldchild object reference. 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 automatically deleted from memory after a short time. if child is actually not a child of the element node, the method throws an
exception. ...
...trievable, and will usually be automatically deleted from memory after a short time. if child is actually not a child of the element node, the method throws an
exception. ...
... an
exception. 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. if the child doesn't exist on the dom of the page, the method throws the following
exception: uncaught typeerror: failed to execute 'removechild' on 'node': parameter 1 is not of type 'node'. examples simple examples given this html: <div id="top"> <div ...
SVGMarkerElement - Web APIs
tribute orient; otherwise, it will be set to zero. methods this also inherits methods from its parent, svgelement, and implements properties from svgstylable. setorienttoangle(in svgangle angle) void sets the value of attribute orient to the given angle. ...
... to zero. methods this also inherits methods from its parent, svgelement, and implements properties from svgstylable. setorienttoangle(in svgangle angle) void sets the value of attribute orient to the given angle. ...
... sets the value of attribute orient to the given angle.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the object itself is read only. setorienttoauto() void sets the value of attribute orient to 'auto'.
exceptions: a dom
exception with code no_modification_allowed_err is raised when the object itself is read only. browser compatibility desktop mobile chrome edge firefox interne...
TextDecoder() - Web APIs
syntax decoder = new textdecoder(utflabel, options); parameters utflabeloptional is a domstring, defaulting to "utf-8", containing the label of the encoder. ...
... specifications...
...nary with the property: fatal a boolean flag indicating if the textdecoder.decode() method must throw a dom
exception with the "encodingerror" value when an coding error is found. it defaults to false. example var textdecoder1 = new textdecoder("iso-8859-2"); var textdecoder2 = new textdecoder(); var textdecoder3 = new textdecoder("csiso2022kr", {fatal: true}); // allows encodingerror
exception to be thrown. var textdecoder4 = new textdecoder("iso-2022-cn"); // throw a typeerror
exception. specifications specification status comment encodingthe definition of 'textdecoder()' in that specification. living standard initial definition. ...
URL() - Web APIs
the url() constructor returns a newly created url object representing the url defined by the parameters. if the given base url or the resulting url are not valid urls, the javascript typeerror
exception is thrown. note: this feature is available in web workers. syntax const url = new url(url [, base]) parameters url a usvstring representing an absolute or relative url. if url is a relative url, base is required, and will be used as the base url. if url is an absolute url, a given base will be ignored. base optional a usvstring representing the base url to use in case url is a relative url. ...
...relative url. if url is a relative url, base is required, and will be used as the base url. if url is an absolute url, a given base will be ignored. base optional a usvstring representing the base url to use in case url is a relative url. if not specified, it defaults to ''. note: you can still use an existing url object for the base, which stringifies itself to the object's href property.
exceptions
exception explanation typeerror url (in the case of absolute urls) or base + url (in the case of relative urls) is not a valid url. examples // base urls let m = 'https://developer.mozilla.org'; let a = new url("/", m); // => 'https://developer.mozilla.org/' let b = new url(m); // => 'https://...
...cs' new url('/docs', a); // => 'https://developer.mozilla.org/docs' new url('/docs', "https://developer.mozilla.org/fr-fr/toto"); // => 'https://developer.mozilla.org/docs' new url('/docs', ''); // raises a typeerror
exception as '' is not a valid url new url('/docs'); // raises a typeerror
exception as '/docs' is not a valid url new url('http://www.example.com', ); // => 'http://www.example.com/' new url('http://www.example.com', b); // => 'http://www.example.com/' new url("//foo.com", "https://example.com") // => 'https://foo.com' (see rela...
Writing a WebSocket server in Java - Web APIs
ie 10 and higher. first steps websockets communicate over a tcp (transmission control protocol) connection. java's serversocket class is located in the java.net package. serversocket constructor: serversocket(int port) when you instantiate the serversocket class, it is bound to the port number you specified by the port argument. ...
...uctor: serversocket(int port) when you instantiate the serversocket class, it is bound to the port number you specified by the port argument. ...
...io.io
exception; import java.io.inputstream; import java.io.outputstream; import java.net.serversocket; import java.net.socket; import java.security.messagedigest; import java.security.nosuchalgorithm
exception; import java.util.base64; import java.util.scanner; import java.util.regex.matcher; import java.util.regex.pattern; public class websocket { public static void main(string[] args) throws io
exception, nosuchalgorithm
exception { serversocket server = new serversocket(80); try { system.out.println("server has started on 127.0.0.1:80.\r\nwaiting for a connection..."); socket client = server.accept(); system.out.println("a client connected."); socket methods: java.net.socket getinputstream() returns an input stream for this socket. java.net.socket getoutputstream() returns ...
Using Web Workers - Web APIs
at are utilized by a single script; shared workers use sharedworkerglobalscope). a dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts. note: see the web workers api landing page for reference documentation on workers and additional guides. you can run whatever code you like inside the worker thread, with some
exceptions. for example, you can't directly manipulate the dom from inside a worker, or use some default methods and properties of the window object. but you can use a large number of items available under window, including websockets, and data storage mechanisms like indexeddb. see functions and classes available to workers for more details. data is sent between workers and the main thread via a system o...
...ir messages using the postmessage() method, and respond to messages via the onmessage event handler (the message is contained within the message event's data attribute.) the data is copied rather than shared. workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. in addition, workers may use xmlhttprequest for network i/o, with the
exception that the responsexml and channel attributes on xmlhttprequest always return null. dedicated workers as mentioned above, a dedicated worker is only accessible by the script that called it. in this section we'll discuss the javascript found in our basic dedicated worker example (run dedicated worker): this allows you to enter two numbers to be multiplied together. the numbers are sent to a dedica...
...content-security-policy: script-src 'self' among other things, this will prevent any scripts it includes from using eval(). however, if the script constructs a worker, code running in the worker's context will be allowed to use eval(). to specify a content security policy for the worker, set a content-security-policy response header for the request which delivered the worker script itself. the
exception to this is if the worker script's origin is a globally unique identifier (for example, if its url has a scheme of data or blob). in this case, the worker does inherit the csp of the document or worker that created it. transferring data to and from workers: further details data passed between the main page and workers is copied, not shared. objects are serialized as they're handed to the worke...
XPathEvaluator.evaluate() - Web APIs
evaluating the expression. this must be one of the xpathresult.constants. result optional allows to specify a result object which may be reused and returned by this method. if this is specified as null or the implementation does not reuse the specified result, a new result object will be returned. return value an xpathresult object representing the result of evaluating the xpath expression.
exceptions invalid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpath
exception of type invalid_expression_err is raised. type_err in case result cannot be converted to the specified type, an xpath
exception of type type_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, ...
...valid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpath
exception of type invalid_expression_err is raised. type_err in case result cannot be converted to the specified type, an xpath
exception of type type_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a dom
exception of type namespace_error is raised. wrong_document_err if the provided context node is from a document that is not supported by the xpathevaluator, a dom
exception of type wrong_document_err is raised. ...
... example the following example shows the use of the evaluate() method. ...
XPathExpression.evaluate() - Web APIs
evaluating the expression. this must be one of the xpathresult.constants. result optional allows to specify a result object which may be reused and returned by this method. if this is specified as null or the implementation does not reuse the specified result, a new result object will be returned. return value an xpathresult object representing the result of evaluating the xpath expression.
exceptions invalid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpath
exception of type invalid_expression_err is raised. type_err in case result cannot be converted to the specified type, an xpath
exception of type type_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, ...
...valid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpath
exception of type invalid_expression_err is raised. type_err in case result cannot be converted to the specified type, an xpath
exception of type type_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a dom
exception of type namespace_error is raised. wrong_document_err if the provided context node is from a document that is not supported by the xpathevaluator, a dom
exception of type wrong_document_err is raised. ...
... example the following example shows the use of the evaluate() method. ...
Specificity - CSS: Cascading Style Sheets
e no effect on specificity. (the selectors declared inside :not() do, however.) for more information, visit: "specificity" in "cascade and inheritance", you can also visit: https://specifishity.com inline styles added to an element (e.g., style="font-weight: bold;") always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity. the !important
exception when an important rule is used on a style declaration, this declaration overrides any other declarations. although technically !important has nothing to do with specificity, it interacts directly with it. using !important, however, is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets. when two conflicting declaratio...
...but selectors placed into the pseudo-class count as normal selectors when determining the count of selector types. this chunk of css ... div.outer p { color: orange; } div:not(.outer) p { color: blueviolet; } ... when used with the following html ...
...ormal selectors when determining the count of selector types. this chunk of css ... div.outer p { color: orange; } div:not(.outer) p { color: blueviolet; } ... when used with the following html ... <div class="outer"> <p>this is in the outer div.</p> <div class="inner"> <p>this text is in the inner div.</p> </div> </div> ... appears on the screen like this: the :where()
exception the specificity-adjustment pseudo-class :where() always has its specificity replaced with zero. this chunk of css ... div:where(.outer) p { color: orange; } div p { color: blueviolet; } #no-where-support { margin: 0.5em; border: 1px solid red; } #no-where-support:where(*) { display: none !important; } ... when used with the following html ... <div id="no-where-suppor...
Browser detection using the user agent - HTTP
. see the mobile device detection section for more information. another such case is for fixing bugs in browsers that do not automatically update. internet explorer (on windows) and webkit (on ios) are two perfect examples. prior to version 9, internet explorer had unbelievable issues with rendering bugs, css bugs, api bugs, and so forth. however, internet explorer was such a special little wasp
exception prior to version 9 that it was very easy to detect the browser based upon the browser-specific features available. webkit is a bit worse because apple forces all of the browsers on ios to use webkit internally, thus the user has no way to get a better more updated browser on older devices. most bugs can be detected, but some bugs take more effort to detect than others. in such cases, it might be ...
...y actually want "rendering engine detection". do you actually want to detect firefox, as opposed to seamonkey, or chrome as opposed to chromium? or do you actually simply want to see if the browser is using the gecko or the webkit rendering engine? if this is what you need, see further down the page. most browsers set the name and version in the format browsername/versionnumber, with the notable
exception of internet explorer. but as the name is not the only information in a user agent string that is in that format, you can not discover the name of the browser, you can only check if the name you are looking for. but note that some browsers are lying: chrome for example reports both as chrome and safari. so to detect safari you have to check for the safari string and the absence of the chrome strin...
... string edgehtml edge/xyz the non-chromium edge puts its engine version after the edge/ token, not the application version. note: edgehtml is no longer used in edge browser builds >= version 79 (see 'blink'). blink chrome/xyz rendering engine version most rendering engines put the version number in the renderingengine/versionnumber token, with the notable
exception of gecko. gecko puts the gecko version number in the comment part of the user agent after the rv: string. from gecko 14 for the mobile version and gecko 17 for the desktop version, it also puts this value in the gecko/version token (previous version put there the build date, then a fixed date called the geckotrail). os the operating system is given in most user agent strings (although not web-f...
Proxy Auto-Configuration (PAC) file - HTTP
xy w3proxy.mozilla.org:8080; direct"; } } note: this is the simplest and most efficient autoconfig file for cases where there's only one proxy. ...
...be careful to note the parentheses around the or expression before the and expression to achieve the above-mentioned efficient behaviour. example 3 use prox...
...lla.org") && !localhostordoaminis(host, "merchant.mozilla.org") ) { return "direct"; } else { return "proxy w3proxy.mozilla.org:8080; direct"; } } the above example will use the proxy for everything except local hosts in the mozilla.org domain, with the further
exception that hosts www.mozilla.org and merchant.mozilla.org will go through the proxy. note the order of the above
exceptions for efficiency: localhostordomainis() functions only get executed for urls that are in local domain, not for every url. be careful to note the parentheses around the or expression before the and expression to achieve the above-mentioned efficient behaviour. example 3 use proxy only if cannot resolve host this example will work in an environment where the internal dns server is set up so that...
Meta programming - JavaScript
reported as existent if it does not exists as an own property of target and target is not extensible. a property cannot be reported as non-configurable if it does not exist as an own property of target or if it exists as a configurable own property of target. the result of object.getownpropertydescriptor(target) can be applied to target using object.defineproperty and will not throw an
exception. handler.defineproperty() object.defineproperty() reflect.defineproperty() a property cannot be added if target is not extensible. a property cannot be added as (or modified to be) non-configurable if it does not exist as a non-configurable own property of target. a property may not be non-configurable if a corresponding configurable property of ta...
...rget is not extensible. a property cannot be added as (or modified to be) non-configurable if it does not exist as a non-configurable own property of target. a property may not be non-configurable if a corresponding configurable property of target exists. if a property has a corresponding target object property, then object.defineproperty(target, prop, descriptor) will not throw an
exception. in strict mode, a false value returned from the defineproperty handler will throw a typeerror
exception. handler.has() property query foo in proxy inherited property query foo in object.create(proxy) reflect.has() a property cannot be reported as non-existent, if it exists as a non-configurable own property of target...
...e different from the value of the corresponding target property if the corresponding target property is a non-writable, non-configurable data property. cannot set the value of a property if the corresponding target property is a non-configurable accessor property that has undefined as its [[set]] attribute. in strict mode, a false return value from the set handler will throw a typeerror
exception. handler.deleteproperty() property deletion delete proxy[foo] delete proxy.foo reflect.deleteproperty() a property cannot be deleted if it exists as a non-configurable own property of target. handler.enumerate() property enumeration / for...in: for (let name in proxy) {...} reflect.enumerate() ...
Inheritance and the prototype chain - JavaScript
ck its prototype. // is there a 'd' own property on o.[[prototype]]? no, check its prototype. // o.[[prototype]].[[prototype]] is object.prototype and there is no 'd' property by default, check its prototype. // o.[[prototype]].[[prototype]].[[prototype]] is null, stop searching, // no property found, return undefined. code link setting a property to an object creates an own property. the only
exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter. inheriting "methods" javascript does not have "methods" in the form that class-based languages define them. in javascript, any function can be added to an object in the form of a property. an inherited function acts just as any other property, including property shadowing as shown above (...
...he enter/return key. (the console is included in most web browser's developer tools. more information is available for firefox developer tools, chrome devtools, and edge devtools.) function dosomething(){} console.log( dosomething.prototype ); // it does not matter how you declare the function, a // function in javascript will always have a default // prototype property. // (ps: there is one
exception that arrow function doesn't have a default prototype property) var dosomething = function(){}; console.log( dosomething.prototype ); as seen above, dosomething() has a default prototype property, as demonstrated by the console. after running this code, the console should have displayed an object that looks similar to this. { constructor: ƒ dosomething(), __proto__: { construct...
... var inst = { __proto__: { bar_prop: "bar val", __proto__: { foo_prop: "foo val", __proto__: object.prototype } } }; console.log(inst.foo_prop); console.log(inst.bar_prop) support in all in-use-today browsers which are all non-microsoft browsers plus ie11 and up. setting __proto__ to something that is not an object only fails silently. it does not throw an
exception. grossly deprecated and non-performant. making your javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some brows...
EvalError() constructor - JavaScript
however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
...however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
...however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
Introduction to using XPath in JavaScript - XPath
h expressions and the possibly different prefixes used in the document. the function can be either: created by using the creatensresolver method of a xpathevaluator object. you should use this virtually all of the time. null, which can be used for html documents or when no namespace prefixes are used. note that, if the xpathexpression contains a namespace prefix, this will result in a dom
exception being thrown with the code namespace_err. a custom user-defined function. see the using a user defined namespace resolver section in the appendix for details. resulttype: a constant that specifies the desired result type to be returned as a result of the evaluation. the most commonly passed constant is xpathresult.any_type which will return the results of the xpath expression as the most...
... node-set types the xpathresult object allows node-sets to be returned in 3 principal different types: iterators snapshots first nodes iterators when the specified result type in the resulttype parameter is either: unordered_node_iterator_type ordered_node_iterator_type the xpathresult object returned is a node-set of matched nodes which will behave...
...contained by using the iteratenext() method of the xpathresult. once we have iterated over all of the individual matched nodes, iteratenext() will return null. note however, that if the document is mutated (the document tree is modified) between iterations that will invalidate the iteration and the invaliditeratorstate property of xpathresult is set to true, and a ns_error_dom_invalid_state_err
exception is thrown. iterator example var iterator = document.evaluate('//phonenumber', documentnode, null, xpathresult.unordered_node_iterator_type, null ); try { var thisnode = iterator.iteratenext(); while (thisnode) { alert( thisnode.textcontent ); thisnode = iterator.iteratenext(); } } catch (e) { alert( 'error: document tree modified during iteration ' + e ); } snapshots when ...
selection - Archive of obsolete content
"\\\" + selection.html + "///"; }); globals properties text gets or sets the current selection as plain text. setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. getting the selection when there is no current selection returns null. setting the selection when there is no current selection throws an
exception. getting the selection when iscontiguous is true returns the text of the first selection. html gets or sets the current selection as html. setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. getting the selection when there is no current selection returns null. setting the selection when there is no c...
...n iscontiguous is true returns the text of the first selection. html gets or sets the current selection as html. setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. getting the selection when there is no current selection returns null. setting the selection when there is no current selection throws an
exception. getting the selection when iscontiguous is true returns the text of the first selection. iscontiguous true if the current selection is a single, contiguous selection, and false if there are two or more discrete selections, each of which may or may not be spatially adjacent. (discontiguous selections can be created by the user with ctrl+click-and-drag.) events select this event is emitted wh...
url - Archive of obsolete content
constructors url(source, base) the url constructor creates an object that represents a url, verifying that the provided string is a valid url in the process. any api in the sdk which has a url parameter will accept url objects, not raw strings, unless otherwise noted. parameters source : string a string to be converted into a url. if source is not a valid uri, this constructor will throw an
exception. base : string an optional string used to resolve relative source urls into absolute ones. dataurl(uri) the dataurl constructor creates an object that represents a data: url, verifying that the provided string is a valid data: url in the process. parameters uri : string a string to be parsed as data url. if is not a valid uri, this constructor will throw an
exception. functions tofilenam...
... parameters url : string the url, as a string, to be converted. returns string : the converted native file path as a string. ...
io/byte-streams - Archive of obsolete content
the backing stream, an nsiinputstream. bytewriter(outputstream) creates a binary output stream that writes bytes to a backing stream. you can also create bytewriter objects using io/file's open() function. parameters outputstream : stream the backing stream, an nsioutputstream. bytereader methods close() closes both the stream and its backing stream. if the stream is already closed, an
exception is thrown. read(numbytes) reads a string from the stream. if the stream is closed, an
exception is thrown. parameters numbytes : number the number of bytes to read. if not given, the remainder of the entire stream is read. returns string : a string containing the bytes read. if the stream is at the end, returns the empty string. properties closed true if the stream is closed. bytewrite...
...rown. parameters numbytes : number the number of bytes to read. if not given, the remainder of the entire stream is read. returns string : a string containing the bytes read. if the stream is at the end, returns the empty string. properties closed true if the stream is closed. bytewriter methods close() closes both the stream and its backing stream. if the stream is already closed, an
exception is thrown. write(str) writes a string to the stream. if the stream is closed, an
exception is thrown. parameters str : string the string to write. properties closed true if the stream is closed. ...
util/deprecate - Archive of obsolete content
experimental functions to deprecate code. globals functions deprecatefunction(fun, msg) dump to the console the error message given in the second argument, prefixed with "deprecated:", and print the stacktrace; then execute the function passed as first argument and returns its value. it does not raise an
exception, but just displays the error message and continues to execute the function. this function is mostly used to flag usage of deprecated functions, that are still available but which we intend to remove in a future release. parameters fun : function the function to execute after the error message msg : string the error message to display returns * : the returned value from fun deprecateusage(msg) dump to the console the error message given, prefixed with "deprecated:", and ...
...cated functions, that are still available but which we intend to remove in a future release. parameters fun : function the function to execute after the error message msg : string the error message to display returns * : the returned value from fun deprecateusage(msg) dump to the console the error message given, prefixed with "deprecated:", and print the stacktrace. it does not raise an
exception, but just displays the error message and returns. this function is mostly used to flag usage of deprecated functions that are no longer available. parameters msg : string the error message to display ...
Chrome Authority - Archive of obsolete content
ay be able to sneak around these restrictions). the manifest is built with a simple regexp-based scanner, not a full javascript parser. developers should stick to simple require statements, with a single static string, one per line of code. if the scanner fails to see a require entry, the manifest will not include that entry, and (once the implementation is complete) the runtime code will get an
exception. ...
...r, not a full javascript parser. developers should stick to simple require statements, with a single static string, one per line of code. if the scanner fails to see a require entry, the manifest will not include that entry, and (once the implementation is complete) the runtime code will get an
exception. ...
JavaScript Debugger Service - Archive of obsolete content
ook = { 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. jsd.errorhook = { onerror: function(message, filename, lineno, colno, flags, errnum, exc) { dump(message + "@" + filename + "@" + lineno + "@" + colno + "@" + errnum + "\n"); // check message type var jsdierrorhook = components.interfaces.jsdierrorhook; var messagetype; if (flags & jsdierrorhook.report_error) messagetype = "error"; if (flags & jsdierrorhook.report_warning...
..., colno, flags, errnum, exc) { dump(message + "@" + filename + "@" + lineno + "@" + colno + "@" + errnum + "\n"); // check message type var jsdierrorhook = components.interfaces.jsdierrorhook; var messagetype; if (flags & jsdierrorhook.report_error) messagetype = "error"; if (flags & jsdierrorhook.report_warning) messagetype = "warning"; if (flags & jsdierrorhook.report_
exception) messagetype = "uncaught-
exception"; if (flags & jsdierrorhook.report_strict) messagetype += "-strict"; dump(messagetype + "\n"); return false; // trigger debughook // return true; if you do not wish to trigger debughook } }; // note that debughook does not _always_ trigger when jsd.errorhook[onerror] returns false // it is not well-known why debughook sometimes fails to trigg...
The Essentials of an Extension - Archive of obsolete content
chrome://mozapps/content/downloads/downloads.xul on your location bar and press enter. surprised? you just opened the downloads window in a firefox tab! you can access any chrome file by just typing its uri in the location bar. this can come in handy if you want to inspect script files that are part of firefox, other extensions, or your own. most of these files are opened as text files, with the
exception of xul files, which are executed and displayed like you would normally see them on a window. content there are 2 files in the content directory. let's look at the xul file first. xul files are xml files that define the user interface elements in firefox and firefox extensions. xul was inspired by html, so you'll see many similarities between the two. however, xul is also an improvement over ht...
...length is not having lines longer than 80 characters. this feels very restrictive, specially with xml files, but the number was chosen to allow pretty much any text editor to handle these files easily. even old command line editors work well with files that cut their lines at 80 characters. the tabulation is very straightforward: 2 blank space indents. we never use actual tab characters, with the
exception of makefiles, which will be covered later on. most of our coding standards are based on mozilla's or other known and used standards. we'll skip some code that is covered in the locale section, moving on to the most important part of the content: <menubar id="main-menubar"> <menu id="xulschoolhello-hello-menu" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.hellomenu.ac...
cert_override.txt - Archive of obsolete content
the syntax is described on this web site. example here is an example for a sha1-256 hash algorithm. the key and the website are not valid: # psm certificate override settings file # this is a generated file! do not edit. ...
...the syntax is described on this web site. example here is an example for a sha1-256 hash algorithm. the key and the website are not valid: # psm certificate override settings file # this is a generated file! do not edit. ...
Using Breakpoints in Venkman - Archive of obsolete content
zero, non-undefined, and non-false value will do), execution will continue normally. if, on the other hand, the script returns a false value, venkman will stop execution at that point. early return from caller with 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. ...
..., execution will continue normally. if, on the other hand, the script returns a false value, venkman will stop execution at that point. early return from caller with 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. the pass
exceptions to caller checkbox allows you to pass
exceptions thrown by the breakpoint script directly to the caller. normally, if the breakpoint script generates an
exception, venkman assumes you made a mistake and stops execution after displaying the
exception. if you would like to see what your code does when
exceptions are thrown at it, check "pass
exceptions to caller", and thrown an
exception from the breakpoint script. the log result checkbox tell...
Introduction to XUL - Archive of obsolete content
e documents describing those particular applications. check the xptoolkit index for the most recent list. since xul is a language for describing window layout, there is some overlap in the topics covered by this document and a separate document describing xul windows. the task of writing a xul window description is basically 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. these elements are widgets and certain infrastructure associated with the behaviour of the window, explained below. most of the details of writing a xul document are identical to those for writing an xml document, a description of which we will leave to other excellent xml documentation which we assu...
...ll want to store xul in *.xul files. a xul file can contain xml elements and html elements, as well as special elements unique to xul: xul elements. namespace declarations for xul (and html, if html elements are used) must be included in the file. namespaces must be treated carefully. correct namespace usage dictates that the namespace be used only for the tag, not in individual attributes. rare
exceptions to this rule are bugs. xul file preamble xul is xml, and a good xul file begins with the standard xml version and doctype statements. since xml has no implicit display semantics, there must always be associated stylesheets. mozilla includes a standard stylesheet, "xul.css". you can load as many style sheets as you wish using repeated processing directives, although you should always make sure...
Writing Skinnable XUL and CSS - Archive of obsolete content
xplicitly. this is done using an @import directive placed at the top of the file. @import url(chrome://global/skin/) ... rest of skin file ... css files for a skin fall into two categories: base skin files and derived skin files. css files that import another skin file are calledderived skin files. css files that don't import another skin file are calledbase skin files. there is one notable
exception to this rule. skin files that don't import any other skin files, but that are only intended to be used in the context of another component's skin are also considered derived skin files, since they are implicitly importing information from the other component's skin. these sorts of files are typically used with reusable overlayable widgets (e.g., the sidebar). your css file should never import an...
...or this button. it should only describe the icon. because the button is used in the navigator window (through overlays), the fonts/colors used should not be described by messenger. this allows the button to blend in as much as possible regardless of where it is used. the importance of this rule cannot be overstated. derived skin files should not contain any rules for colors, fonts, or borders.
exceptions to this rule must be approved in order to be allowed into the product. note that in our current designed mozilla skin (aside from global) every single css file is a derived skin file, so this applies to all of you!!! derived skin files should not attempt to change the default look for a widget. for example, there should never be any css rules of the form tagname {...}; in a derived skin file.
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 automatically detect minified js files and pretty-print them. pause on
exceptions when this option is enabled, execution of the script will automatically pause whenever a javascript
exception is thrown. ...
...s 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 automatically detect minified js files and pretty-print them. pause on
exceptions when this option is enabled, execution of the script will automatically pause whenever a javascript
exception is thrown. ignore caught
exceptions if this option is set (it is set by default) and "pause on
exceptions" is set, then execution will pause on an
exception only if that
exception is not caught. this is usually the behavior you want. you don't generally want to pause execution when an
exception that is thrown is caught, since that generally indicates that your program is handling it properly. show panes o...
Browser Detection and Cross Browser Support - Archive of obsolete content
de these users with alternative unscripted versions of your pages or to at least notify them of the need to use scripting in order to view your content properly. since browsers such as netscape navigator 4 and internet explorer 4 do not support some of the most recent additions to the javascript (ecmascript) standard, it is often necessary to limit the use of advanced javascript features such as
exception processing. one approach is to require that users of browsers which do not support the level of javascript used in your content to turn off javascript in order to be able to use your content. you can do this by providing an error message for users of older browsers as well as alternative content contained in noscript tags. <html> <head> <title>noscript</title> </head> <body> <scrip...
...</head> <body> <script language="javascript"> window.onerror = function () { // redirect user to a page describing the limitations // of their browser and requesting that they turn off // javascript in order to view your site. } // netscape navigator 4 will throw an error // on any javascript which attempts to use // try ... catch
exception processing. try { // code to implement fancy menu } catch (errors) { // handle
exceptions } </script> <noscript> <!-- if javascript is not enabled, then the browser will display the contents of the noscript tag which in this case is a simple menu implemented as an unordered list. --> <ul> ...
LiveConnect - Archive of obsolete content
or remove as needed.) while the bloated liveconnect code in the mozilla source was removed in version 1.9.2 of the platform (see bug 442399), its former api has been restored (see also the specification and this thread) (building on npapi?), and as of java 6 update 12, extensions as well as applets can make use of this restored api. the reimplementation also restores the ability to use try-catch
exceptions within javascript, and is free of the increasing number of other bugs introduced by the decline of the original liveconnect (e.g., java.lang.string and arrays not working properly). 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 ...
...ion by javascript code (e.g. by writing code like "new java.lang.string('javascript string')" for classes in the java.* package hierarchy, or using a new "packages" object for classes outside this hierarchy). old liveconnect documents, broken links: java method overloading and liveconnect 3 the technique that liveconnect uses to invoke overloaded java methods from javascript. liveconnect
exceptions how do java and javascript catch
exceptions generated by the other party? liveconnect testcases determine that applets within different html tags work properly. 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 ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
hanics an entity header is an http header that can be used in an http request or response, and describes the content of the body of themessage. headers like content-length, content-language, content-encoding are entities headers. 135 event codingscripting, glossary events are assets generated by dom elements, which can be manipulated by a javascript code. 136
exception beginner, codingscripting, glossary an
exception is a condition that interrupts normal code execution. in javascript syntax errors are a very common source of
exceptions. 137 expando codingscripting, javascript, reference, expando expando properties are properties added to dom nodes with javascript, where those properties are not part of the object's dom specificati...
...ear to instantly as possible). 443 syntax codingscripting, glossary, syntax syntax specifies the required combination and sequence of characters making up correctly structured code. syntax generally includes grammar and the rules that apply to writing it, such as indentation requirements in python. 444 syntax error codingscripting, glossary, javascript an
exception caused by the incorrect use of a pre-defined syntax. syntax errors are detected while compiling or parsing source code. 445 synthetic monitoring glossary, rum, reference, synthetic monitoring, web performance synthetic monitoring involves monitoring the performance of a page in a 'laboratory' environment, typically with automation tooling in an environment that is as consiste...
WAI-ARIA basics - Learn web development
idea of support levels by looking at powermapper's wai-aria screen reader compatibility article. in this article, we won't attempt to cover every wai-aria feature, and its exact support details. instead, we will cover the most critical wai-aria features for you to know about; if we don't mention any support details, you can assume that the feature is well-supported. we will clearly mention any
exceptions to this. note: some javascript libraries support wai-aria, meaning that when they generate ui features like complex form controls, they add aria attributes to improve the accessibility of those features. if you are looking for a 3rd party javascript solution for rapid ui development, you should definitely consider the accessibility of its ui widgets as an important factor when making your choi...
.... polite: updates should be announced only if the user is idle. assertive: updates should be announced to the user as soon as possible. we'd like you to take a copy of aria-no-live.html and quotes.json, and update your <section> tag as follows: <section aria-live="assertive"> this will cause a screenreader to read out the content as it is updated. note: most browsers will throw a security
exception if you try to do an xmlhttprequest call from a file:// url, e.g. if you just load the file by loading it directly into the browser (via double clicking, etc.). to get it to run, you will need to upload it to a web server, for example using github, or a local web server like python's simplehttpserver. there is an additional consideration here — only the bit of text that updates is read out. it...
Web fonts - Learn web development
e finished example live). using an online font service online font services generally store and serve fonts for you, so you don't have to worry about writing the @font-face code, and generally just need to insert a simple line or two of code into your site to make everything work. examples include adobe fonts and cloud.typography. most of these services are subscription-based, with the notable
exception of google fonts, a useful free service, especially for rapid testing work and writing demos. most of these services are easy to use, so we won't cover them in great detail. let's have a quick look at google fonts, so you can get the idea. again, use copies of web-font-start.html and web-font-start.css as your starting point. go to google fonts. use the filters on the left-hand side to displa...
... case is optional, but it is useful to declare it because it allows browsers to find a font they can use faster. multiple declarations can be listed, separated by commas — the browser will search through them and use the first one it can find that it understands — it is therefore best to put newer, better formats like woff2 earlier on, and older, not so good formats like ttf later on. the one
exception to this is the eot fonts — they are placed first to fix a couple of bugs in older versions of ie whereby it will try to use the first thing it finds, even if it can't actually use the font. font-weight/font-style: these lines specify what weight the font has, and whether it is italic or not. if you are importing multiple weights of the same font, you can specify what their weight/style is and ...
What is a URL? - Learn web development
p, url is one of the key concepts of the web. it is the mechanism used by browsers to retrieve any published resource on the web. url stands for uniform resource locator. a url is nothing more than the address of a given unique resource on the web. in theory, each valid url points to a unique resource. such resources can be an html page, a css document, an image, etc. in practice, there are some
exceptions, the most common being a url pointing to a resource that no longer exists or that has moved. as the resource represented by the url and the url itself are handled by the web server, it is up to the owner of the web server to carefully manage that resource and its associated url. active learning there is no active learning available yet. deeper dive basics: anatomy of a url here are some exa...
...isplay media such as images (with the <img> element), videos (with the <video> element), sounds and music (with the <audio> element), etc.; to display other html documents with the <iframe> element. note: when specifying urls to load resources as part of a page (such as when using the <script>, <audio>, <img>, <video>, and the like), you should generally only use http and https urls, with few
exceptions (one notable one being data:; see data urls). using ftp, for example, is not secure and is no longer supported by modern browsers. other technologies, such as css or javascript, use urls extensively, and these are really the heart of the web. absolute urls vs relative urls what we saw above is called an absolute url, but there is also something called a relative url. let's examine what that ...
Drawing graphics - Learn web development
browser; the below example shows a simple rotating webgl cube: this article will focus mainly on 2d canvas, as raw webgl code is very complex. we will however show how to use a webgl library to create a 3d scene more easily, and you can find a tutorial covering raw webgl elsewhere — see getting started with webgl. note: basic canvas functionality is supported well across browsers, with the
exception of ie 8 and below for 2d canvas, and ie 11 and below for webgl. active learning: getting started with a <canvas> if you want to create a 2d or 3d scene on a web page, you need to start with an html <canvas> element. this element is used to define the area on the page into which the image will be drawn. this is as simple as including the element on the page: <canvas width="320" height="240"></...
...ordinate, it would appear 85 pixels lower than the mouse position. function draw() { if(pressed) { ctx.fillstyle = colorpicker.value; ctx.beginpath(); ctx.arc(curx, cury-85, sizepicker.value, degtorad(0), degtorad(360), false); ctx.fill(); } requestanimationframe(draw); } draw(); note: the <input> range and color types are supported fairly well across browsers, with the
exception of internet explorer versions less than 10; also safari doesn't yet support color. if your browser doesn't support these inputs, they will fall back to simple text fields and you'll just have to enter valid color/number values yourself. webgl it's now time to leave 2d behind, and take a quick look at 3d canvas. 3d canvas content is specified using the webgl api, which is a completely separate ...
Starting our Svelte Todo list app - Learn web development
todo --> <form> <h2 class="label-wrapper"> <label for="todo-0" class="label__lg"> what needs to be done? ...
... clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); white-space: nowrap; } [class*="stack"] > * { margin-top: 0; margin-bottom: 0; } .stack-small > * + * { margin-top: 1.25rem; } .stack-large > * + * { margin-top: 2.5rem; } @media screen and (min-width: 550px) { .stack-small > * + * { margin-top: 1.4rem; } .stack-large > * + * { margin-top: 2.8rem; } } .stack-
exception { margin-top: 1.2rem; } /* end global styles */ .todoapp { background: #fff; margin: 2rem 0 4rem 0; padding: 1rem; position: relative; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 2.5rem 5rem 0 rgba(0, 0, 0, 0.1); } @media screen and (min-width: 550px) { .todoapp { padding: 4rem; } } .todoapp > * { max-width: 50rem; margin-left: auto; margin-right: auto; } .todoapp > f...
Gecko info for Windows accessibility vendors
mozillahiddenwindowclass - ignore these windows, they are used to help manage other windows mozillawindowclass - general filler window, a catch all starting in firefox 2, however, you should begin switching your code to use navrelation_embeds. going forward, this may be the only way to efficiently find the content area, as mozilla will begin to become a windowless application, with an
exception for plugins which create their own window. when you see the content window receive focus, first check the role. if it is role_pane or role_document then this should be treated as a document for the default modality of the screen reader. if it is a role_application, role_dialog or role_alert then stay in focus tracking mode -- there is no need to parse the document. in addition, if it is a role_...
..._show, event_hide and event_locationchange are fired for the caret object. event_reorder is fired on an object whenever its children change. event_show and event_hide may also be fired with the reorder event, for the child who's visibility changed. the show and hide events are not fired on every iaccessible when a new subtree of iaccessibles changes visibility -- only the top iaccessible. the
exception is progress meters, which are guaranteed to fire event_show and event_hide events when they are displayed or hidden. event_alert is fired when an object of role_alert appears or changes. this should indicate to a screen reader to read the contents of the alert (it may be a container who's descendents should be read). event_selection is fired on children of single selection containers alon...
What to do and what not to do in Bugzilla
reopened only if the original reporter provides more info, or confirms someone else's steps to reproduce. if the bug is long, when enough info is provided a new bug should be filed and the original bug marked as a duplicate of it. resolving bugs as invalid you should resolve a bug as invalid if the issue described in the bug is clearly not a mozilla bug or if the issue is intended behavior. the
exceptions are bugs in other software which we have to work around and bugs that involve certain core gecko modules. bugs covered by this
exception should not be invalidated by anyone other than the module owner or module peer; for bugs involving modules like layout or content, attach a test case to the bug and then cc one of the owners or peers. reports of problems with specific websites that result from ...
...m like misspelled words or misaligned text enhancement request for enhancement the blocker severity should be used very seldomly, because only a fraction of the hundreds of thousands bugs really block the development of mozilla and these are normally fixed very quickly. as a result, bugs which are unconfirmed for more than a few days do not qualify for the blocker severity. the
exceptions to this rule are platform-specific or compiler-specific bugs. basically, anything that prevents builds from building, running, or being used for dogfood (able to use bugzilla, tinderbox, lxr, etc.) is a blocker. bug reports about crashes, hangs, data-loss, or severe security exploits (e.g. remote execution of arbitrary code) get the critical severity. priority/target milestone as stated in th...
CustomizableUI.jsm
customizableui provides a way to listen for various bits of customization happening. this can be useful if other parts of the code need to react to changes in the customization of the user interface. in order to use this facility, you should create a plain js object which defines some of the event handlers defined below. not all event handler methods need to be defined. customizableui will catch
exceptions. events are dispatched synchronously on the ui thread, so if you can delay any/some of your processing, that is advisable. the following event handlers are supported: onwidgetadded(awidgetid, aarea, aposition) fired when a widget is added to an area. awidgetid is the widget that was added, aarea the area it was added to, and aposition the position in which it was added. onwidgetmoved(awidg...
... you want to ensure it was added. beginbatchupdate() start a batch update of items. during a batch update, the customization state is not saved to the user's preferences file, in order to reduce (possibly sync) io. calls to begin/endbatchupdate may be nested. callers should ensure that no matter what happens they call endbatchupdate once for each call to beginbatchupdate, even if there are
exceptions in the code in the batch update. otherwise, for the duration of the firefox session, customization state is never saved. typically, you would do this using a try...finally block wrapped around your insertion code. endbatchupdate() end a batch update. see the documentation for beginbatchupdate above. state is not saved if we believe it is identical to the last known saved state. state is onl...
FileUtils.jsm
optional file open flags (see constants above) return value returns nsifileoutputstream (the non-safe variant) to write to. openatomicfileoutputstream() opens an atomic file output stream for writing. note: 'safe' and 'atomic' file output streams will never append; they will always overwrite an existing file. starting in gecko 38.0, passing mode_append without mode_truncate will throw an
exception. nsifileoutputstream openatomicfileoutputstream( nsifile file, int modeflags ); parameters file the file to write to. modeflags optional file open flags (see constants above) return value returns nsifileoutputstream (the safe variant) to write to. note: openatomicfileoutputstream() is generally better than opensafefileoutputstream() because flushing is not needed in most of the ...
...file output stream. void closeatomicfileoutputstream( nsifileoutputstream stream ); parameters stream the stream to close. opensafefileoutputstream() opens a safe file output stream for writing. note: 'safe' and 'atomic' file output streams will never append; they will always overwrite an existing file. starting in gecko 38.0, passing mode_append without mode_truncate will throw an
exception. nsifileoutputstream opensafefileoutputstream( nsifile file, int modeflags ); parameters file the file to write to. modeflags optional file open flags (see constants above) return value returns nsifileoutputstream (the safe variant) to write to. remarks note: starting in gecko 6 the stream is opened with the defer_open nsifileoutputstream behavior flag constant; this means the...
OS.File for the main thread
to copy. at the time of this writing, this function does not copy directories. destpath the full path of the destination. note that this is not a directory but a file. optionsoptional an optional object used to control the behavior of this function. you may pass an object with a subset of the following fields: nooverwrite if destpath already exists, do not overwrite it, but rather launch an
exception. promise can be rejected with os.file.error in case of any error, in particular if the file does not exist. performance notes to avoid erasing the destination file, it is much faster to use option nooverwrite than to check manually whether the file exists. this operation is os-optimized under os x (native operation copyfile), linux/android (native operation splice), and windows (nati...
...th is a directory. destpath the full path of the destination. at the time of this writing, the behavior of this function is unspecified if destpath is a directory. optionsoptional an optional object used to control the behavior of this function. you may pass an object with a subset of the following fields: nooverwrite if destpath already exists, do not overwrite it, but rather launch an
exception. nocopy if moving the file would require a copy (i.e. if the destination path resides on another drive/device/file system as the source path), fail. promise can be rejected with os.file.error in case of any error, in particular if the file does not exist. performance note: this operation is os-optimized under os x, linux/android, and windows. os.file.read() read the contents o...
PromiseWorker.jsm
ge; } customerror.prototype.tomsg = function() { return { exn: 'customerror', message: this.message, }; }; // a function called by message. function func() { ... // throw a custom error. ...
... the complete demo is found here: github :: promiseworker custom errors demo catching the promise from the worker, it is not possible, as of firefox 40, to cause the promise on the main thread catch. ...
Mozilla DOM Hacking Guide
class corresponding to the data passed in. the implementation is detailed in section 1.6. static void shutdown(): releases the interface pointers. static nsiclassinfo* docreate(nsdomclassinfodata* adata): inline function that returns a nsiclassinfo pointer to a new instance of the nsdomclassinfo class. static nsresult wrapnative(...): xpconnect fu, not our problem. static nsresult throwjs
exception(jscontext *cx, nsresult aresult);: help me! static nsresult initdomjsclass(jscontext *cx, jsobject *obj);: help me! static jsclass sdomjsclass;: help me! protected section: const nsdomclassinfodata* mdata;: help me! static nsresult init(): called only once, it is used to initialize the remaining members of the nsdomclassinfodata structure, as mentioned above. once called, init() set...
...of type "location". however a common technique is to do window.location = "http://mozilla.org" instead of the correct window.location.href = "http://mozilla.org". so, we have to override the default behavior of "setting the location property on the window object". the default behavior would be that xpconnect expects a nsidomlocation object. however it would be passed a js string. a bad conversion
exception would be thrown. before we start looking at the implementation of the nsixpcscriptable interface, the implementor needs the following information: which dom object is concerned what action does he want to override what should happen for our example, it is the window object. the action is setting a property. what should happen is that setting .location should set .location.href. with that...
A brief guide to Mozilla preferences
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(). preferences files to protect privacy by preventing inadvertent loading of a preferences file in the browser, the first line of the file is made un-parseable and skipped on loading. the only
exception to this is user.js . on application launch, several preferences files are loaded. they are: default preference files firefox ships default preferences in several files, all in the application directory: greprefs.js - preferences shared by all applications using the mozilla platform services/common/services-common.js - preferences for some shared services code, this should arguably b...
...et preferences are saved to prefs.js . this also means that preferences initially set by user.js will also be saved to prefs.js. do not edit prefs.js directly. note the application never changes user.js, so on launch user.js overrides conflicting preferences from the previous application session. when prefs.js is written, it only saves user preferences which are different from the default. the
exception to this is a preference read using sticky_pref() - these preference will be written whenever the preference has a user value even when it is the same as the default. modifying preferences advanced users can set named preferences via the advanced preferences editor, by typing about:config in the location bar. this ui is not recommended for most users. programmatic changes to preferences can be...
PR_Poll
led. the reason for the failure can be obtained by calling pr_geterror. description this function returns as soon as i/o is ready on one or more of the underlying socket objects. a count of the number of ready descriptors is returned unless a timeout occurs, in which case zero is returned. 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. on successful return, the out_flags field of the prpolldesc data structure is set to indicate what kind of i/o is ready on the respective descriptor. pr_poll uses the out_flags fields as scratch variables during the call. if pr_poll returns 0 or -1, the out_flags fields do not contain meaningful values and must not be used. the prpolldesc s...
...t, including one representing a file or a pipe. cross-platform applications should only set the fd field to a pointer to a prfiledesc object representing a socket or a pollable event because on windows the select function can only be used with sockets. in_flags a bitwise or of the following bit flags: pr_poll_read: fd is readable. pr_poll_write: fd is writable. pr_poll_except: fd has an
exception condition. out_flags a bitwise or of the following bit flags: pr_poll_read pr_poll_write pr_poll_except pr_poll_err: fd has an error. pr_poll_nval: fd is bad. note that the pr_poll_err and pr_poll_nval flags are used only in out_flags. the pr_poll_err and pr_poll_nval events are always reported by pr_poll. ...
Rhino scopes and contexts
h execution, simply exit the context: context.exit(); these calls will work properly even if there is already a context associated with the current thread. that context will be returned and an internal counter incremented. only when the counter reaches zero will it be disassociated from the thread. remember to put the exit() call in a finally block if you're executing code that could throw an
exception. scopes a scope is a set of javascript objects. execution of scripts requires a scope for top-level script variable storage as well as a place to find standard objects like function and object. it's important to understand that a scope is independent of the context that created it. you can create a scope using one context and then evaluate a script using that scope and another context (either ...
...ork properly for other scripts. such bugs are hard to debug and to remove a possibility for them to occur one can seal the shared scope and all its objects. a notion of a sealed object is a javascript extension supported by rhino and it means that properties can not be added/deleted to the object and the existing object properties can not be changed. any attempt to modify sealed object throws an
exception. to seal all objects in the standard library passtrue for the sealed argument when calling context.initstandardobjects(scriptableobject, boolean): scriptableobject sealedsharedscope = cx.initstandardobjects(null, true); this seals only all standard library objects, it does not seal the shared scope itself thus after callinginitstandardobjects, sealedsharedscope can be farther populated with ap...
Rhino serialization
ino 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.
exceptions will be thrown if foo or foo.prototype cannot be found the scopes used in either scriptableoutputstream or scriptableinputstream. rhino serialization in compilation mode serialization works well with objects and with functions and scripts in interpretive mode. however, you can run into problems with serialization of compiled functions and scripts: $ cat test.jsfunction f() { return 3; } serializ...
... with objects and with functions and scripts in interpretive mode. however, you can run into problems with serialization of compiled functions and scripts: $ cat test.jsfunction f() { return 3; } serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ java org.mozilla.javascript.tools.shell.main -opt -1test.js 3 $ java org.mozilla.javascript.tools.shell.main test.js js: uncaught javascript
exception: java.lang.classnotfound
exception:c1 the problem is that java serialization has no built-in way to serialize java classes themselves. (it might be possible to save the java bytecodes in an array and then load the class upon deserialization, but at best that would eat up a lot of memory for just this feature.) one way around this is to compile the functions using the jsc tool: $ cat f.js function...
Creating JavaScript jstest reftests
test. additionally, it loads every shell.js and broswer.js file in the subdirectories on the path from js/src/tests to the location of your test. if you have functionality several tests share in a given folder, you can add the functionality to the shell.js or broswer.js file in the directory. asserteq asserteq(v1, v2[, message]) checks that v1 and v2 are the same value. if they're not, throw an
exception (which will cause the test to fail). reportcompare reportcompare(expected, actual, description) is somewhat like asserteq(actual, expected, description) except that the first two arguments are swapped, failures are reported via stdout rather than by throwing
exceptions, and the matching is fuzzy in an unspecified way. for example, reportcompare sometimes considers numbers to be the same if they...
...e> --- that tells the post-processing scripts jsdriver.pl or post-process-logs.pl that the test passes if the shell or browser terminates with that exit code. 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. this approach has limited use, however. in the javascript shell, an uncaught
exception or out of memory error will terminate the shell with an exit code of 3. however, an uncaught error or
exception will not cause the browser to terminate with a non-zero exit code. to make the situation even more complex, newer c++ compilers will abort the browser with a typical exit code of 5 by throwing a c++
exception when an out of memory error occurs. simply testing the exit code does not allo...
Invariants
in gc" and no threads are in requests; or no thread is doing gc, in which case any number of threads may be in requests; or the gc lock is held. a thread that holds the gc lock never does anything that blocks. a thread that is in a request never does anything that blocks. there are the usual invariants regarding locks: we do not reenter them (it would be nice to check this as there might be an
exception or two); we do not wait on a condition variable unless the corresponding lock is held. there are the usual invariants regarding various fields: they are protected by certain locks or more complex locking schemes. in particular, native objects' fields are protected by property locking (below); and several things are protected by the request model, such that there may be either one writer (in gc) ...
...e locking scheme is described under jsobjectops.dropproperty. (note that the locking scheme applies to all objects and talks about properties being locked. as implemented for native objects, the locking is not really that fine-grained, but that is a transparent optimization as long as we follow the rules.) a thread holding a property lock never leaves or suspends the current request. with a few
exceptions (known to brendan and probably jst and mrbkap), we never call a jsapi callback with a property locked. (that would risk deadlock too.) name instructions the first operand to a jsop_setname instruction is always produced by a preceding jsop_bindname instruction. (taken together, ecma 262-3 §11.13.1 and ecma 262-3 §10.1.4 specify that in an assignment such as x = f(), the name lookup for x oc...
JSNative
added in spidermonkey 24 as well as through "jsapi.h".) this structure encapsulates access to the callee function, this, the function call's arguments, and the eventual return value. on success, the callback must set js::callargs::rval() or call js_set_rval (at least once) and return true. otherwise it should either report an error (using e.g. js_reporterror or js_reportoutofmemory) or raise an
exception (using js_setpending
exception), and the callback must return false. (returning false without reporting an error or raising an
exception terminates the script with an uncatchable error. this has limited use cases; it's used to implement firefox's "slow script" dialog, for example.) when a jsnative is called, no jsstackframe is generated. this causes the function not to appear on the stack in jav...
...to appear on the stack in javascript debuggers. it also means that applications that implement jscheckaccessop or jscheckaccessidop in terms of apis such as js_frameiterator and js_stackframeprincipals, must take extra care, as the native function's principals will be missing from the stack. see also mxr id search for jsnative js::callargs js_reporterror js_reportoutofmemory js_setpending
exception ...
JS_DefineProperty
trs). if obj already has an own property with the given name or id, the existing property is replaced. these functions can currently replace jsprop_permanent properties, but such usage is deprecated. the javascript engine will call the getter or setter callback each time the property is read or written, whether from javascript code or via jsapi functions like js_getproperty and js_setproperty. (
exception: if attrs contains the jsprop_readonly flag, the setter will never be called, as property assignment will fail before it gets that far. also note that certain jsapi functions, including js_lookupproperty, js_hasproperty, and property_attributes, can detect or examine a property without calling its getter.) if getter (or setter) is null, the new property will use the jsclass.getproperty (or jsclas...
... from obj's class. if attrs contains the jsprop_getter (or jsprop_setter) flag, then getter (or setter) must point to a javascript function, not a c/c++ function. that is, it must be a jsobject * that points to a javascript function, cast to type jspropertyop. for more about javascript getters and setters, see defining getters and setters. on success, js_defineproperty returns true. on error or
exception, it returns false. see also mxr id search for js_defineproperty mxr id search for js_defineucproperty mxr id search for js_definepropertybyid js_defineelement bug 461163 bug 1113369 -- added desc and result parameters ...
JS_ReportError
syntax void js_reporterror(jscontext *cx, const char *format, ...); bool js_reportwarning(jscontext *cx, const char *format, ...); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. format const char * format string to convert into an error message using js_vsmprintf. ...
...porterror is the simplest jsapi function for reporting errors. first it builds an error message from the given sprintf-style format string and any additional arguments passed after it. 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. an example is shown in the jsapi phrasebook. for internationalization, use js_reporterrornumber instead. to report an out-of-memory error, use js_reportoutofmemory. see also mxr id search for js_reporterror mxr id search for js_reportwarning ...
JS_ReportErrorNumber
nter that was passed to the reporterrornumber api. errornumber const unsigned the errornumber that was passed to the reporterrornumber api. description these functions create a jserrorreport, populate it with an error message obtained from the given jserrorcallback, and either report it to the current error reporter callback or create an error object and set it as the pending
exception. first errorcallback(userref, errornumber) is called. if errorcallback returns null, (??? what happens?). otherwise, if the jserrorformatstring returned by the jserrorcallback has .exntype == jsexn_none, then the error reporter, if any, is called, and no error object is created. (??? the source code seems to say we ignore the .exntype, actually, but surely i'm just missing something.) otherwise, ...
...llback has .exntype == jsexn_none, then the error reporter, if any, is called, and no error object is created. (??? the source code seems to say we ignore the .exntype, actually, but surely i'm just missing something.) otherwise, if any javascript code is running in cx (for example, if the caller is a jsnative that was called from a script), then an error object is created and becomes the pending
exception. the error reporter is not called yet, because the script still has an opportunity to catch and handle the
exception. otherwise, no javascript code is running in cx. if the jsoption_dont_report_uncaught option is set, (??? what happens?). otherwise, (??? what happens?). see also mxr id search for js_reporterrornumber mxr id search for js_reporterrornumberuc mxr id search for js_reporterrorfla...
JS_ValueToNumber
, conversion succeeds, and the result is nan, 0, 0, or 1 respectively. if v is a string, conversion proceeds as specified in ecma 262-3 §9.3.1. js_valuetonumber always succeeds in this case, returning js_true. if the string is not a numeric string, *dp is set to nan. otherwise v is an object. js_valuetonumber carries out the following steps to convert it to a number. if at any step an error or
exception occurs, or conversion succeeds, the rest of the steps are skipped. (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. if the convert callback produces a primitive value, the value is...
...rted to a number as described above and conversion succeeds. otherwise, the resulting object's tostring method, if any, is called. if that produces a primitive value, the value is converted to a number as described above and conversion succeeds. otherwise conversion fails with a typeerror. on success, js_valuetonumber stores the converted value in *dp and returns js_true. on error or
exception, it returns js_false, and the value left in *dp is undefined. see also js_convertarguments js_convertvalue js_gettypename js_typeofvalue js_valuetoint32 js_valuetoecmaint32 bug 884410 ...
JS_ValueToString
v is a number, conversion succeeds, and the result is a string representation of that number as specified in ecma 262-3 §9.8.1. this might be "nan", "infinity", or "-infinity". otherwise the result is a decimal representation of the number, possibly using exponential notation. otherwise v is an object. js_valuetostring uses the steps below to convert it to a string. if at any point an error or
exception occurs, or conversion succeeds, the rest of the steps are skipped. (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. if that method returns a primitive value, the value is converted to a string as described above and conversion succeeds. otherwise, the resulting object's jsclass.convert...
...ulting object's jsclass.convert callback is called. for standard classes, this is js_convertstub, which simply calls v.valueof() if present. if the convert callback produces a primitive value, the value is converted to a string as described above and conversion succeeds. otherwise conversion fails with a typeerror. on success, js_valuetostring returns a pointer to a string. on error or
exception, it returns null. this happens, for example, if v is an object and v.tostring() throws an
exception. the resulting jsstring is subject to garbage collection. protect it using a local root, an object property, or the js_addroot function. see also bug 933834 js::tostring ...
Setting up the Gecko SDK
tory. if your component will use other parts of the sdk (e.g., necko), you will have to add these include directories to this field as well. assuming you are using the example location for your project, these paths are the following: c:\gecko-sdk\embedstring\include c:\gecko-sdk\xpcom\include c:\gecko-sdk\nspr\include c:\gecko-sdk\string\include under the c++ language category, disable
exception handling. as described in the section
exceptions in xpcom,
exception handling isn't supported across interface boundaries, so setting this option may catch problems during development. the weblock component needs to link against the appropriate libraries to uses xpcom glue. to add these libraries, select the link tab, then choose the input category. in this panel, instead of linking to the inclu...
...ing, see the make manual. sample makefile for the gecko sdk module = mozshim # change this to point at your gecko sdk directory. gecko_sdk_path ?= $(home)/tmp/xr xpidl ?= $(gecko_sdk_path)/bin/xpidl cxx ?= c++ xpidlsrcs = \ interfacea.idl \ interfaceb.idl \ $(null) cppsrcs = \ sourcea.cpp \ sourceb.cpp \ $(null) cppflags += -fno-rtti \ -fno-
exceptions \ -fshort-wchar \ -fpic \ $(null) # gcc only define which allows us to not have to #include mozilla-config # in every .cpp file. if your not using gcc remove this line and add # #include "mozilla-config.h" to each of your .cpp files. gecko_config_include = -include mozilla-config.h gecko_defines = -dmozilla_strict_api gecko_includes = -i$(gecko_sdk_path) ...
Components object
he nsixpccomponents interface which is reflected into javascript as a top level object using xpconnect. some properties of components require advanced privileges and may not work in web pages. ...
...eflected into javascript as a top level object using xpconnect. some properties of components require advanced privileges and may not work in web pages. ...
Using components
it is common to start addon scripts like: var cc = components.classes; var ci = components.interfaces; there is also another way to start, which is exactly equivalent to the above. var {cc: classes, ci: interfaces} = components; there are many more than just classes and interfaces. var { cu: utils, ci: interfaces, cc: classes, cr: results, cs: stack, cm: manager, ce:
exception, } = components; here is a full breakdown of what is contained in components. any of the below can be accessed by components.blah (ie: components.issuccesscode) utils=[object nsxpccomponents_utils] interfaces=[object nsxpccomponents_interfaces] classes=[object nsxpccomponents_classes] results=[object nsxpccomponents_results] issuccesscode=function issuccesscode() { [native code] } constructor=[o...
...] issuccesscode=function issuccesscode() { [native code] } constructor=[object nsxpccomponents_constructor] queryinterface=function queryinterface() { [native code] } 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] } cancallmethod=function cancallmethod() { [native code] } cangetproperty=function cangetproperty() { [native code] } cansetproperty=function cansetproperty() { [native code] } ...
Language bindings
pt as a top level object using xpconnect.components.classescomponents.classes is a read-only object whose properties are classes indexed by contractid.components.classesbyidcomponents.classesbyid is a read-only object whose properties are classes indexed by cid.components.constructorcreates a javascript function which can be used to create or construct new instances of xpcom components.components.
exceptioncomponents.
exception is a javascript constructor to create nsixpc
exception objects. these
exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will.components.idcomponents.id is a constructor that creates native objects that conform to the nsijsid interfa...
...e, and if any native properties have been redefined, this has no effect.components.utils.makeobjectpropsnormalensures that the specified object's methods are all in the object's scope, and aren't cross-component wrappers.components.utils.reporterrorcomponents.utils.reporterror reports a javascript error object to the error console, and returns. it is meant for use by extension developers who have
exception handler blocks which want to "eat" an
exception, but still want to report it to the console.components.utils.sandboxcomponents.utils.sandbox is used to create a sandbox object for use with evalinsandbox().components.utils.scheduleprecisegcthis method lets scripts schedule a garbage collection cycle. the garbage collection cycle will occur sometime in the future, when no javascript code is executi...
nsIAccessibleHyperText
this hypertext object. read only. note: renamed from links in gecko 1.9 methods getlink() retrieves the nsiaccessiblehyperlink object at the given link index. nsiaccessiblehyperlink getlink( in long linkindex ); parameters linkindex 0-based index of the link that is to be retrieved. this can be retrieved via getlinkindex(). return value an nsiaccessiblehyperlink object.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ns_error_invalid_arg the link index is invalid. getlinkindex() the link index at the given offset (character index). long getlinkindex( in long charindex ); parameters charindex the 0-based character index. return value the index of the link if it's presented on the given character ...
...ailure indicates that the accessible is unattached from the accessible tree. ns_error_invalid_arg the link index is invalid. getlinkindex() the link index at the given offset (character index). long getlinkindex( in long charindex ); parameters charindex the 0-based character index. return value the index of the link if it's presented on the given character index, otherwise -1.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. getselectedlinkindex() obsolete since gecko 1.9 (firefox 3) long getselectedlinkindex(); parameters none. return value missing description
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsi...
nsIAccessibleImage
. this method is the same as nsiaccessible.getbounds() excepting coordinate origin parameter. void getimageposition( in unsigned long coordtype, out long x, out long y ); parameters coordtype specifies coordinates origin (for available constants refer to nsiaccessiblecoordinatetype). x the x coordinate of the image accessible position. y the y coordinate of the image accessible position. ...
...age accessible position.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. getimagesize() returns the size of the image accessible. this method is the same as nsiaccessible.getbounds(). void getimagesize( out long width, out long height ); parameters width the width of the image accessible. height the height of the image accessible.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
nsIAccessibleSelectable
ly. constants constant value description eselection_add 0 eselection_remove 1 eselection_getstate 2 methods addchildtoselection() adds the specified accessible child of the object to the object's selection. if the specified object is already selected, then it does nothing. void addchildtoselection( in long index ); parameters index the zero-based accessible child index.
exceptions thrown ns_error_failure if the specified object is not selectable. clearselection() clears the selection in the object so that no children in the object are selected. void clearselection(); parameters none. getselectedchildren() returns an nsiarray of the selected nsiaccessible children. nsiarray getselectedchildren(); parameters none. return value an nsiarray. ischildselected() determines i...
...tion( in long index ); parameters index zero-based selected accessible child index. return value the selected accessible child. removechildfromselection() removes the specified child of the object from the object's selection. if the specified object was not selected, then it does nothing. void removechildfromselection( in long index ); parameters index zero-based accessible child index.
exceptions thrown ns_error_failure if the specified object is not selectable. selectallselection() select all children. boolean selectallselection(); parameters none. return value if the object does not accept multiple selection, return false. otherwise, returns true. ...
nsIAnnotationService
n the future. aexpiration one of the expire_* constant value defined above. amimetype mime type of the data to be retrieved. default to "0" if value was not binary data. atype one of type_* constansts defined above. getpageannotationtype() this method retrieves the type of an existing annotation. use getannotationinfo() method, if you need this along with the mime-type etc. it throwns an
exception if the annotation is not set. pruint16 getpageannotationtype( in nsiuri auri, in autf8string aname ); parameters auri the uri on which the annotation is set. aname the annotation name. return value returns one of the type_* constants defined above. getitemannotationtype() this method retrieves the type of an existing annotation. use getannotationinfo() method, if you need this a...
...tpageannotationtype( in nsiuri auri, in autf8string aname ); parameters auri the uri on which the annotation is set. aname the annotation name. return value returns one of the type_* constants defined above. getitemannotationtype() this method retrieves the type of an existing annotation. use getannotationinfo() method, if you need this along with the mime-type etc. it throwns an
exception if the annotation is not set. pruint16 getpageannotationtype( in long long aitemid, in autf8string aname ); parameters auri the item on which the annotation is set. aname the annotation name. return value returns one of the type_* constants defined above. getpageswithannotation() this method returns a list of all uris having a given annotation. void getpageswithannotation( in...
nsIAuthModule
are in use. void unwrap( [const] in voidptr aintoken, in unsigned long aintokenlength, out voidptr aouttoken, out unsigned long aouttokenlength ); parameters aintoken a buffer containing the data received from the server. aintokenlength the length of the input token. aouttoken a buffer containing the plaintext data from the server. aouttokenlength the length of the output token buffer.
exceptions thrown ns_error_not_implemented if the underlying authentication mechanism does not support security layers. wrap() once a security context has been established through calls to getnexttoken() it may be used to protect data exchanged between client and server. calls to this method are used to protect items of data to be sent to the server. void wrap( [const] in voidptr aintoken, in unsigne...
...ned long aouttokenlength ); parameters aintoken a buffer containing the data to be sent to the server. aintokenlength the length of the input token. confidential if set to true, it will encrypt the data, otherwise data will just be integrity protected (checksummed). aouttoken a buffer containing the resulting data to be sent to the server. aouttokenlength the length of the output token buffer.
exceptions thrown ns_error_not_implemented if the underlying authentication mechanism does not support security layers. ...
nsIAuthPrompt2
from the user. a single prompt will be shown; then the callbacks for all the coalesced prompts will be notified with the resulting authentication information. serialize prompts that are all in the same "context" (this might mean application-wide, for a given window, or something else depending on the user interface) so that the user is not deluged with prompts. note: this method may throw any
exception when the prompt fails to queue, for example because of out-of-memory error. it must not throw when the prompt could already be potentially shown to the user. in that case information about the failure has to come through the callback. this way we prevent multiple dialogs shown to the user because consumer may fall back to synchronous prompt on synchronous failure of this method. nsicancelable as...
...k acontext level one of the level constants. authinfo authentication information object. the implementation should fill in this object with the information entered by the user before returning. return value promptauth() requests a username and a password. implementations will commonly show a dialog with a username and password field, depending on flags also a domain field. note:
exceptions thrown from this function will be treated like a return value of false. boolean promptauth( in nsichannel achannel, in pruint32 level, in nsiauthinformation authinfo ); parameters achannel the channel that requires authentication. level one of the level constants. authinfo authentication information object. the implementation should fill in this object with the information enter...
nsIBidiKeyboard
nformation. currently, this is only implemented on windows. methods islangrtl() determines if the current keyboard language is right-to-left. (supported on: win32, mac, gtk2) note: prior to gecko 1.9 this method used a parameter 'out prbool aisrtl' to return the value. boolean islangrtl(); parameters none. return value true if the current keyboard is right-to-left, false if it is not. ...
... remarks implementation windows this implementation uses win32 api to get the language of the keyboard layout, and the direction of those languages. linux this implementation depends on the gecko and gtk+ version. ...
nsIBinaryInputStream
ers none. return value a boolean value read from the stream. readbytearray() reads an opaque byte array from the stream, storing the results as an array of pruint8s. void readbytearray( in pruint32 alength, [array, size_is(alength), retval] out pruint8 abytes ); parameters alength the number of bytes that must be read. abytes an array containing the bytes read from the stream. ...
... readcstring() reads an 8-bit pascal style string from the stream. 32-bit length field, followed by length 8-bit chars. acstring readcstring(); parameters none. return value the string read from the stream. readdouble() reads from the stream. ...
nsIBrowserSearchService
whether the user should be asked for confirmation before this engine is added to the list. if this value is false, the engine will be added to the list upon successful load, but it will not be selected as the current engine. callback a nsisearchinstallcallback that will be notified when the addition is complete, or if the addition fails. it will not be called if addengine throws an
exception.
exceptions thrown ns_error_failure if the type is invalid, or if the description file cannot be successfully loaded. addenginewithdetails() adds a new search engine, without asking the user for confirmation and without starting to use it right away. void addenginewithdetails( in astring name, in astring iconurl, in astring alias, in astring description, in astring meth...
...lled once initialization is complete, or immediately, if the service has already been initialized. in javascript, this observer can be a regular function. moveengine() moves a visible search engine. void moveengine( in nsisearchengine engine, in long newindex ); parameters engine the engine to move. newindex the engine's new index in the set of visible engines.
exceptions thrown ns_error_failure if newindex is out of bounds, or if engine is hidden. removeengine() removes the search engine. if the search engine is installed in a global location, this will just hide the engine. if the engine is in the user's profile directory, it will be removed from disk. void removeengine( in nsisearchengine engine ); parameters engine the engine...
nsICacheService
this is used by the offline cache. the offline cache lets clients accumulate entries in a temporary client and merge them in as a group using nsiofflinecachesession.mergetemporaryclient(). acstring createtemporaryclientid( in nscachestoragepolicy storagepolicy ); parameters storagepolicy the cache storage policy. return value returns a newly created unique, temporary cache client id.
exceptions thrown ns_error_not_implemented this method is deprecated. evictentries() this method evicts all entries in all devices implied by the storage policy. note: this function may evict some items but will throw if it fails to evict everything. void evictentries( in nscachestoragepolicy storagepolicy ); parameters storagepolicy the cache storage policy. init() obso...
...storage policy. note: this function may evict some items but will throw if it fails to evict everything. void evictentries( in nscachestoragepolicy storagepolicy ); parameters storagepolicy the cache storage policy. init() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) initialize the cache service. void init(); parameters none.
exceptions thrown missing
exception missing description shutdown() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) shutdown() the cache service. void shutdown(); parameters none. visitentries() this method visits entries stored in the cache. used to implement the about:cache uri. void visitentries( in nsicachevisitor visitor ); parameters...
nsICategoryManager
entry being modified. ("http") avalue the value for the category entry. ("moz.httprulez.1") apersist no longer supported. category entries never persist across application sessions. you must pass false for this parameter. areplace a flag indicating whether or not to overwrite the value of an existing category entry. return value the previous value for the given category entry (if any).
exceptions thrown ns_error_invalid_arg this error is returned if areplace is false and the category entry already has a value, or if apersist is true. deletecategory() delete a category and all entries. note: if the category does not exist, then this method does nothing. void deletecategory( in string acategory ); parameters acategory the name of the category being deleted. deletecategor...
...tscstring. getcategoryentry() get the value for the given category's entry. string getcategoryentry( in string acategory, in string aentry ); parameters acategory the category being queried. ("protocol") aentry the entry being queried. ("http") return value the value of the given category's entry. this pointer must be released using nsimemory.free() when it is no longer needed.
exceptions thrown ns_error_not_available indicates that either the category or entry is undefined. examples print out a list of all categories this snippet shows how to print out a list of all categories in c++. nsresult printallcategories() { nsresult rv; nscomptr<nsiservicemanager> svcmgr; rv = ns_getservicemanager(getter_addrefs(svcmgr)); if (ns_failed(rv)) return rv; nscomptr<n...
nsIChannel
tself alive until it has called onstoprequest on alistener or called onchannelredirect. implementations are allowed to synchronously add themselves to the associated load group (if any). void asyncopen( in nsistreamlistener alistener, in nsisupports acontext ); parameters alistener the nsistreamlistener implementation. acontext an opaque parameter forwarded to alistener's methods.
exceptions thrown ns_error_already_opened if the channel is reopened ns_error_port_access_not_allowed if the specified port is in the nsioservice forbidden port list. open() synchronously open the channel. note: extensions should not call this method, because it tends to fail when a request is redirected, rather than redirecting transparentlynote: nsichannel implementations are not required to im...
...e: nsichannel implementations are not required to implement this method. moreover, since this method may block the calling thread, it should not be called on a thread that processes ui events. like any other nsichannel method it must not be called on any thread other than the xpcom main thread. nsiinputstream open(); parameters none. return value blocking input stream to the channel's data.
exceptions thrown ns_error_in_progress if the channel is reopened. see also nsichanneleventsink for onchannelredirect ...
nsICommandLine
flag, and flags of the form --flag=param are normalized to the form -flag param. astring getargument( in long aindex ); parameters aindex the argument to retrieve. this index is 0-based, and does not include the application name. return value the value of the specified argument. this is the full text of that argument, so if the argument is a flag, the returned value is "-flag [<flagvalue>]".
exceptions thrown ns_error_invalid_arg the specified index is out of bounds. handleflag() finds the specified flag, removing it from the array of flags. reports whether or not the specified flag was found. this is useful for boolean flags; that is, flags that don't accept a parameter. you can determine if the flag was provided and remove it from the list of flags waiting to be processed in one operation.
...nes findflag() and removearguments() into one operation. astring handleflagwithparam( in astring aflag, in boolean acasesensitive ); parameters aflag the flag name to find and remove. acasesensitive whether to do case-sensitive flag search. return value the value of the specified flag, an empty string if the flag's value is the empty string, or null if the specified parameter wasn't found.
exceptions thrown ns_error_invalid_arg the specified flag has no value. removearguments() removes a range of arguments from the command line; this is typically done once those arguments have been handled. void removearguments( in long astart, in long aend ); parameters astart the index to the first argument to remove from the command line; this is 0-based, and the name of the application is not inc...
nsIDOMHTMLTimeRanges
epresented by the nsidomhtmltimeranges object. read only. methods end() returns the time offset to the end of the specified time range. float end( in unsigned long index ); parameters index the index to the time range whose end time is to be returned. return value the time at which the specified range ends, in seconds measured from the beginning of the timeline represented by the object.
exceptions thrown index_size_err the specified index is not valid. start() returns the time offset to the start of the specified time range. float start( in unsigned long index ); parameters index the index to the time range whose start time is to be returned. return value the time at which the specified range starts, in seconds measured from the beginning of the timeline represented by the object. ...
...s thrown index_size_err the specified index is not valid. start() returns the time offset to the start of the specified time range. float start( in unsigned long index ); parameters index the index to the time range whose start time is to be returned. return value the time at which the specified range starts, in seconds measured from the beginning of the timeline represented by the object.
exceptions thrown index_size_err the specified index is not valid. ...
nsIDOMNSHTMLDocument
doshowui this is not implemented in gecko. value some commands require an argument. you can pass null for those commands that do not need an argument. return value true if the command was recognized, false otherwise. execcommandshowhelp() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) this method never did anything but throw an
exception, and was removed entirely in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11). boolean execcommandshowhelp( in domstring commandid ); parameters commandid the name of the command. return value this method is not supported and always throws an
exception. getselection() domstring getselection(); parameters none. return value the text of the current selection, the same as ...
...mandsupported() boolean querycommandsupported( in domstring commandid ); parameters commandid the name of the command to query. return value returns true if the command is supported on the current range, false otherwise. querycommandtext() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) this method never did anything but throw an
exception, and was removed entirely in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11). domstring querycommandtext( in domstring commandid ); parameters commandid the name of the command to query. return value this method is not supported and always throws an
exception. querycommandvalue() domstring querycommandvalue( in domstring commandid ); parameters commandid the...
nsIDOMWindowUtils
void startpccountprofiling(); void stoppccountprofiling(); void suppresseventhandling(in boolean asuppress); void suspendtimeouts(); nsidomfile wrapdomfile(nsifile afile); attributes attribute type description currentinnerwindowid unsigned long long the id of the window's current inner window. read only.
exceptions thrown ns_error_not_available there is no current inner window displaydpi float the dpi of the display. read only. doccharsetisforced boolean whether the charset of the window's current document has been forced by the user. cannot be accessed from unprivileged context (not content-accessible) read only. elementsrestyled read only ...
...tdefault() the event before dispatch. aadditionalflags optional 0 or key_flag_prevent_default and/or one of key_flag_location_*. if key_flag_prevent_default is specified, the dispatching key event's default is prevented. if key_flag_location_* isn't set, an appropriate location is automatically computed from akeycode. if two or more key_flag_location_* is specified, this method will throw an
exception. return value false if the event had preventdefault() called on it, true otherwise. in other words, true if and only if the default action was taken. sendmouseevent() synthesize a mouse event. the event types supported are: mousedown, mouseup, mousemove, mouseover, mouseout, contextmenu. events are sent in coordinates offset by ax and ay from the window. note: that additional events may be...
nsIDroppedLinkHandler
n prbool aallowsamedocument ); parameters aevent a dragenter or dragover event. aallowsamedocument if false, drops are only allowed if the document of the source of the drag is different from the destination. this check includes any parent, sibling and child frames in the same content tree. if true, the source is not checked. return value true if the link being dragged can be dropped.
exceptions thrown missing
exception missing description droplink() given a drop event, determines the link being dragged. if a uri is returned the caller can, for instance, load it. if null is returned, there is no valid link to be dropped. astring droplink( in nsidomdragevent aevent, out astring aname, [optional] in boolean adisallowinherit ); parameters aevent a drop event. aname th...
...s returned the caller can, for instance, load it. if null is returned, there is no valid link to be dropped. astring droplink( in nsidomdragevent aevent, out astring aname, [optional] in boolean adisallowinherit ); parameters aevent a drop event. aname the link title if it exists, or an empty string otherwise. return value a uri, or null if there is no valid link to be dropped.
exceptions thrown ns_error_dom_security_err error will be thrown and the event canceled if the receiving target should not load the uri for security reasons. this will occur if the source of the drag initiated a link for dragging that it itself cannot access. this prevents a source document from tricking the user into a dragging a chrome url for example. droplinks() given a drop event, determines th...
nsIMsgFilter
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgfilter.idl attributes type attribute nsmsgruleactiontype type; priority // target priority.. throws an
exception if the action is not priority attribute nsmsgpriorityvalue priority; targetfolderuri // target folder.. throws an
exception if the action is not move to folder attribute acstring targetfolderuri; label // target label. ...
...entral/ mailnews/ base/ search/ public/ nsimsgfilter.idl attributes type attribute nsmsgruleactiontype type; priority // target priority.. throws an
exception if the action is not priority attribute nsmsgpriorityvalue priority; targetfolderuri // target folder.. throws an
exception if the action is not move to folder attribute acstring targetfolderuri; label // target label. ...
nsINavBookmarksService
the folder is marked as read-only, otherwise returns false. getfoldertitle() obsolete since gecko 1.9 (firefox 3) note: getitemtitle() provides an alternative for this method. get the title for a bookmark folder. astring getfoldertitle( in print64 folder ); parameters folder the folder whose title should be retrieved. return value the title of the folder.
exceptions thrown invalid argument
exception if it can not find a folder with the given id. getfolderuri() obsolete since gecko 1.9 (firefox 3) note: getbookmarkuri() provides an alternative for this method. get the url for a bookmark folder. nsiuri getfolderuri( in print64 folder ); parameters folder the folder whose uri should be retrieved. return value the u...
...erwise the indices will become corrupted. warning: this is api is intended for scenarios such as folder sorting, where the caller manages the indices of all items in the folder. you must always ensure each index is unique after a reordering. void setitemindex( in long long aitemid, in long anewindex ); parameters aitemid the id of the item to modify. anewindex the new index.
exceptions thrown if anewindex is out of bounds. setitemlastmodified() this method sets the last modified time for an item. note: this is the only method that will send an itemchanged notification for the property. lastmodified will still be updated in any other method that changes an item property, but we will send the corresponding itemchanged notification instead. void setitemlastmodified( ...
nsIProtocolProxyService
to config (pac) may perform a synchronous dns query, which may not return immediately. so, calling resolve without this flag may result in locking up the calling thread for a lengthy period of time. by passing this flag to resolve, one can failover to asyncresolve to avoid locking up the calling thread if a pac query is required. when this flag is passed to resolve, resolve may throw the
exception ns_base_stream_would_block to indicate that it failed due to this flag being present. methods resolve() deprecated since gecko 18 this method has been removed in firefox 18. use resolveasync instead previous doc this method returns a nsiproxyinfo instance that identifies a proxy to be used for loading the given uri. otherwise, this method returns null indicating that a direct connectio...
...i auri, in nsresult areason ); parameters aproxyinfo the proxy that was unavailable. auri the uri that was originally passed to resolve/asyncresolve. areason the error code corresponding to the proxy failure. this value may be used to tune the delay before this proxy is used again. the proxy that was unavailable. return value an nsiproxyinfo object or null for a direct connection.
exceptions thrown ns_error_not_available if there is no alternate proxy available. registerfilter() this method may be used to register a proxy filter instance. each proxy filter is registered with an associated position that determines the order in which the filters are applied (starting from position 0). when resolve/asyncresolve is called, it generates a list of proxies for the given uri, and the...
nsIRequestObserver
start and end of a request. 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. note: an
exception thrown from onstartrequest has the side-effect of causing the request to be canceled. void onstartrequest( in nsirequest arequest, in nsisupports acontext ); parameters arequest request being observed. acontext user defined context. onstoprequest() called to signify the end of an asynchronous request. this call is always preceded by a call to onstartrequest(). n...
...from onstartrequest has the side-effect of causing the request to be canceled. void onstartrequest( in nsirequest arequest, in nsisupports acontext ); parameters arequest request being observed. acontext user defined context. onstoprequest() called to signify the end of an asynchronous request. this call is always preceded by a call to onstartrequest(). note: an
exception thrown from onstoprequest is generally ignored. void onstoprequest( in nsirequest arequest, in nsisupports acontext, in nsresult astatuscode ); parameters arequest request being observed. acontext user defined context. astatuscode reason for stopping (ns_ok if completed successfully) see also nsistreamlistener ...
nsISHistory
e loads that initiate in session history. getentryatindex() called to obtain handle to the history entry at a given index. nsishentry getentryatindex( in long index, in boolean modifyindex ); parameters index the index value whose entry is requested. modifyindex a boolean flag that indicates if the current index of session history should be modified to the parameter index.
exceptions thrown ns_ok history entry for the index is obtained successfully. ns_error_failure error in obtaining history entry for the given index. purgehistory() called to purge older documents from history. documents can be removed from session history for various reasons. for example to control memory usage of the browser, to prevent users from loading documents from history, to erase evidence of prior...
...ple to control memory usage of the browser, to prevent users from loading documents from history, to erase evidence of prior page loads and so on. void purgehistory( in long numentries ); parameters numentries the number of toplevel documents to be purged from history. during purge operation, the latest documents are maintained and older numentries documents are removed from history.
exceptions thrown ns_error_failure numentries is invalid or out of bounds with the size of history. ns_success_loss_of_insignificant_data purge was vetoed. reloadcurrententry() void reloadcurrententry(); parameters none. removeshistorylistener() called to remove a listener for the session history component. listeners are notified when pages are loaded from history. note: a listener objec...
nsIScriptError
ull if it's not applicable. read only. timestamp long long elapsed time, in milliseconds, from a platform-specific zero time to the time the message was created. read only. flag constants constant value description errorflag 0x0 error messages. a pseudo-flag for the default, error case. warningflag 0x1 warning messages.
exceptionflag 0x2 an
exception was thrown for this case -
exception-aware hosts can ignore this. strictflag 0x4 one of the flags declared in nsiscripterror. infoflag 0x8 just a log message methods init() initializes the object with information describing the error which occurred. void init( in wstring message, in wstring sourcename, in wstring sourceline,...
...ere are a lot of categories, and they're not all maintained in a single list anywhere in the code. this is an attempt to group them together for reference. note that these are strings. if you want to log an error at chrome level you should set a category from the first section (leaving it empty might log it as content error). as addon author i would recommend using "chrome javascript" for logging
exceptions caused by addon code. categories the web console does not display "xpconnect javascript" "component javascript" "chrome javascript" "chrome registration" "xbl" "xbl prototype handler" "xbl content sink" "xbl javascript" "frameconstructor" categories the web console displays "hudconsole" "css parser" "css loader" "content javascript" "dom events" "dom:html" "dom window" "s...
nsIScriptableUnescapeHTML
ue if the fragment is an xml string; otherwise set it to false. baseuri pointer to the base uri against which to resolve any uris included in the fragment. this parameter is ignored if isxml is false. element the nsidomelement to be used as the context node for the purposes of the fragment parsing algorithm. return value an nsidomdocumentfragment of the element with the new text appended.
exceptions thrown ns_error_failure unable to append the text to the element. unescape() convents html source into plain text. this is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0). you should call nsiparserutils::converttoplaintext() instead of calling this method. astring unescape( in astring s...
... is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0). you should call nsiparserutils::converttoplaintext() instead of calling this method. astring unescape( in astring src ); parameters src the html string to convert into plain text. return value the result of the plain text conversion.
exceptions thrown ns_error_failure unable to convert the string. see also nsidomdocumentfragment nsiuri nsidomelement ...
nsISeekableStream
rameters whence specifies how to interpret the 'offset' parameter in setting the stream offset associated with the implementing stream, according to the table of constants above. offset specifies a value, in bytes, that is used in conjunction with the 'whence' parameter to set the stream offset of the implementing stream. a negative value causes seeking in the reverse direction.
exceptions thrown ns_base_stream_closed if called on a closed stream. seteof() this method truncates the stream at the current offset. void seteof(); parameters none.
exceptions thrown ns_base_stream_closed if called on a closed stream. tell() this method reports the current offset, in bytes, from the start of the stream. long long tell(); parameters none. return value the current off...
...lled on a closed stream. seteof() this method truncates the stream at the current offset. void seteof(); parameters none.
exceptions thrown ns_base_stream_closed if called on a closed stream. tell() this method reports the current offset, in bytes, from the start of the stream. long long tell(); parameters none. return value the current offset, in bytes, from the start of the stream.
exceptions thrown ns_base_stream_closed if called on a closed stream. ...
nsIUTF8ConverterService
through the conversion. skipping asciiness/utf8ness check. the most common case is the input is in 7bit non-ascii character sets like iso-2022-jp, hz or utf-7 (in its original form or a modified form used in imap folder names). aallowsubstitution when true, allow the decoder to substitute invalid input sequences by replacement characters. return value the converted string in utf-8.
exceptions thrown ns_error_uconv_noconv when there is no decoder for acharset or error code of nsiunicodedecoder in case of conversion failure. converturispectoutf8() ensure that aspec (after url-unescaping it) is encoded in utf-8. if not, convert it to utf-8, assuming it's encoded in acharset, and return the result. make sure that all characters outside us-ascii in your input spec are url-e...
...n unescaped utf-8 and it will be returned without further processing. no valid spec going around in mozilla code would break this assumption. autf8string converturispectoutf8( in acstring aspec, in string acharset ); parameters aspec an url-escaped uri spec to ensure its utf8ness. acharset the character set to convert from if aspec is not in utf-8. return value the converted spec in utf-8.
exceptions thrown ns_error_uconv_noconv when there is no decoder for acharset or error code of nsiunicodedecoder in case of conversion failure. ...
nsIUUIDGenerator
rfaces.nsiuuidgenerator); method overview nsidptr generateuuid(); void generateuuidinplace(in nsnonconstidptr id); native code only! methods generateuuid() obtains a new uuid using appropriate platform-specific methods to obtain a nsid that can be considered to be globally unique. nsidptr generateuuid(); parameters none. return value this method returns a nsidptr containing a unique id.
exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) native code only!generateuuidinplace obtain a new uuid like the generateuuid() method, but place it in the provided nsid pointer instead of allocating a new nsid. void generateuuidinplace( in nsnonconstidptr id ); parameters id an existing nsid pointer where the uuid w...
...or_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) native code only!generateuuidinplace obtain a new uuid like the generateuuid() method, but place it in the provided nsid pointer instead of allocating a new nsid. void generateuuidinplace( in nsnonconstidptr id ); parameters id an existing nsid pointer where the uuid will be stored. ...
nsIZipReader
the patterns foo or bar may use the 'pat~pat2' syntax described immediately above. \ will escape a special character. escaping is required for all special characters unless otherwise specified. all other characters match case-sensitively. an apattern not conforming to this syntax has undefined behavior. return value the nsiutf8stringenumerator containing the matching entry names.
exceptions thrown ns_error_illegal_value on many but not all invalid apattern values. getcertificateprincipal() returns an object describing the entity which signed an entry. 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 (...
...directory) { var inputstream = zr.getinputstream(entrypointer); reusablestreaminstance.init(inputstream); var filecontents = reusablestreaminstance.read(entry.realsize); console.log('contenst of file=', filecontents); } else { console.log('is directory, no stream to read'); } } } catch (ex) { console.warn('
exception occured = ', ex); if (ex.name == 'ns_error_file_not_found') { services.ww.activewindow.alert('xpi at path does not exist!\n\npath = ' + pathtoxpitoread); } } finally { zr.close(); console.log('zr closed'); } see also nsizipentry nsizipwriter ...
XPCOM Interface Reference by grouping
ccessibletable nsiaccessibletext nsiaccessibletreecache nsiaccessiblevalue nsiaccessnode nsisyncmessagesender script nsiscriptableunescapehtml nsiscriptableunicodeconverter nsiscripterror nsiscripterror2 stylesheet nsistylesheetservice url nsiuri nsiurl util nsidomserializer nsidomxpathevaluator nsidomxpath
exception nsidomxpathexpression nsidomxpathresult xslt nsixslt
exception nsixsltprocessor download nsidownload nsidownloadmanager nsidownloadprogresslistener element internal nsiworker nsiworkerglobalscope nsiworkermessageevent nsiworkermessageport nsiworkerscope tree nsitreeboxobject nsitreecolumn nsitreecolumns ...
... nsiaccelerationlistener nsiaccelerometer misc nsisound nsiwifimonitor document nsiwebnavigation environment nsienvironment event nsieventlistenerinfo nsieventlistenerservice nsieventtarget
exception nsi
exception extention nsiextensionmanager nsiinstalllocation external nsiexternalprotocolservice frame nsicontentframemessagemanager history nsishentry nsishistory idle nsiidleservice internal ...
Storage
e statement. warning: if you fail to reset a write statement, it will continue to hold a lock on the database preventing future writes or reads. additionally, if you fail to reset a read statement, it will prevent any future writes to the database. in javascript, the language makes it pretty easy to ensure that you always reset a statement. be aware that you should always reset even if an
exception is thrown, so your code should look something like this: var statement = dbconn.createstatement("select * from table_name"); try { while (statement.step()) { // use the results... } } finally { statement.reset(); } in c++, storage provides a helper object in storage/public/mozstoragehelper.h, mozstoragestatementscoper, which ensures that the statement object is reset when the object ...
...onous and synchronous statement execution. the best way to deal with this is to only execute your statements asynchronously using mozistorageconnection.executeasync(). this method will manage the transactions for you, so you don't have to worry about them. note: the database engine does not support nested transactions, so attempting to start a transaction when one is already active will throw an
exception. transactions can be started with mozistorageconnection.begintransaction() or mozistorageconnection.begintransactionas(). the latter takes one of three constants to describe the type of transaction: mozistorageconnection.transaction_deferred mozistorageconnection.transaction_immediate mozistorageconnection.transaction_exclusive mozistorageconnection.begintransaction() is equivalent to cal...
Getting Started Guide
ddref|s the new one, in the appropriate sequence to avoid the ownership bug mentioned earlier. */ mfooptr = afooptr; additionally, the class using raw xpcom interface pointers will need a destructor to release mfooptr; and a constructor to ensure that mfooptr is initially set to null (or some other reasonable value). nscomptr helps you write code that is leak-proof,
exception safe, and significantly less verbose than you would with raw xpcom interface pointers. with nscomptr, you may never have to call addref, release, or queryinterface by hand. you still have to understand xpcom. you still have to know which functions return interface pointers that have already been addrefed and which don't. you still have to ensure your program logic doesn't produce circularly refe...
...s. you should use nscomptr on the stack, where it makes calling queryinterface almost pleasant, and eliminates the complex logic that falls out of error handling. where shouldn't i use nscomptrs? don't use nscomptrs where you don't need an owning reference. see some com ownership guidelines. nscomptr is designed to be used with xpcom interfaces, so don't use it with non-interfaces with specific
exceptions described below. don't use nscomptrs in xpcom interfaces. don't use them in plain old c code; nscomptrs are, of course, a c++ only construct. never cast an nscomptr, it's almost guaranteed to leak. nscomptrs for non-interface classes appropriately formatted answer to come, in the meanwhile, the full details are available in this news posting (via google groups). nscomptrs in function signatur...
Using the Gecko SDK
he right way" such that they will remain compatible with future versions of mozilla. for information on how to retrieve and install the gecko sdk, see here. an xpcom component will be compatible with future versions of mozilla if it only makes use of frozen gecko apis. a frozen gecko api is one that is included in the gecko and marked frozen with the text <tt>@status frozen</tt> (with nspr as the
exception to the rule). the frozen gecko api consists of a set of component interfaces (c++ vtables) and <tt>extern "c"</tt> symbols exported from the xpcom library and the nspr libraries. 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). the gecko abi is therefore comp...
...orm. the sdk contains headers for all of the frozen interfaces and functions, and it also contains headers for classes and functions defined in the glue libraries. when those classes or functions are used, the component must link with the corresponding static library. every frozen interface or function will be labeled as such in the idl or header file with "@status frozen". (note: nspr is the one
exception to this rule. all nspr functions are frozen by default and are not marked as such in the respective header files.) the glue library exists to make common tasks easier. for example, the nscomptr class is defined in the xpcom glue library. if your component does not use any of the glue classes or functions, then you do not need to link against the glue library. work in progress... linking (link li...
Declaring and Using Callbacks
warning: you must store a reference to the callback object as long as the native code might call it. if you don't, the gc might collect the relev...
... warning: you must store a reference to the callback object as long as the native code might call it. ...
Working with data
of the syntax for creating cdata objects without immediately assigning them a value: var mycdataobj = new type; var mycdataobj = new type(); var mycdataobj = type(); these all do the same thing: they return a new cdata object of the specified type, whose data buffer has been populated entirely with zeroes. note: if type.size is undefined, creating a new object this way will throw a typeerror
exception. 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. if the conversion i...
... ...
CData
tostring() properties properties of all cdata objects property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror
exception if the value can't be converted. methods available on all cdata objects address() returns a cdata object of the pointer type ctypes.pointertype(dataobject.constructor) whose value points to the c object referred to by the object. this provides a way to get a pointer to the actual data of the c value represented by the cdata object. cdata address() parameters none. return value a cd...
...string identifying the data. 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. readstring() converts a character array to a javascript string. 8-bit strings are assumed to be encoded as utf-8. if the 8-bit string contains invalid encoded character, a typeerror
exception is thrown. string readstring(); parameters none. return value a new string object that is a copy of the original string contents. readstringreplacemalformed() converts a character array to a javascript string. 8-bit strings are assumed to be encoded as utf-8. if the 8-bit string contains invalid encoded character, no
exception is thrown. string readstringreplacemalformed(); parameter...
FunctionType
ction; this is one of the abi constants. returntype a ctype indicating the type of the value returned by the function. argtype1... argtypen zero or more ctype objects indicating the types of each of the parameters passed into the c function. return value a ctype describing the function type. the equivalent c function type declaration would be: returntype (*) ([argtype1, ..., argtypen]);
exceptions thrown typeerror abi is not a valid abi constants, or returntype or any of the argument types are not valid ctype objects. properties property type description abi one of the abi constants the abi of the function. read only. argtypes ctype[] a sealed array of the argument types. read only. returntype ctype the return type of the ...
... ctype array([n]) string tosource() string tostring() functiontype cdata functiontype cdata cannot be constructed. function pointer is created with functiontype.ptr. cdata functiontype.ptr([func]); functiontype is functiontype ctype. parameters func a pointer value or javascript function. return value a cdata representing the newly allocated function pointer.
exceptions thrown typeerror func is not either pointer value or javascript function. see also ctype cdata abi library type conversion ...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
ebuggertoglobal(window); (function () { // the debugger we'll use to observe a tab's allocation. var dbg; // start measuring the selected tab's main window's memory // consumption. this function is available in the browser // console. window.demotrackallocations = function() { dbg = new debugger; // this makes hacking on the demo *much* more // pleasant. dbg.uncaught
exceptionhook = handleuncaught
exception; // find the current tab's main content window. var w = gbrowser.selectedbrowser.contentwindow; console.log("tracking allocations in page: " + w.location.href); // make that window a debuggee of our debugger. dbg.adddebuggee(w.wrappedjsobject); // enable allocation tracking in dbg's debuggees. dbg.memory.trackingallocati...
...ow.demoplotallocations = function() { // grab the allocation log. var log = dbg.memory.drainallocationslog(); // neutralize the debugger, and drop it on the floor // for the gc to collect. console.log("stopping allocation tracking."); dbg.removealldebuggees(); dbg = undefined; // analyze and display the allocation log. plot(log); } function handleuncaught
exception(ex) { console.log('debugger hook threw:'); console.log(ex.tostring()); console.log('stack:'); console.log(ex.stack); }; function plot(log) { // given the log, compute a map from allocation sites to // allocation counts. note that stack entries are '===' if // they represent the same site with the same callers. var counts = new map; for (let site of log) { ...
Debugger.Object - Firefox Developer Tools
the descriptions use "referent" to mean "the referent of this debugger.object instance". unless otherwise specified, these methods are not invocation functions; if a call would cause debuggee code to run (say, because it gets or sets an accessor property whose handler is debuggee code, or because the referent is a proxy whose traps are debuggee code), the call throws a debugger.debuggeewouldrun
exception. getproperty(name) return the value of the referent's property namedname, or undefined if it has no such property.name must be a string. the result is a debuggee value. setproperty(name,value) storevalue as the value of the referent's property namedname, creating the property if it does not exist.name must be a string;value must be a debuggee value. getownpropertydescriptor(name) ...
... evalinglobal(code, [options]) if the referent is a global object, evaluatecode in that global environment, and return a completion value describing how it completed.code is a string. all extant handler methods, breakpoints, watchpoints, and so on remain active during the call. this function follows the invocation function conventions. if the referent is not a global object, throw a typeerror
exception. codeis interpreted as strict mode code when it contains a use strict directive. ifcode is not strict mode code, then variable declarations incode affect the referent global object. (in the terms used by the ecmascript specification, the variableenvironment of the execution context for the eval code is the referent.) theoptions argument is as for debugger.frame.prototype.eval. evalinglob...
Animation.finish() - Web APIs
ent playback time to the end of the animation corresponding to the current playback direction. 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. syntax animation.finish(); parameters none. return value none.
exceptions invalidstate the player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. examples the following example shows how to use the finish() method and catch an invalidstate error. interfaceelement.addeventlistener("mousedown", function() { try { player.finish(); } catch(e if e instanceof invalidstate) { console.l...
...an 0 and the end time of the animation is infinity. examples the following example shows how to use the finish() method and catch an invalidstate error. 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. elem.getanimations().foreach( function(animation){ return animation.finish(); } ); specifications specification status comment web animationsthe definition of 'finish()' in that specification. working draft ...
AudioContext() - Web APIs
of audiocontext.baselatency to determine the true latency after creating the context. samplerate optional the samplerate to be used by the audiocontext, specified in samples per second. the value may be any value supported by audiobuffer. if not specified, the preferred sample rate for the context's output device is used by default. return value the newly constructed audiocontext instance.
exceptions notsupportederror the specified samplerate isn't supported by the context. usage notes the specification doesn't go into a lot of detail about things like how many audio contexts a user agent should support, or minimum or maximum latency requirements (if any), so these details can vary from browser to browser. be sure to check the values if they matter to you. in particular, the specific...
...lues if they matter to you. in particular, the specification doesn't indicate a maximum or minimum number of audio contexts that must be able to be open at the same time, so this is left up to the browser implementations to decide. google chrome per-tab audio context limitation in chrome prior to version 66 google chrome only supported up to six audio contexts per tab at a time. non-standard
exceptions in chrome if the value of the latencyhint property isn't valid, chrome throws a typeerror
exception with the message "the provided value '...' is not a valid enum value of type audiocontextlatencycategory". example this example creates a new audiocontext for interactive audio (optimizing for latency) and a sample rate of 44.1khz. var audiocontext = window.audiocontext || window.webkitaudioc...
AudioNode.connect() - Web APIs
stination you want to connect the current audionode to; the default is 0. the index numbers are defined according to the number of input channels (see audio channels). it is possible to connect an audionode to another audionode, which in turn connects back to the first audionode, creating a cycle. this is allowed only if there is at least one delaynode in the cycle. ...
... invalidaccesserror the destination node is not part of the same audio context as the source node. ...
AudioParam.setValueCurveAtTime() - Web APIs
iven interval starting at starttime and a specific duration. syntax var paramref = param.setvaluecurveattime(values, starttime, duration); parameters values an array of floating-point numbers representing the value curve the audioparam will change through along the specified duration. every value in the array must be a finite number; if any value is nan, infinity, or -infinity, a typeerror
exception is thrown. starttime a double representing the time (in seconds) after the audiocontext was first created that the change in value will happen. if this value is lower than audiocontext.currenttime, it is clamped to currenttime. duration a double representing the total time (in seconds) over which the parameter's value will change following the specified curve. the specified values are spaced ...
...alue is lower than audiocontext.currenttime, it is clamped to currenttime. duration a double representing the total time (in seconds) over which the parameter's value will change following the specified curve. the specified values are spaced equally along this duration. return value a reference to this audioparam object. some older browser implementations of this interface return undefined.
exceptions invalidstateerror the specified array of values has fewer than 2 items in it. rangeerror the specified starttime is either negative or a non-finite value, or duration is not a finite, strictly positive number. typeerror one or more of the values in the values array is non-finite. non-finite values are nan, infinity, and -infinity. usage notes when the parameter's value finishes follow...
CSSPrimitiveValue.getFloatValue() - Web APIs
syntax var floatvalue = cssprimitivevalue.getfloatvalue(unit); parameters unittype an unsigned short representing the code for the unit type, in which the value should be returned. valid values are: constant description css_cm the value is a <length> in centimeters. ...
...s_pc the value is a <length> in picas. css_percentage the value is a <percentage>. css_pt the value is a <length> in points. css_px the value is a <length> in pixels. css_rad the value is an <angle> in radians. css_s the value is a <time> in seconds. return value a float value in the specified unit.
exceptions type description dom
exception an invalid_access_err is raised if the css value doesn't contain a float value or if the float value can't be converted into the specified unit. example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("margin-top"); console.log(cssvalue.getfloatvalue(cssprimitivevalue.css_cm)); specificatio...
CSSPrimitiveValue.setFloatValue() - Web APIs
syntax cssprimitivevalue.setfloatvalue(unittype, floatvalue); parameters unittype an unsigned short representing the code for the unit type, in which the value should be returned. valid values are: constant description css_cm the value is a <length> in centimeters. ...
...<length> in picas. css_percentage the value is a <percentage>. css_pt the value is a <length> in points. css_px the value is a <length> in pixels. css_rad the value is an <angle> in radians. css_s the value is a <time> in seconds. floatvalue a float representing the new float value. return value void.
exceptions type description dom
exception an invalid_access_err is raised if the css value doesn't contain a float value or if the string value can't be converted into the specified unit. an no_modification_allowed_err is raised if this property is read-only. specifications specification status comment document object model (dom) level 2 style...
CSSPrimitiveValue.setStringValue() - Web APIs
the setstringvalue() method of the cssprimitivevalue interface is used to set a string value. if the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a dom
exception will be raised. syntax cssprimitivevalue.setstringvalue(stringtype, stringvalue); parameters stringtype an unsigned short representing the type of the value. possible values are: constant description css_attr the value is an attr() function. css_ident the value is an identifier. ...
...representing the type of the value. possible values are: constant description css_attr the value is an attr() function. css_ident the value is an identifier. css_string the value is a <string>. css_uri the value is a <uri>. stringvalue a domstring representing the new string value. return value void.
exceptions type description dom
exception an invalid_access_err is raised if the css value doesn't contain a string value or if the string value can't be converted into the specified unit. an no_modification_allowed_err is raised if this property is read-only. specifications specification status comment document object model (dom) level 2 styl...
Cache - Web APIs
. (see selective caching live) the code uses cachestorage.open() to open any cache objects with a content-type header that starts with font/. the code then uses cache.match() to see if there's already a matching font in the cache, and if so, returns it. if there isn't a matching font, the code fetches the font from the network and uses cache.put() to cache the fetched resource. the code handles
exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an
exception. it will return a normal response object that has the appropriate error code. the code snippet also shows a best practice for versioning caches used by the service worker. though there's only one cache in this example, the same approach can be used for multiple caches. it maps a shortha...
...to', event.request.url); cache.put(event.request, response.clone()); } else { console.log(' not caching the response to', event.request.url); } // return the original response object, which will be used to fulfill the resource request. return response; }); }).catch(function(error) { // this catch() will handle
exceptions that arise from the match() or fetch() operations. // note that a http error response (e.g. 404) will not trigger an
exception. // it will return a normal response object that has the appropriate error code set. console.error(' error in fetch handler:', error); throw error; }); }) ); }); storing cookies in caches the fetch api requires set-cookie h...
ClipboardItem.getType() - Web APIs
typeerror no parameter is specified or the type is not that of the clipboarditem. ...
... typeerror no parameter is specified or the type is not that of the clipboarditem. ...
DOMMatrixReadOnly - Web APIs
. for a 2d matrix, the elements a through f are listed, for a total of six values and the form matrix(a, b, c, d, e, f). for a 3d matrix, the returned string contains all 16 elements and takes the form matrix3d(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44). see the css matrix3d() function for details on the 3d notation's syntax. throws an invalidstateerror
exception if any of the elements in the matrix are non-finite (even if, in the case of a 2d matrix, the non-finite values are in elements not used by the 2d matrix representation). dommatrixreadonly.transformpoint() transforms the specified point using the matrix, returning a new dompoint object containing the transformed point. neither the matrix nor the original point are altered. dommatrixreadonly.
..., the vector is (0, 0, 0). the original matrix is not changed. static methods this interface inherits methods from dommatrixreadonly. fromfloat32array() creates a new mutable dommatrix object given an array of single-precision (32-bit) floating-point values. if the array has six values, the result is a 2d matrix; if the array has 16 values, the result is a 3d matrix. otherwise, a typeerror
exception is thrown. fromfloat64array() creates a new mutable dommatrix object given an array of double-precision (64-bit) floating-point values. if the array has six values, the result is a 2d matrix; if the array has 16 values, the result is a 3d matrix. otherwise, a typeerror
exception is thrown. frommatrix() creates a new mutable dommatrix object given an existing matrix or a dommatrixinit dictiona...
Document.querySelector() - Web APIs
th-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes. syntax element = document.queryselector(selectors); parameters selectors a domstring containing one or more selectors to match. this string must be a valid css selector string; if it isn't, a syntax_err
exception is thrown. see locating dom elements using selectors for more about selectors and how to manage them. note: characters that are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, be especially careful when writing string literals using these characters. see escaping special characters for more information. return value ...
...when writing string literals using these characters. see escaping special characters for more information. return value an htmlelement object representing the first element in the document that matches the specified set of css selectors, or null is returned if there are no matches. if you need a list of all elements matching the specified selectors, you should use queryselectorall() instead.
exceptions syntax_err the syntax of the specified selectors is invalid. usage notes if the specified selector matches an id that is incorrectly used more than once in the document, the first element with that id is returned. css pseudo-elements will never return any elements, as specified in the selectors api. escaping special characters to match against an id or selectors that do not follow stan...
Document.querySelectorAll() - Web APIs
ist of the document's elements that match the specified group of selectors. note: this method is implemented based on the parentnode mixin's queryselectorall() method. syntax elementlist = parentnode.queryselectorall(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid css selector string; if it's not, a syntaxerror
exception is thrown. see locating dom elements using selectors for more information about using selectors to identify elements. multiple selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, special care must be taken when writing string literals us...
...t be taken when writing string literals using these characters. see escaping special characters for more information. return value a non-live nodelist containing one element object for each element that matches at least one of the specified selectors or an empty nodelist in case of no matches. note: if the specified selectors include a css pseudo-element, the returned list is always empty.
exceptions syntaxerror the syntax of the specified selectors string is not valid. examples obtaining a list of matches to obtain a nodelist of all of the <p> elements in the document: var matches = document.queryselectorall("p"); this example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.queryselectorall("div.note, div.alert...
Document - Web APIs
has special meaning in privileged javascript code (with universalxpconnect privileges). document.popupnode returns the node upon which a popup was invoked. document.tooltipnode returns the node which is the target of the current tooltip. ...
... internet explorer notes microsoft defines some non-standard properties: document.filesize* returns size in bytes of the document. starting with internet explorer 11, that property is no longer supported. see msdn. ...
Document Object Model (DOM) - Web APIs
ture, style, or content. nodes can also have event handlers attached to them. once an event is triggered, the event handlers get executed. to learn more about what the dom is and how it represents documents, see our article introduction to the dom. ...
...eger svganimatedlength svganimatedlengthlist svganimatednumber svganimatednumberlist svganimatedpathdata svganimatedpoints svganimatedpreserveaspectratio svganimatedrect svganimatedstring svganimatedtransformlist smil-related interfaces elementtimecontrol timeevent other svg interfaces getsvgdocument shadowanimation svgcolorprofilerule svgcssrule svgdocument svg
exception svgexternalresourcesrequired svgfittoviewbox svglangspace svglocatable svgrenderingintent svgstylable svgtests svgtransformable svgunittypes svguseelementshadowroot svgurireference svgviewspec svgzoomandpan svgzoomevent specifications specification status comment dom living standard ...
Element.outerHTML - Web APIs
n element, use the innerhtml property instead. syntax var content = element.outerhtml; element.outerhtml = htmlstring; value reading the value of outerhtml returns a domstring containing an html serialization of the element and its descendants. setting the value of outerhtml replaces the element and all of its descendants with a new dom tree constructed by parsing the specified htmlstring.
exceptions syntaxerror an attempt was made to set outerhtml using an html string which is not valid. nomodificationallowederror an attempt was made to set outerhtml on an element which is a direct child of a document, such as document.documentelement. examples getting the value of an element's outerhtml property: html <div id="d"> <p>content</p> <p>further elaborated</p> </div> javascript ...
....firstchild.nodename); // logs "div" d.outerhtml = "<p>this paragraph replaced the original div.</p>"; console.log(container.firstchild.nodename); // logs "p" // the #d div is no longer part of the document tree, // the new paragraph replaced it. notes if the element has no parent element, setting its outerhtml property will not change it or its descendants. many browsers will also throw an
exception. for example: var div = document.createelement("div"); div.outerhtml = "<div class=\"test\">test</div>"; console.log(div.outerhtml); // output: "<div></div>" also, while the element will be replaced in the document, the variable whose outerhtml property was set will still hold a reference to the original element: var p = document.getelementsbytagname("p")[0]; console.log(p.nodename); // shows:...
Element.querySelector() - Web APIs
eryselector() method of the element interface returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors. syntax element = baseelement.queryselector(selectors); parameters selectors a group of selectors to match the descendant elements of the element baseelement against; this must be valid css syntax, or a syntaxerror
exception will occur. the first element found which matches this group of selectors is returned. return value the first descendant element of baseelement which matches the specified group of selectors. the entire hierarchy of elements is considered when matching, including those outside the set of elements including baseelement and its descendants; in other words, selectors is first applied to the whole...
...aseelement and its descendants; in other words, selectors is first applied to the whole document, not the baseelement, to generate an initial list of potential elements. the resulting elements are then examined to see if they are descendants of baseelement. the first match of those remaining elements is returned by the queryselector() method. if no matches are found, the returned value is null.
exceptions syntaxerror the specified selectors are invalid. examples let's consider a few examples. find a specific element with specific values of an attribute in this first example, the first <style> element which either has no type or has type "text/css" in the html document body is returned: var el = document.body.queryselector("style[type='text/css'], style:not([type])"); the entire hierar...
Element.querySelectorAll() - Web APIs
ectors which are descendants of the element on which the method was called. note: this method is implemented based on the parentnode mixin's queryselectorall() method. syntax elementlist = parentnode.queryselectorall(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid css selector string; if it's not, a syntaxerror
exception is thrown. see locating dom elements using selectors for more information about using selectors to identify elements. multiple selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backspace escaping, special care must be taken when writing string literals us...
...ackspace escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. return value a non-live nodelist containing one element object for each descendant node that matches at least one of the specified selectors. note: if the specified selectors include a css pseudo-element, the returned list is always empty.
exceptions syntaxerror the syntax of the specified selectors string is not valid. examples dataset selector & attribute selectors <section class="box" id="sect1"> <div class="funnel-chart-percent1">10.900%</div> <div class="funnel-chart-percent2">3700.00%</div> <div class="funnel-chart-percent3">0.00%</div> </section> // dataset selectors const refs = [...document.queryselectorall(`[data-na...
Element.requestFullscreen() - Web APIs
ol the behavior of the transition to full-screen mode. currently, the only option is navigationui, which controls whether or not to show navigation ui while the element is in full-screen mode. the default value is "auto", which indicates that the browser should decide what to do. return value a promise which is resolved with a value of undefined when the transition to full screen is complete. ...
...reen mode. currently, the only option is navigationui, which controls whether or not to show navigation ui while the element is in full-screen mode. the default value is "auto", which indicates that the browser should decide what to do. return value a promise which is resolved with a value of undefined when the transition to full screen is complete.
exceptions rather than throw a traditional
exception, the requestfullscreen() procedure announces error conditions by rejecting the promise it has returned. the rejection handler receives one of the following
exception values: typeerror the typeerror
exception may be delivered in any of the following situations: the document containing the element isn't fully active; that is, it's not the current active document. the element is not contai...
Event.initEvent() - Web APIs
full support yesedge full support 12firefox full support 17 full support 17 no support ? ...
...not for use in new websites.
FileSystemDirectoryEntry.getDirectory() - Web APIs
for androidsafari on iossamsung internetgetdirectory experimentalchrome full support 8edge full support 79firefox full support 50notes full support 50notes notes in firefox, the errorcallback's input parameter is a dom
exception rather than a fileerror object.ie no support noopera no support nosafari full support 11.1webview android full support ≤37chrome android full support 18firefox android ...
...t 11.1webview android full support ≤37chrome android full support 18firefox android full support 50notes full support 50notes notes in firefox, the errorcallback's input parameter is a dom
exception rather than a fileerror object.opera android no support nosafari ios full support 11.3samsung internet android full support yeslegend full support full support n...
FileSystemDirectoryEntry.getFile() - Web APIs
opera for androidsafari on iossamsung internetgetfile experimentalchrome full support 8edge full support 79firefox full support 50notes full support 50notes notes in firefox, the errorcallback's input parameter is a dom
exception rather than a fileerror object.ie no support noopera no support nosafari full support 11.1webview android full support ≤37chrome android full support 18firefox android ...
...t 11.1webview android full support ≤37chrome android full support 18firefox android full support 50notes full support 50notes notes in firefox, the errorcallback's input parameter is a dom
exception rather than a fileerror object.opera android no support nosafari ios full support 11.3samsung internet android full support yeslegend full support full support n...
HTMLMediaElement.play() - Web APIs
s been successfully started. failure to begin playback for any reason, such as permission issues, result in the promise being rejected. syntax var promise = htmlmediaelement.play(); parameters none. return value a promise which is resolved when playback has been started, or is rejected if for any reason playback cannot be started. note: older browsers may not return a value from play().
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). possible errors include: notallowederror the user agent (browser) or operating system doesn't allow playback of media in the current context or situation. this may happen, for example, if the browser requires the user to explicitly star...
...t (browser) or operating system doesn't allow playback of media in the current context or situation. this may happen, for example, if the browser requires the user to explicitly start media playback by clicking a "play" button. notsupportederror the media source (which may be specified as a mediastream, mediasource, blob, or file, for example) doesn't represent a supported media format. other
exceptions may be reported, depending on browser implementation details, media player implementation, and so forth. 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 ...
HTMLMediaElement - Web APIs
k objects contained in the element. htmlmediaelement.autoplay a boolean that reflects the autoplay html attribute, indicating whether playback should automatically begin as soon as enough media is available to do so without interruption. note: automatically 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. see the autoplay guide for media and web audio apis for more information. keep in mind that browsers may ignore autoplay requests, so you should ensure that your code isn't dependent on autoplay working. htmlmediaelement.buffered read only returns a timeranges object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is ...
... in the framebuffer of each mozaudioavailable event. this number is a total for all channels, and by default is set to be the number of channels * 1024 (e.g., 2 channels * 1024 samples = 2048 total). the mozframebufferlength property can be set to a new value for lower latency, larger amounts of data, etc. the size given must be a number between 512 and 16384. using any other size results in an
exception being thrown. the best time to set a new length is after the loadedmetadata event fires, when the audio info is known, but before the audio has started or mozaudioavailable events have begun firing. htmlmediaelement.mozsamplerate read only returns a double representing the number of samples per second that will be played. for example, 44100 samples per second is the sample rate used by c...
HTMLSelectElement.add() - Web APIs
tion elements for this select element. syntax collection.add(item[, before]); parameters item is an htmloptionelement or htmloptgroupelement before is optional and an element of the collection, or an index of type long, representing the item item should be inserted before. if this parameter is null (or the index does not exist), the new element is appended to the end of the collection.
exceptions a domerror of the type hierarchyrequesterror if the item passed to the method is an ancestor of the htmlselectelement. examples creating elements from scratch var sel = document.createelement("select"); var opt1 = document.createelement("option"); var opt2 = document.createelement("option"); opt1.value = "1"; opt1.text = "option: value 1"; opt2.value = "2"; opt2.text = "option: value 2"...
... before can now be a long and is optional. it throws a domerror of the type hierarchyrequesterror if the passed item is an ancestor of the htmlselectelement and no longer throws if the before parameter is not found. document object model (dom) level 2 html specificationthe definition of 'htmlselectelement.add()' in that specification. obsolete the method now throws an not_found_err
exception if the item of the before parameter is not a child of this element. document object model (dom) level 1 specificationthe definition of 'htmlselectelement.add()' in that specification. obsolete initial definition ...
HTMLTableRowElement - Web APIs
reflects the valign attribute and can have one of the following values: "top", "middle", "bottom", or "baseline". methods inherits methods from its parent, htmlelement. htmltablerowelement.deletecell() removes the cell at the given position in the row. if the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than 0, it raises a dom
exception with the indexsizeerror value. htmltablerowelement.insertcell() inserts a new cell just before the given position in the row. if the given position is not given or is -1, it appends the cell to the row. if the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than -1, it raises a dom
exception with the indexsizeerror value. returns a ref...
...n of 'htmltablerowelement' in that specification. recommendation the parameter of insertcell is now optional and default to -1. document object model (dom) level 2 html specificationthe definition of 'htmltablerowelement' in that specification. obsolete the cells, rowindex, and selectionrowindex properties are now read-only. the methods insertcell and deletecell can raise
exceptions. document object model (dom) level 1 specificationthe definition of 'htmltablerowelement' in that specification. obsolete initial definition. ...
History.pushState() - Web APIs
ate object. the state object can be anything that can be serialized. because firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. if you pass a state object whose serialized representation is larger than this to pushstate(), the method will throw an
exception. if you need more space than this, you're encouraged to use sessionstorage and/or localstorage. title most browsers currently ignore this parameter, although they may use it in the future. passing the empty string here should be safe against future changes to the method. alternatively, you could pass a short title for the state to which you're moving. url optional the new history entry's url ...
...given by this parameter. 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. the new url does not need to be absolute; if it's relative, it's resolved relative to the current url. the new url must be of the same origin as the current url; otherwise, pushstate() will throw an
exception. if this parameter isn't specified, it's set to the document's current url. 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. but pushstate() has a few advantages: the new url can be any url in the same origin as the current url. in contrast, setti...
IDBDatabase.transaction() - Web APIs
u can specify its name as a string. therefore the following lines are equivalent: var transaction = db.transaction(['my-store-name']); var transaction = db.transaction('my-store-name'); if you need to access all object stores in the database, you can use the property idbdatabase.objectstorenames: var transaction = db.transaction(db.objectstorenames); passing an empty array will throw an
exception. mode optional the types of access that can be performed in the transaction. transactions are opened in one of three modes: readonly, readwrite and readwriteflush (non-standard, firefox-only.) versionchange mode can't be specified here. if you don't provide the parameter, the default access mode is readonly. to avoid slowing things down, don't open a readwrite transaction unless you actually ne...
...k before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. details optional dictionary of other settings, supported only by chrome: return value an idbtransaction object.
exceptions this method may raise a dom
exception of one of the following types:
exception description invalidstateerror the close() method has previously been called on this idbdatabase instance. notfounderror an object store specified in in the storenames parameter has been deleted or removed. typeerror the value for the mode parameter is inval...
IDBFactory.cmp() - Web APIs
s. note: do not use this method for comparing arbitrary javascript values, because many javascript values are either not valid indexeddb keys (booleans and objects, for example) or are treated as equivalent indexeddb keys (for example, since indexeddb ignores arrays with non-numeric properties and treats them as empty arrays, so any non-numeric arrays are treated as equivalent). this throws an
exception if either of the values is not a valid key. syntax var result = indexeddb.cmp(first, second); parameters first the first key to compare. second the second key to compare. return value an integer that indicates the result of the comparison; the table below lists the possible values and their meanings: returned value description -1 1st key is less than the 2nd ...
...rs first the first key to compare. second the second key to compare. return value an integer that indicates the result of the comparison; the table below lists the possible values and their meanings: returned value description -1 1st key is less than the 2nd key 0 1st key is equal to the 2nd key 1 1st key is greater than the 2nd key
exceptions this method may raise a dom
exception of the following types: attribute description dataerror one of the supplied keys was not a valid key. example var a = 1; var b = 2; var result = window.indexeddb.cmp(a, b); console.log( "comparison results: " + result ); specifications specification status comment indexed database api 2.0the defin...
IDBIndex.getAll() - Web APIs
.getall(query, count); parameters query optional a key or an idbkeyrange identifying the records to retrieve. if this value is null or missing, the browser will use an unbound key range. count optional the number records to return. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror
exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. invalidstateerror the idbindex has been deleted or removed. a typeerror ...
... will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. invalidstateerror the idbindex has been deleted or removed. a typeerror
exception is thrown if the count parameter is not between 0 and 232-1 included. example var myindex = objectstore.index('index'); var getallrequest = myindex.getall(); getallrequest.onsuccess = function() { console.log(getallrequest.result); } specification specification status comment indexed database api draftthe definition of 'getall()' in that specification. recommendat...
IDBIndex.getAllKeys() - Web APIs
getallkeys(query, count); parameters query optional a key or an idbkeyrange identifying the keys to retrieve. if this value is null or missing, the browser will use an unbound key range. count optional the number records to return. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror
exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. invalidstateerror the idbindex has been deleted or removed. a type...
...be thrown. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. invalidstateerror the idbindex has been deleted or removed. a typeerror
exception is thrown if the count parameter is not between 0 and 232-1 included. example var myindex = objectstore.index('index'); var getallkeysrequest = myindex.getallkeys(); getallkeysrequest.onsuccess = function() { console.log(getallkeysrequest.result); } specification specification status comment indexed database api draftthe definition of 'getall()' in that specificatio...
IDBIndex.name - Web APIs
invalidstateerror the index, or its object store, has been deleted; or the current transaction is not an upgrade transaction. ...
... invalidstateerror the index, or its object store, has been deleted; or the current transaction is not an upgrade transaction. ...
IDBObjectStore.getAll() - Web APIs
request = objectstore.getall(query); var request = objectstore.getall(query, count); parameters query optional a key or idbkeyrange to be queried. if nothing is passed, this will default to a key range that selects all the records in this object store. count optional specifies the number of values to return if more than one is found. if it is lower than 0 or greater than 232-1 a typeerror
exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid k...
... specifications specification status comment indexed database api draftthe definition of 'getall()' in that specification. ...
IDBTransaction.error - Web APIs
the exact error is one of serveral possibilities. ...
...a android full support 14safari ios full support 8samsung internet android full support 1.5 full support 1.5 no support 1.5 — 7.0prefixed prefixed implemented with the vendor prefix: webkitdom
exception value instead of domerrorchrome full support 48edge full support ≤18firefox full support 58ie no support noopera full support yessafari no support ...
IDBTransaction - Web APIs
t callback: abort due to bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint. this causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. this can be prevented by using preventdefault() on the error event on the request. an explicit abort() call from script. an uncaught
exception in the request's success/error handler. an i/o error (e.g. an actual failure to write to disk, or other os/hardware failure). quota exceeded. a user agent crash. firefox durability guarantees note that as of firefox 40, indexeddb transactions have relaxed durability guarantees to increase performance (see bug 1112702.) previously in a readwrite transaction idbtransaction.oncomplete was fire...
...itical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction. properties idbtransaction.db read only the database connection with which this transaction is associated. idbtransaction.error read only returns a dom
exception indicating the type of error that occured when there is an unsuccessful transaction. this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with theidbtransaction.abort() function. idbtransaction.mode read only the mode for isolating access to data in the object stores that are in the scope of the transaction. the default value is reado...
KeyframeEffect.setKeyframes() - Web APIs
only specified the end state of the animation, and the beginning state is implied. attributes keyframes may specify property-value pairs for any of the animatable css properties. the property names are specified using camel-case so for example background-color becomes backgroundcolor and background-position-x becomes backgroundpositionx. shorthand values such as margin are also permitted. two
exceptional css properties are: float, which must be written as cssfloat since "float" is a reserved word in javascript. it's just for reference here, this will have no effect on animation since "float" is not an animatable css property. offset, which must be written as cssoffset since "offset" represents the keyframe offset as described below. the following special attributes may also be specified: ...
...yframe will be evenly spaced between adjacent keyframes. easing the timing function used from this keyframe until the next keyframe in the series. composite the keyframeeffect.composite operation used to combine the values specified in this keyframe with the underlying value. this will be auto if the composite operation specified on the effect is being used. return value void.
exceptions
exception explanation typeerror one or more of the frames were not of the correct type of object, the keyframes were not loosely sorted by offset, or a keyframe existed with an offset of less than 0 or more than 1. note: if the keyframes cannot be processed or are malformed, the keyframeeffect's keyframes are not modified. examples // passing an array of k...
LocalFileSystem - Web APIs
ent is the filesystem object with two properties: name - the unique name assigned by the browser to the file system. root - the read-only directoryentry object representing the root of the file system. opt_errorcallback the error callback that is called when errors happen or when the request to obtain the file system is denied. its argument is the fileerror object. returns void
exceptions this method can raise an fileerror with the following code:
exception description security_error the application does not have permission to access the file system interface. for example, you cannot run from file://. for more details, see the article on basic concepts. resolvelocalfilesystemurl() lets you look up the entry for a file or directory with a local ur...
...k successcallback, in optional errorcallback errorcallback ); parameters url the url of a local file in the file system. successcallback the success callback that is called when the browser provides the file or directory for the supplied url. errorcallback the error callback that is called when errors happen or when the request to obtain the entry object is denied. returns void
exceptions this method can raise an fileerror with the following code:
exception description encoding_err the syntax of the url was invalid. not_found_err the url was structurally correct, but refers to a resource that does not exist. security_err the application does not have permission to access the file system interface. browser compatibility ...
MediaRecorder.start() - Web APIs
ent. syntax mediarecorder.start(timeslice) parameters timeslice optional the number of milliseconds to record into each blob. 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. return value undefined.
exceptions errors that can be detected immediately are thrown as dom
exceptions. all other errors are reported through error events sent to the mediarecorder object. you can implement the onerror event handler to respond to these errors. invalidmodificationerror the number of tracks on the stream being recorded has changed. you can't add or remove tracks while recording media. invalidstateerror the ...
... can't be recorded using the current configuration. securityerror the mediastream is configured to disallow recording. this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device. this also happens when a mediastreamtrack within the stream is marked as isolated due to the peeridentity constraint on the source stream. this
exception may also be delivered as an error event if the security options for the source media change after recording begins. unknownerror something else went wrong during the recording process. example ... record.onclick = function() { mediarecorder.start(); console.log("recorder started"); } ... specifications specification status comment mediastream recording...
MediaRecorderErrorEvent.error - Web APIs
the read-only error property in the mediarecordererrorevent interface is a dom
exception object providing details about the
exception that was thrown by a mediarecorder instance. when a mediarecordererrorevent occurs, you can determine to some extent what went wrong by examining the error property within the mediarecordererrorevent received by the mediarecorder's error event handler, onerror. syntax error = mediarecordererrorevent.error; value a dom
exception describing the error represented by the event. the error's name property's value may be any
exception that makes sense during the handling of media recording, including these specifically identified by the specification. the descriptions here are generic ones; you'll find more specific ones to various scenarios in which ...
...thin the stream is marked as isolated due to the peeridentity constraint on the source stream. example this function creates and returns a mediarecorder for a given mediastream, configured to buffer data into an array and to watch for errors. ...
MediaRecorderErrorEvent - Web APIs
read only. constructor mediastreamrecorderevent() creates and returns a new mediarecordererrorevent event object with the given parameters. methods inherits methods from its parent interface, event. ...
...read only. constructor mediastreamrecorderevent() creates and returns a new mediarecordererrorevent event object with the given parameters. methods inherits methods from its parent interface, event. ...
Capabilities, constraints, and settings - Web APIs
individual constraints, as well as an optional sub-object named advanced, which contains another set of zero or more constraints which the user agent must satisfy if at all possible. the user agent attempts to satisfy constraints in the order specified in the constraint set. the most important thing to understand is that most constraints aren't requirements; instead, they're requests. there are
exceptions, and we'll get to those shortly. requesting a specific value for a setting most simply, each constraint may be a specific value indicating a desired value for the setting. for example: let constraints = { width: 1920, height: 1080, aspectratio: 1.777777778 }; mytrack.applyconstraints(constraints); in this case, the constraints indicate that any values are fine for nearly all propertie...
... tracks using the code in the two tracks' constraint set edit boxes. function buildconstraints() { try { videoconstraints = json.parse(videoconstrainteditor.value); audioconstraints = json.parse(audioconstrainteditor.value); } catch(error) { handleerror(error); } } this uses json.parse() to parse the code in each editor into an object. if either call to json.parse() throws an
exception, handleerror() is called to output the error message to the log. configuring and starting the stream the startvideo() method handles setting up and starting the video stream. function startvideo() { buildconstraints(); navigator.mediadevices.getusermedia({ video: videoconstraints, audio: audioconstraints }).then(function(stream) { let audiotracks = stream.getaudiotracks();...
Navigator.getBattery() - Web APIs
al details, a guide to using the api, and sample code. note: in some browsers access to this feature is controlled by feature-policy directive battery. syntax var batterypromise = navigator.getbattery(); return value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state.
exceptions this method doesn't throw true
exceptions; instead, it rejects the returned promise, passing into it a dom
exception whose name is one of the following: securityerror the user agent does not expose battery information to insecure contexts and this method was called from insecure context. note: old versions of some user agents might allow use of this feature in insecure contexts. notallowed...
...for example, it might not be explicitly allowed or restricted via feature-policy battery feature. ...
NodeIterator.detach() - Web APIs
the nodeiterator.detach() method is a no-op, kept for backward compatibility only. originally, it detached the nodeiterator from the set over which it iterates, releasing any resources used by the set and setting the iterator's state to invalid. once this method had been called, calls to other methods on nodeiterator would raise the invalid_state_err
exception. ...
...methods on nodeiterator would raise the invalid_state_err
exception. syntax nodeiterator.detach(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodeiterator.detach(); // detaches the iterator nodeiterator.nextnode(); // throws an invalid_state_err
exception specifications specification status comment domthe definition of 'nodeiterator.detach' in that specification. living standard transformed in a no-op document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator.detach' in that specification. obsolete initial definition. ...
ParentNode.querySelector() - Web APIs
selectorall() instead. note: this method is implemented as document.queryselector(), documentfragment.queryselector() and element.queryselector(). syntax element = parentnode.queryselector(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid compound selector list supported by the browser; if it's not, a syntaxerror
exception is thrown. see locating dom elements using selectors for more information about using selectors to identify elements. multiple selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backspace escaping, special care must be taken when writing string literals us...
...avascript also uses backspace escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. return value the first element that matches at least one of the specified selectors or null if no such element is found. note: if the specified selectors include a css pseudo-element, the returned value is always null.
exceptions syntaxerror the syntax of the specified selectors string is not valid. specifications specification status comment domthe definition of 'parentnode.queryselector()' in that specification. living standard living standard selectors api level 2the definition of 'parentnode.queryselector()' in that specification. obsolete no change dom...
ParentNode.querySelectorAll() - Web APIs
he queryselector() method instead. note: this method is implemented as element.queryselectorall(), document.queryselectorall(), and documentfragment.queryselectorall() syntax elementlist = parentnode.queryselectorall(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid css selector string; if it's not, a syntaxerror
exception is thrown. see locating dom elements using selectors for more information about using selectors to identify elements. multiple selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, special care must be taken when writing string literals us...
...ackslash escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. return value a non-live nodelist containing one element object for each descendant node that matches at least one of the specified selectors. note: if the specified selectors include a css pseudo-element, the returned list is always empty.
exceptions syntaxerror the syntax of the specified selectors string is not valid. examples to obtain a nodelist of all of the <p> elements in the document: var matches = document.queryselectorall("p"); this example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.queryselectorall("div.note, div.alert"); here, we get a list of ...
PaymentRequest.show() - Web APIs
ed between instantiating the payment interface and the user beginning to interact with it. the promise should resolve with a paymentdetailsupdate object containing the updated information. return value a promise that eventually resolves with a paymentresponse. the promise is resolved when the user accepts the payment request (such as by clicking a "pay" button in the browser's payment sheet).
exceptions aborterror the returned promise rejects with an aborterror if the user agent is already showing a payment panel. only one payment panel may be visible at a time across all documents loaded by the user agent. the promise is also rejected with aborterror if the user cancels the payment request. invalidstateerror the promise rejects with an invalidstateerror if the same payment has alre...
... checkallvalues() looks at each value in the response and ensures that they're valid, returning true if every field is valid or false if any are not. if and only if every field is valid, the complete() method is called on the response with the string "success", which indicates that everything is valid and that the payment can complete accordingly. if any fields have unacceptable values, or if an
exception is thrown by the previous code, complete() is called with the string "fail", which indicates that the payment process is complete and failed. instead of immediately failing, you could choose to call retry() on the response object to ask the user agent to try to process the payment again; this should usually only be done after the user has made any needed corrections to the order. starting the p...
Using the Payment Request API - Web APIs
; } }); } else { window.location.href = '/legacy-web-form-checkout'; } } note: see our checking user can make payments before prices are known demo for the full code. recommending a payment app when user has no apps if you select to pay with the bobpay demo payment provider on this merchant page, it tries to call paymentrequest.show(), while intercepting the notsupportederr
exception. if this payment method is not supported, it redirects to the signup page for bobpay. the code looks something like this: checkoutbutton.addeventlistener('click', function() { var request = new paymentrequest(buildsupportedpaymentmethoddata(), buildshoppingcartdetails()); request.show().then(function(paymentresponse) { // here we would process the payment. for this demo, simulate ...
...ls()); request.show().then(function(paymentresponse) { // here we would process the payment. for this demo, simulate immediate success: paymentresponse.complete('success') .then(function() { // for demo purposes: intropanel.style.display = 'none'; successpanel.style.display = 'block'; }); }).catch(function(error) { if (error.code == dom
exception.not_supported_err) { window.location.href = 'https://bobpay.xyz/#download'; } else { // other kinds of errors; cancelled or failed payment. for demo purposes: intropanel.style.display = 'none'; legacypanel.style.display = 'block'; } }); }); note: see our recommending a payment app when user has no apps demo for the full code. showing additional user i...
RTCIceCandidate.RTCIceCandidate() - Web APIs
ct is initialized to the value of the property by the same name from rtcicecandidateinit. this includes the candidate, sdpmid, sdpmlineindex, and usernamefragment properties. the candidate string (which is sdp text) is parsed; each property found is stored in the corresponding field in the rtcicecandidate. if any of the fields is invalid, parsing of the string silently aborts without throwing an
exception. the default value of candidate is the empty string, which indicates that the candidate is an "end-of-candidates" message. the following fields are initialized to null if they are not included in the rtcicecandidate.candidate property: foundation, component, priority , ip, protocol, port, type, tcptype, relatedaddress, and relatedport. note: parsing of the candidate string is performed using ...
...ates that the candidate is an "end-of-candidates" message. the following fields are initialized to null if they are not included in the rtcicecandidate.candidate property: foundation, component, priority , ip, protocol, port, type, tcptype, relatedaddress, and relatedport. note: parsing of the candidate string is performed using the candidate-attribute grammar from the webrtc specification.
exceptions typeerror the specified rtcicecandidateinit has values of null in both the sdpmid and sdpmlineindex properties. usage notes this constructor does not do complete validation of the specified candidateinfo object or string. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate()' in that s...
RTCIceCandidate.protocol - Web APIs
the protocol property's value is set when the rtcicecandidate() constructor is used. the value is automatically extracted from the candidate a-line, if it's formatted properly. ...
...information about the kind of tcp candidate represented by the object. udp the candidate will use the udp transport protocol for its data. this is the preferred protocol for media interactions because of its better performance profile. note: if protocol is null — and protocol is supported by the user agent — passing the candidate to addicecandidate() will fail, throwing an operationerror
exception. usage notes here's an example candidate a-line from an ice transaction: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the third field, "udp", is the protocol type, indicating that the candidate would use the udp transport protocol. example this code snippet examines the value of protocol to decide if it should look at the value of tcptype to see if it's a simultaneou...
RTCPeerConnection.addIceCandidate() - Web APIs
e() instead. the parameters for this form of addicecandidate() are described below, to aid in updating existing code. successcallback a function to be called when the ice candidate has been successfully added. this function receives no input parameters and doesn't return a value. failurecallback a function to be called if attempting to add the ice candidate fails. ...
...ut parameters and doesn't return a value. failurecallback a function to be called if attempting to add the ice candidate fails. receives as input a dom
exception object describing why failure occurred. return value a promise which is fulfilled when the candidate has been successfully added to the remote peer's description by the ice agent. the promise does not receive any input parameters.
exceptions when an error occurs while attempting to add the ice candidate, the promise returned by this method is rejected, returning one of the errors below as the name attribute in the specified dom
exception object passed to the rejection handler. typeerror the specified candidate's sdpmid and sdpmlineindex are both null. invalidstateerror the rtcpeerconnection currently has no remote peer establi...
RTCPeerConnection.createOffer() - Web APIs
ode to use the promise-based version of createoffer() instead. the parameters for this form of createoffer() are described below, to aid in updating existing code. successcallback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription object describing the newly-created offer. errorcallback an rtcpeerconnectionerrorcallback which will be passed a single dom
exception object explaining why the request to create an offer failed. options optional an optional rtcofferoptions dictionary providing options requested for the offer. return value a promise whose fulfillment handler will receive an object conforming to the rtcsessiondescriptioninit dictionary which contains the sdp describing the generated offer. that received offer should be delivered through the ...
...o create an offer failed. options optional an optional rtcofferoptions dictionary providing options requested for the offer. return value a promise whose fulfillment handler will receive an object conforming to the rtcsessiondescriptioninit dictionary which contains the sdp describing the generated offer. that received offer should be delivered through the signaling server to a remote peer.
exceptions these
exceptions are returned by rejecting the returned promise. your rejection handler should examine the received
exception to determine which occurred. invalidstateerror the rtcpeerconnection is closed. notreadableerror no certificate or set of certificates was provided for securing the connection, and createoffer() was unable to create a new one. since all webrtc connections are requi...
RTCPeerConnection.getStats() - Web APIs
ts(selector) parameters selector optional a mediastreamtrack for which to gather statistics. if this is null (the default value), statistics will be gathered for the entire rtcpeerconnection. return value a promise which resolves with an rtcstatsreport object providing connection statistics. the contents of the report depend on the selector as well as other details of the connection.
exceptions this method does not throw
exceptions; instead, it rejects the returned promise with one of the following errors: invalidaccesserror there is no rtcrtpsender or rtcrtpreceiver whose track matches the specified selector, or selector matches more than one sender or receiver. obsolete syntax previously, getstats() used success and failure callbacks to report the results to you, instead of u...
... gathered for the entire rtcpeerconnection. successcallback a callback function to call when the stats have been retrieved. the function receives as input a single parameter: an rtcstatsreport with the collected statistics. no output is expected from the function. failurecallback a function to call when an error occurs while attempting to collect statistics. the callback receives as input the
exception (a dom
exception object describing the error which occurred. no return value is expected from the callback. example this example creates a periodic function using setinterval() that collects statistics for an rtcpeerconnection every second, generating an html-formatted report and inserting it into a specific element in the dom. window.setinterval(function() { mypeerconnection.getstats(null).
RTCPeerConnection.setLocalDescription() - Web APIs
ting existing code. successcallback a javascript function which accepts no input parameters to be be called once the description has been successfully set. at that time, the offer can be sent to a remote peer via the signaling server. errorcallback a function matching the signature rtcpeerconnectionerrorcallback which gets called if the description can't be set. ...
...nature rtcpeerconnectionerrorcallback which gets called if the description can't be set. it is passed a single dom
exception object explaining why the request failed. this deprecated form of the method returns instantaneously without waiting for the actual setting to be done: in case of success, the successcallback will be called; in case of failure, the errorcallback will be called. deprecated
exceptions when using the deprecated callback-based version of setlocaldescription(), the following
exceptions may occur: invalidstateerror the connection's signalingstate is "closed", indicating that the connection is not currently open, so negotiation cannot take place. invalidsessiondescriptionerror the rtcsessiondescription specified by the sessiondescription parameter is invalid. examples...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
, in order of preference, each providing the parameters for one of the transceiver's supported codecs. if codecs is empty, the codec configurations are all returned to the user agent's defaults. note: any codecs not included in codecs will not be considered during the process of negotiating a connection. this lets you prevent the use of codecs you don't wish to use. return value undefined
exceptions invalidaccesserror the codecs list includes one or more codecs which are not supported by the transceiver. usage notes getting a list of supported codecs you can only include in the codecs list codecs which the transceiver actually supports. that means that either the associated rtcrtpsender or the rtcrtpreceiver needs to support every codec in the list. if any unsupported codecs are lis...
...one or more codecs which are not supported by the transceiver. usage notes getting a list of supported codecs you can only include in the codecs list codecs which the transceiver actually supports. that means that either the associated rtcrtpsender or the rtcrtpreceiver needs to support every codec in the list. if any unsupported codecs are listed, the browser will throw an invalidaccesserror
exception when you call this method. a good approach to setting codec preferences is to first get the list of codecs that are actually supported, then modify that list to match what you want. pass the altered list into setcodecpreferences() to specify your preferences. to determine which codecs are supported by the transceiver, call the sender's getcapabilities() and the receiver's getcapabilities() meth...
SVGAnimationElement - Web APIs
cause the href specifies an unknown element) the value returned is null. methods this interface also inherits methods from its parent, svgelement. svganimationelement.getstarttime() returns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. if there is no current interval, then a dom
exception with code invalid_state_err is thrown. svganimationelement.getcurrenttime() returns a float representing the current time in seconds relative to time zero for the given time container. svganimationelement.getsimpleduration() returns a float representing the number of seconds for the simple duration for this animation. if the simple duration is undefined (e.g., the end time is indefinite), the...
...ode invalid_state_err is thrown. svganimationelement.getcurrenttime() returns a float representing the current time in seconds relative to time zero for the given time container. svganimationelement.getsimpleduration() returns a float representing the number of seconds for the simple duration for this animation. if the simple duration is undefined (e.g., the end time is indefinite), then a dom
exception with code not_supported_err is raised. svganimationelement.beginelement() creates a begin instance time for the current time. the new instance time is added to the begin instance times list. the behavior of this method is equivalent to beginelementat(0). svganimationelement.beginelementat() creates a begin instance time for the current time plus the specified offset. the new instance ti...
SVGMatrix - Web APIs
warning: svg 2 replaced the svgmatrix interface by the more general dommatrix and dommatrixreadonly interfaces. ...
...ing matrix as svgmatrix. svgmatrix.flipy() post-multiplies the transformation [1 0 0 -1 0 0] and returns the resulting matrix as svgmatrix. svgmatrix.skewx() post-multiplies a skewx transformation on the current matrix and returns the resulting matrix as svgmatrix. svgmatrix.skewy() post-multiplies a skewy transformation on the current matrix and returns the resulting matrix as svgmatrix.
exceptions a dom
exception with the code no_modification_allowed_err is raised when attempting updating a read-only attribute or when the object itself is read-only. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgmatrix' in that specification. recommendation initial definition ...
SVGNumber - Web APIs
methods this interface doesn't provide any specific methods. ...
... methods this interface doesn't provide any specific methods. ...
SVGPreserveAspectRatio - Web APIs
svg preserveaspectratio interface the svgpreserveaspectratio interface corresponds to the preserveaspectratio attribute, which is available for some of svg's elements. an svgpreserveaspectratio object can be designated as read only, which means that attempts to modify the object will result in an
exception being thrown. interface overview also implement none methods none properties unsigned short align unsigned short meetorslice constants svg_preserveaspectratio_unknown = 0 svg_preserveaspectratio_none = 1 svg_preserveaspectratio_xminymin = 2 svg_preserveaspectratio_xmidymin = 3 svg_preserveaspectratio_xmaxymin = 4 svg_preserveaspectratio_xminymid = 5 svg_preserveaspectratio_xmidym...
...veaspectratio. properties name type description align unsigned short the type of the alignment value as specified by one of the svg_preserveaspectratio_* constants defined on this interface. meetorslice unsigned short the type of the meet-or-slice value as specified by one of the svg_meetorslice_* constants defined on this interface.
exceptions on setting: a dom
exception with code no_modification_allowed_err is raised on an attempt to change the value of an attribute on a read only object. methods the svgpreserveaspectratio interface do not provide any specific methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://gith...
SVGStyleElement - Web APIs
-anchor="middle" alignment-baseline="middle">svgstyleelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svgelement and implements properties from linkstyle. svgstyleelement.type a domstring corresponding to the type attribute of the given element. svg 1.1 defined that a dom
exception is raised with code no_modification_allowed_err on an attempt to change the value of a read-only attribute. this restriction was removed in svg 2. svgstyleelement.media a domstring corresponding to the media attribute of the given element. svg 1.1 defined that a dom
exception is raised with code no_modification_allowed_err on an attempt to change the value of a read-only attribute. this restr...
...this restriction was removed in svg 2. ...
SourceBuffer.abort() - Web APIs
example the spec description of abort() is somewhat confusing — consider for example step 1 of reset parser state. ...
... example the spec description of abort() is somewhat confusing — consider for example step 1 of reset parser state. ...
SourceBuffer.mode - Web APIs
utomatically for the segments that observe this order. the mode value is initially set when the sourcebuffer is created using mediasource.addsourcebuffer(). if timestamps already exist for the media segments, then the value will be set to segments; if they don't, then the value will be set to sequence. if you try to set the mode property value to segments when the initial value is sequence, an
exception will be thrown. the existing segment order must be maintained in sequence mode. you can, however, change the value from segments to sequence. it just means the play order will be fixed, and new timestamps generated to reflect this. this property cannot be changed during while the sourcebuffer is processing either an appendbuffer() or remove() call. syntax var mymode = sourcebuffer.mode; sourc...
...e maintained in sequence mode. you can, however, change the value from segments to sequence. it just means the play order will be fixed, and new timestamps generated to reflect this. this property cannot be changed during while the sourcebuffer is processing either an appendbuffer() or remove() call. syntax var mymode = sourcebuffer.mode; sourcebuffer.mode = 'sequence'; value a domstring.
exceptions the following
exceptions may be thrown when setting a new value for this property.
exception explanation invalidaccesserror an attempt was made to set the value to segments when the initial value is sequence. invalidstateerror the sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), the last media segment appe...
Storage Access API - Web APIs
ak embedded cross-origin content that requires access to its first-party storage. as an example, federated logins often require access to authentication cookies stored in first-party storage, and will require the user to sign in on each site separately (or completely break) if those cookies are not available. in the case of breakage, site owners have often encouraged users to add their site as an
exception or to disable the policy entirely. as a consequence, users who wish to continue to interact with embedded content are forced to greatly relax their blocking policy for resources loaded from all embedded origins and possibly across all websites. the storage access api is intended to solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a s...
...ding 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"> ... </iframe> the api is designed to limit the potential storage
exceptions to origins for which the user has shown an intent to interact. this is enforced through the following constraints: access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click. this also prevents embedded content on the page from spamming the browser or user with excessive access requests. origins that have never been inte...
WakeLockSentinel.release() - Web APIs
you should always listen for the onrelease event to check if a wake lock has been released. ...
...you should always listen for the onrelease event to check if a wake lock has been released. ...
Lighting a WebXR setting - Web APIs
le some of these are also useful in any other 3d setting, most are specific to virtual reality and, in some cases even more so, to augmented reality. since your scene is intended to represent a setting a person or their avatar can exist within, you should try to achieve some degree of consistency and realism in terms of the positioning and presentation of your light sources. obviously, there are
exceptions to this guideline, such as when your scene represents an otherworldly or alien setting, or when your goal is to create an unsettling visual effect. realism in light source placement when possible, you should try to make your virtual light sources correspond to objects that actually exists. if you have a virtual room that needs overhead lighting, have a model of a ceiling lamp at the location o...
...en your scene represents an otherworldly or alien setting, or when your goal is to create an unsettling visual effect. realism in light source placement when possible, you should try to make your virtual light sources correspond to objects that actually exists. if you have a virtual room that needs overhead lighting, have a model of a ceiling lamp at the location of your light source. there are
exceptions, such as the ambient lighting that simply adds a baseline amount of lighting to your setting, and the sun, which is a directional light (that is, a light source where every light ray is parallel, coming from somewhere in the sky and ending somewhere within your scene). try to place light sources in realistic locations for the setting and the mood you're trying to create. a scene intended to fee...
Using the Web Storage API - Web APIs
ability note: this api is available in current versions of all major browsers. testing for availability is necessary only if you must support very old browsers, such as internet explorer 6 or 7, or in the limited circumstances described below. browsers that support localstorage have a property on the window object named localstorage. however, just asserting that that property exists may throw
exceptions. if the localstorage object does exist, there is still no guarantee that the localstorage api is actually available, as various browsers offer settings that disable localstorage. so a browser may support localstorage, but not make it available to the scripts on the page. for example, safari browser in private browsing mode gives us an empty localstorage object with a quota of zero, effectively ...
...ction should take these scenarios into account. ...
Web Workers API - Web APIs
global context that is different from the current window. this context is represented by either a dedicatedworkerglobalscope object (in the case of dedicated workers - workers that are utilized by a single script), or a sharedworkerglobalscope (in the case of shared workers - workers that are shared between multiple scripts). you can run whatever code you like inside the worker thread, with some
exceptions. for example, you can't directly manipulate the dom from inside a worker, or use some default methods and properties of the window object. but you can use a large number of items available under window, including websockets, and data storage mechanisms like indexeddb. see functions and classes available to workers for more details. data is sent between workers and the main thread via a system ...
...heir messages using the postmessage() method, and respond to messages via the onmessage event handler (the message is contained within the message event's data property). the data is copied rather than shared. workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page. in addition, workers may use xmlhttprequest for network i/o, with the
exception that the responsexml and channel attributes on xmlhttprequest always return null. in addition to dedicated workers, there are other types of worker: shared workers are workers that can be utilized by multiple scripts running in different windows, iframes, etc., as long as they are in the same domain as the worker. they are a little more complex than dedicated workers — scripts must communic...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
can only call it from a browser extension or from a xulrunner application. the channel property becomes available only after the request is sent and the connection was established, that is, on readystate loaded, interactive or completed. by setting the mozbackgroundrequest property of the request object and modifying the example appropriately, you can create your own alert dialog to handle ssl
exceptions in your firefox extension or xulrunner application. // adapted from the patch for moztcpsocket error reporting (bug 861196). const {cc,ci} = require("chrome"); function createtcperrorfromfailedxhr(xhr) { let status = xhr.channel.queryinterface(ci.nsirequest).status; let errtype; if ((status & 0xff0000) === 0x5a0000) { // security module const nsinsserrorsservice = ci.nsinsserrorsse...
... = ci.nsinsserrorsservice; let nsserrorsservice = cc['@mozilla.org/nss_errors_service;1'].getservice(nsinsserrorsservice); let errorclass; // geterrorclass will throw a generic ns_error_failure if the error code is // somehow not in the set of covered errors. ...
XMLSerializer.serializeToString() - Web APIs
the xmlserializer method serializetostring() constructs a string representing the specified dom tree in xml form. syntax xmlstring = anxmlserializer.serializetostring(rootnode); parameters rootnode the node to use as the root of the dom tree or subtree for which to construct an xml representation. return value a domstring containing the xml representation of the specified dom tree.
exceptions typeerror the specified rootnode is not a compatible node type. the root node must be either node or attr. invalidstateerror the tree could not be successfully serialized, probably due to issues with the content's compatibility with xml serialization. syntaxerror a serialization of html was requested but could not succeed due to the content not being well-formed. usage notes compatible n...
...node—and all of its descendants—must be compatible with the xml serialization algorithm. the root node itself must be either a node or attr object. the following types are also permitted as descendants of the root node, in addition to node and attr: documenttype document documentfragment element comment text processinginstruction attr if any other type is encountered, a typeerror
exception is thrown. notes on the resulting xml there are some things worth noting about the xml output by serializetostring(): for xml serializations, element and attr nodes are always serialized with their namespaceuri intact. this may mean that a previously-specified prefix or default namespace may be dropped or altered. the resulting xml is compatible with the html parser. elements in the html n...
XRSystem: isSessionSupported() - Web APIs
the xrsystem method issessionsupported() returns a promise which resolves to true if the specified webxr session mode is supported by the user's webxr device. otherwise, the promise resolves with false. if the no devices are available or the browser doesn't have permission to use the xr device, the promise is rejected with an appropriate dom
exception. syntax var issupportedpromise = xr.issessionsupported(xrsessionmode) parameters xrsessionmode a domstring specifying the webxr session mode for which support is to be checked. this string must be one of inline (to present the webxr content inline within the context of an html document) or immersive-vr for a fully-immersive virtual experience. return value a promise that resolves to true if the specified session mode is supported; otherwise...
...xrsessionmode a domstring specifying the webxr session mode for which support is to be checked. this string must be one of inline (to present the webxr content inline within the context of an html document) or immersive-vr for a fully-immersive virtual experience. return value a promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false.
exceptions rather than throwing true
exceptions, issessionsupported() rejects the returned promise, passing to the rejection handler a dom
exception whose name is one of the following strings. securityerror the document's origin does not have permission to use the xr-spatial-tracking feature policy. examples in this example, we see issessionsupported() used to detect whether or not the device suppor...
Cognitive accessibility - Accessibility
ity, and information and functionality cannot be achieved in another way that would conform. this includes animated gifs, if the gif animates for more than 5 seconds. additional timing criteria to consider are: people who have cognitive or language limitations may need more time to read and to understand. for improved usability remove any time limit. timed content should also be avoided, with
exceptions for non-interactive synchronized media and real-time events. people with attention deficit disorders should be able to focus on content without distractions. the user should be able to postpone or suppress interruptions, except situations involving altering a person to an emergency. this provides access to people with cognitive disabilities by enabling them to focus on the main purpose of the c...
... for example, saving the state of a questionnaire. make sure to save data in such a way that it can be modified after a user re-authenticates. before re-authenticating, encode the data as hidden or encrypted. providing warnings about inactivity that could result in data loss. when a timeout is used, tell people exactly how much time will cause the session to time out and result in lost data. the
exception to this is preserving data for more than 20 hours when no actions are taken. navigation guideline 2.4 states "provide ways to help users navigate, find content, and determine where they are," and provides 10 guidelines to ensure the site is navigable and content is findable: include a <title> make sure to include a <title> for the document, as titles provide a quick and easy to refere...
Getting Started - Developer guides
ent get parameter, like a timestamp or random number (see bypassing the cache) note 3: if the httprequest variable is used globally, competing functions calling makerequest() can overwrite each other, causing a race condition. declaring the httprequest variable local to a closure containing the ajax functions avoids this. in the event of a communication error (such as the server going down), an
exception will be thrown in the onreadystatechange method when accessing the response status. to mitigate this problem, you could wrap your if...then statement in a try...catch: function alertcontents() { try { if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { alert(httprequest.responsetext); } else { alert('there was a problem with t...
...e response status. to mitigate this problem, you could wrap your if...then statement in a try...catch: function alertcontents() { try { if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { alert(httprequest.responsetext); } else { alert('there was a problem with the request.'); } } } catch( e ) { alert('caught
exception: ' + e.description); } } step 4 – working with the xml response in the previous example, after receiving the response to the http request we used the request object's responsetext property , which contained the contents of the test.html file. now let's try the responsexml property. first off, let's create a valid xml document that we'll request later on. the document (test.xml) contains t...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
is step is not included. step="any" will never throw this error. type validitystate.typemismatch occurs when the value is not of the correct type, for example a email does not contain an @ or a url doesn't contain a protocol. if a form control doesn't have the required attribute, no value, or an empty string, is not invalid. even if the above attributes are present, with the
exception of required, and empty string will not lead to an error. we can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted. in addition to the errors described in the table above, the validitystate interface contains the badinput, valid, and customerror boolean readonly properties. the...
... if there is an error, supporting browsers will both alert the user and prevent the form from being submitted. a word of caution: if a custom error is set to a truthy value (anything other than the empty string or null), the form will be be prevented from being submitted. if there is no custom error message, and no...
MIME types (IANA media types) - HTTP
main type is text, the optional charset parameter can be used to specify the character set used for the characters in the data. if no charset is specified, the default is ascii (us-ascii) unless overridden by the user agent's settings. to specify a utf-8 text file, the mime type text/plain;charset=utf-8 is used. mime types are case-insensitive but are traditionally written in lowercase, with the
exception of parameter values, whose case may or may not have specific meaning. types there are two classes of type: discrete and multipart. discrete types are types which represent a single file or medium, such as a single text or music file, or a single video. a multipart type is one which represents a document that's comprised of multiple component parts, each of which may have its own individual mime...
...ary documents without a specific or known subtype, application/octet-stream should be used. multipart types multipart types indicate a category of document broken into pieces, often with different mime types; they can also be used — especially in email scenarios — to represent multiple, separate files which are all part of the same transaction. they represent a composite document. with the
exception of multipart/form-data, used in the post method of html forms, and multipart/byteranges, used with 206 partial content to send part of a document, http doesn't handle multipart documents in a special way: the message is transmitted to the browser (which will likely show a "save as" window if it doesn't know how to display the document). there are two multipart types: message list at iana a m...
Content-Security-Policy - HTTP
this helps guard against cross-site scripting attacks (xss). for more information, see the introductory article on content security policy (csp). header type response header forbidden header name no syntax content-security-policy: <policy-directive>; <policy-directive> where <policy-directive> consists of: <directive> <value> with no internal punctuation. ...
...ve is intended for web sites with large numbers of insecure legacy urls that need to be rewritten. csp in workers workers are in general not governed by the content security policy of the document (or parent worker) that created them. to specify a content security policy for the worker, set a content-security-policy response header for the request which requested the worker script itself. the
exception to this is if the worker script's origin is a globally unique identifier (for example, if its url has a scheme of data or blob). in this case, the worker does inherit the content security policy of the document or worker that created it. multiple content security policies the csp mechanism allows multiple policies being specified for a resource, including via the content-security-policy header,...
HTTP response status codes - HTTP
n of a proxy. 306 unused this response code is no longer used; it is just reserved. it was used in a previous version of the http/1.1 specification. 307 temporary redirect the server sends this response to direct the client to get the requested resource at another uri with same method that was used in the prior request. ...
... client error responses 400 bad request the server could not understand the request due to invalid syntax. 401 unauthorized although the http standard specifies "unauthorized", semantically this response means "unauthenticated". ...
Equality comparisons and sameness - JavaScript
an attempt is made to mutate an immutable property: // add an immutable negative_zero property to the number constructor. object.defineproperty(number, 'negative_zero', { value: -0, writable: false, configurable: false, enumerable: false }); function attemptmutation(v) { object.defineproperty(number, 'negative_zero', { value: v }); } object.defineproperty will throw an
exception when attempting to change an immutable property, but it does nothing if no actual change is requested. if v is -0, no change has been requested, and no error will be thrown. internally, when an immutable property is redefined, the newly-specified value is compared against the current value using same-value equality. same-value equality is provided by the object.is method. same-value-zero equali...
...nd readable. hint: read the strict equality algorithm first.) es5 also describes, in section 9.12, the samevalue algorithm for use internally by the js engine. it's largely the same as the strict equality algorithm, except that 11.9.6.4 and 9.12.4 differ in handling numbers. es2015 simply proposes to expose this algorithm through object.is. we can see that with double and triple equals, with the
exception of doing a type check upfront in 11.9.6.1, the strict equality algorithm is a subset of the abstract equality algorithm, because 11.9.6.2–7 correspond to 11.9.3.1.a–f. a model for understanding equality comparisons? prior to es2015, you might have said of double equals and triple equals that one is an "enhanced" version of the other. for example, someone might say that double equals is an e...
Expressions and operators - JavaScript
er the comparison is true. the operands can be numerical, string, logical, or object values. strings are compared based on standard lexicographical ordering, using unicode values. in most cases, if the two operands are not of the same type, javascript attempts to convert them to an appropriate type for the comparison. this behavior generally results in comparing the operands numerically. the sole
exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. these operators do not attempt to convert the operands to compatible types before checking equality. the following table describes the comparison operators in terms of this sample code: var var1 = 3; var var2 = 4; comparison operators operator descrip...
...returns true instanceof the instanceof operator returns true if the specified object is of the specified object type. the syntax is: objectname instanceof objecttype where objectname is the name of the object to compare to objecttype, and objecttype is an object type, such as date or array. use instanceof when you need to confirm the type of an object at runtime. for example, when catching
exceptions, you can branch to different
exception-handling code depending on the type of
exception thrown. for example, the following code uses instanceof to determine whether theday is a date object. because theday is a date object, the statements in the if statement execute. var theday = new date(1995, 12, 17); if (theday instanceof date) { // statements to execute } operator precedence the preced...
Grammar and types - JavaScript
global variable. it also generates a strict javascript warning. undeclared global variables can often lead to unexpected behavior. thus, it is discouraged to use undeclared global variables. evaluating variables a variable declared using the var or let statement with no assigned value specified has the value of undefined. ...
...e immediate if statement block. if (true) { var x = 5; } console.log(x); // x is 5 this behavior changes when using the let declaration (introduced in ecmascript 2015). if (true) { let y = 5; } console.log(y); // referenceerror: y is not defined variable hoisting another unusual thing about variables in javascript is that you can refer to a variable declared later, without getting an
exception. this concept is known as hoisting. variables in javascript are, in a sense, "hoisted" (or "lifted") to the top of the function or statement. however, variables that are hoisted return a value of undefined. so even if you declare and initialize after you use or refer to this variable, it still returns undefined. /** * example 1 */ console.log(x === undefined); // true var x = 3; /** * examp...
Using Promises - JavaScript
error caused a rejection. error propagation you might recall seeing failurecallback three times in the pyramid of doom earlier, compared to only once at the end of the promise chain: dosomething() .then(result => dosomethingelse(result)) .then(newresult => dothirdthing(newresult)) .then(finalresult => console.log(`got the final result: ${finalresult}`)) .catch(failurecallback); if there's an
exception, the browser will look down the chain for .catch() handlers or onrejected. this is very much modeled after how synchronous code works: try { const result = syncdosomething(); const newresult = syncdosomethingelse(result); const finalresult = syncdothirdthing(newresult); console.log(`got the final result: ${finalresult}`); } catch(error) { failurecallback(error); } this symmetry with ...
...se(result); const finalresult = await dothirdthing(newresult); console.log(`got the final result: ${finalresult}`); } catch(error) { failurecallback(error); } } it builds on promises, e.g. dosomething() is the same function as before. you can read more about the syntax here. promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown
exceptions and programming errors. this is essential for functional composition of asynchronous operations. promise rejection events whenever a promise is rejected, one of two events is sent to the global scope (generally, this is either the window or, if being used in a web worker, it's the worker or other worker-based interface). the two events are: rejectionhandled sent when a promise is rejected,...
TypeError: can't access dead object - JavaScript
message typeerror: can't access dead object error type typeerror what went wrong? to improve in memory usage and to prevent memory leaks, firefox disallows add-ons to keep strong references to dom objects after their parent document has been destroyed. a dead object, is holding a strong (keep alive) reference to a dom element that persists even after it was destroyed in the dom. ...
... try { string(window); } catch (e) { console.log("window is likely dead"); } ...
TypeError: "x" is not a constructor - JavaScript
message typeerror: object doesn't support this action (edge) typeerror: "x" is not a constructor typeerror: math is not a constructor typeerror: json is not a constructor typeerror: symbol is not a constructor typeerror: reflect is not a constructor typeerror: intl is not a constructor typeerror: atomics is not a constructor error type typeerror what went wrong? there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. see constructor or the new operator for more information on what a constructor is. ...
...his.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. ...
Function.prototype.apply() - JavaScript
y kind of object which is array-like. in practice, this means it's going to have a length property, and integer ("index") properties in the range (0..length - 1). for example, you could use a nodelist, or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }. note: many older browsers—including chrome <17 and internet explorer <9—don't accept array-like objects, and will throw an
exception. examples using apply to append an array to another you can use push to append an element to an array. and, because push accepts a variable number of arguments, you can also push multiple elements at once. but, if you pass an array to push, it will actually add that array as a single element, instead of adding the elements individually. so you end up with an array inside an array. what if t...
...eeding the javascript engine's argument length limit. the consequences of applying a function with too many arguments (that is, more than tens of thousands of arguments) varies across engines. (the javascriptcore engine has hard-coded argument limit of 65536. this is because the limit (and indeed, even the nature of any excessively-large-stack behavior) is unspecified. some engines will throw an
exception. more perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. to illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array. if your value array might grow i...
Object.assign() - JavaScript
ole.log(copy); // { baz: 3 } primitives will be wrapped to objects const v1 = 'abc'; const v2 = true; const v3 = 10; const v4 = symbol('foo'); const obj = object.assign({}, v1, null, v2, undefined, v3, v4); // primitives will be wrapped, null and undefined will be ignored. // note, only string wrappers can have own enumerable properties. ...
...string wrappers can have own enumerable properties. console.log(obj); // { "0": "a", "1": "b", "2": "c" }
exceptions will interrupt the ongoing copying task const target = object.defineproperty({}, 'foo', { value: 1, writable: false }); // target.foo is a read-only property object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 }); // typeerror: "foo" is read-only // the
exception is thrown when assigning target.foo console.log(target.bar); // 2, the first source was copied successfully. console.log(target.foo2); // 3, the first property of the second source was copied successfully. console.log(target.foo); // 1,
exception is thrown here. console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied. console.log(target.baz); // undefined, ...
Object.prototype.constructor - JavaScript
the constructor property returns a reference to the object constructor function that created the instance object. note that the value of this property is a reference to the function itself, not a string containing the function's name. the value is only read-only for primitive values such as 1, true, and "test". description all objects (with the
exception of objects created with object.create(null)) will have a constructor property. objects created without the explicit use of a constructor function (such as object- and array-literals) will have a constructor property that points to the fundamental object constructor type for that object. let o = {} o.constructor === object // true let o = new object o.constructor === object // true let a = [] a.constructor === array // true let a = new array...
...create itself. function parent() { /* ... */ } 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. to avoid this, just assign the necessary constructor you are going to use. function parent() { /* ... */ } function createdconstructor() { /* ... */ } createdconstructor.prototype = object.create(parent.prototype) createdconstructor.prototype.constructor = createdconstructor // sets the correct constructor for future use createdconstructor.
handler.setPrototypeOf() - JavaScript
totypeof() reflect.setprototypeof() invariants if the following invariants are violated, the proxy will throw a typeerror: if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target). examples if you want to disallow setting a new prototype for your object, your handler's setprototypeof() method can either return false, or it can throw an
exception. approach 1: returning false this approach means that any mutating operation that throws an
exception on failure to mutate, must create the
exception itself. for example, object.setprototypeof() will create and throw a typeerror itself. if the mutation is performed by an operation that doesn't ordinarily throw in case of failure, such as reflect.setprototypeof(), no
exception will be thrown. ...
...failure, such as reflect.setprototypeof(), no
exception will be thrown. const handlerreturnsfalse = { setprototypeof(target, newproto) { return false; } }; const newproto = {}, target = {}; const p1 = new proxy(target, handlerreturnsfalse); object.setprototypeof(p1, newproto); // throws a typeerror reflect.setprototypeof(p1, newproto); // returns false approach 2: throwing an
exception the latter approach will cause any operation that attempts to mutate, to throw. this approach is best if you want even non-throwing operations to throw on failure, or you want to throw a custom
exception value. const handlerthrows = { setprototypeof(target, newproto) { throw new error('custom error'); } }; const newproto = {}, target = {}; const p2 = new proxy(target, handler...
Proxy - JavaScript
this example uses the construct and apply handlers. function extend(sup, base) { var descriptor = object.getownpropertydescriptor( base.prototype, 'constructor' ); base.prototype = object.create(sup.prototype); var handler = { constru...
...this example uses the construct and apply handlers. function extend(sup, base) { var descriptor = object.getownpropertydescriptor( base.prototype, 'constructor' ); base.prototype = object.create(sup.prototype); var handler = { construct: function(target, args) { var obj = obj...
RangeError() constructor - JavaScript
the rangeerror() constructor creates an error when a value is not in the set or range of allowed values. syntax new rangeerror([message[, filename[, linenumber]]]) parameters message optional human-readable description of the error. ...
... the rangeerror() constructor creates an error when a value is not in the set or range of allowed values. syntax new rangeerror([message[, filename[, linenumber]]]) parameters message optional human-readable description of the error. ...
SyntaxError() constructor - JavaScript
the syntaxerror constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ...
...ctor creates a new error object that represents an error when trying to interpret syntactically invalid code. ...
TypeError() constructor - JavaScript
the typeerror() constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. syntax new typeerror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error filename optional optional. ...
...erformed, typically (but not exclusively) when a value is not of the expected type. syntax new typeerror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error filename optional optional. the name of the file containing the code that caused the
exception linenumber optional optional. ...
TypedArray.prototype.set() - JavaScript
lease clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.set(array[, offset]) typedarray.set(typedarray[, offset]) parameters array the array from which to copy values. all values from the source array are copied into the target array, unless the length of the source array plus the offset exceeds the length of the target array, in which case an
exception is thrown. typedarray if the source array is a typed array, the two arrays may share the same underlying arraybuffer; the javascript engine will intelligently copy the source range of the buffer to the destination range. offset optional the offset into the target array at which to begin writing values from the source array. if this value is omitted, 0 is assumed (that is, the source array wil...
...the two arrays may share the same underlying arraybuffer; the javascript engine will intelligently copy the source range of the buffer to the destination range. offset optional the offset into the target array at which to begin writing values from the source array. if this value is omitted, 0 is assumed (that is, the source array will overwrite values in the target array starting at index 0).
exceptions a rangeerror, if the offset is set such as it would store beyond the end of the typed array. examples using set() var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1, 2, 3], 3); console.log(uint8); // uint8array [ 0, 0, 0, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.set' in ...
WebAssembly.instantiate() - JavaScript
e or else a webassembly.linkerror is thrown. return value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module. this module can be instantiated again, shared via postmessage() or cached in indexeddb. instance: a webassembly.instance object that contains all the exported webassembly functions.
exceptions if either of the parameters are not of the correct type or structure, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. secondary overload — taking a module object instance promise<webassembly.instance> webassembly.instantiate(module, importobject)...
...odule the webassembly.module object to be instantiated. importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of module or else a webassembly.linkerror is thrown. return value a promise that resolves to an webassembly.instance object.
exceptions if either of the parameters are not of the correct type or structure, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. examples note: you'll probably want to use webassembly.instantiatestreaming() in most cases, as it is more efficient than instanti...
Optional chaining (?.) - JavaScript
optional chaining when attempting to call a method which may not exist. this can be helpful, for example, when using an api in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an
exception if the method isn't found: let result = someinterface.custommethod?.(); note: if there is a property with such a name and which is not a function, using ?. will still raise a typeerror
exception (someinterface.custommethod is not a function). note: if someinterface itself is null or undefined, a typeerror
exception will still be raised (someinterface is null). if you expect that someinterfa...
...2019 function dosomething(oncontent, onerror) { try { // ... do something with the data } catch (err) { if (onerror) { // testing if onerror really exists onerror(err.message); } } } // using optional chaining with function calls function dosomething(oncontent, onerror) { try { // ... ...
delete operator - JavaScript
pression where expression should evaluate to a property reference, e.g.: delete object.property delete object['property'] parameters object the name of an object, or an expression evaluating to an object. property the property to delete. return value true for all cases except when the property is an own non-configurable property, in which case, false is returned in non-strict mode.
exceptions throws typeerror in strict mode if the property is an own non-configurable property. description unlike what common belief suggests (perhaps due to other programming languages like delete in c++), the delete operator has nothing to do with directly freeing memory. memory management is done indirectly via breaking references. see the memory management page for more details. the delete operato...
...bal property using: object.getownpropertydescriptor(window, 'nameother'); // output: object {value: "xyz", // writable: true, // enumerable: true, // configurable: false} // since "nameother" is added using with the // var keyword, it is marked as "non-configurable" delete nameother; // return false in strict mode, this would have raised an
exception. strict vs. non-strict mode when in strict mode, if delete is used on a direct reference to a variable, a function argument or a function name, it will throw a syntaxerror. therefore, to avoid syntax errors in strict mode, you must use the delete operator in the form of delete object.property or delete object['property']. object.defineproperty(globalthis, 'variable1', { value: 10, configurable...
typeof - JavaScript
ted as a type tag and a value. the type tag for objects was 0. null was represented as the null pointer (0x00 in most platforms). consequently, null had 0 as type tag, hence the "object" typeof return value. (reference) a fix was proposed for ecmascript (via an opt-in), but was rejected. it would have resulted in typeof null === 'null'. using new operator // all constructor functions, with the
exception of the function constructor, will always be typeof 'object' let str = new string('string'); let num = new number(100); typeof str; // it will return 'object' typeof num; // it will return 'object' let func = new function(); typeof func; // it will return 'function' need for parentheses in syntax // parentheses can be used for determining the data type of expressions. let idata = 99; typeof...
...oped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed. typeof undeclaredvariable === 'undefined'; typeof newletvariable; // referenceerror typeof newconstvariable; // referenceerror typeof newclass; // referenceerror let newletvariable; const newconstvariable = 'hello'; class newclass{};
exceptions all current browsers expose a non-standard host object document.all with type undefined. typeof document.all === 'undefined'; although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. the case of document.all having type 'undefined' is classified in the web standards as a "willful violation" of the...
<mstyle> - MathML
attributes dir overall directionality of formulas. possible values are either ltr (left to right) or rtl (right to left). decimalpoint this attribute is specifying the character for the alignment point within <mstack> and <mtable> columns, if the decimalpoint value is used to specify the alignment. ...
...ends on the multiplier specified in scriptsizemultiplier. scriptminsize specifies a minimum font size allowed due to changes in scriptlevel. the default value is 8pt. scriptsizemultiplier specifies the multiplier to be used to adjust font size due to changes in scriptlevel. the default value is 0.71. the <mstyle> element accepts all attributes of all presentation elements with the following
exceptions: height, depth or width do not apply to <mglyph>, <mpadded> or <mtable>. rowalign, columnalign, or groupalign do not apply to <mtr>, <mlabeledtr>, <mtd> or <maligngroup>. lspace or voffset do not apply to <mpadded>. fontfamily does not apply to <mglyph>. align does not apply to <mtable> or <mstack>. index cannot be set on <mstyle>. src and alt on <mglyph> cannot be set on <mstyle>. act...
Web audio codec guide - Web media technologies
cations. unless there's a specific need for lossless compression, or the network bandwidth is guaranteed to be high enough to support it, a lossy compression scheme is a good choice. which one you choose depends on browser compatibility and the availability of any special features you may need the codec to support. usually the latency is not particularly important when streaming music. possible
exceptions include looped music, where you need music to be able to play back uninterrupted over and over, or when you need to be able to play songs back to back with no gap between them. this can be particularly important for classical music, theatrical soundtracks, and for background music during gameplay. for general music playback, the three most likely candidates are mp3, aac, and vorbis. aac in a...
...n an audio layer iii track. if you need to minimize latency during music playback, you should strongly consider opus, which has the lowest range of latencies of the general-purpose codecs (5 ms to 66.5 ms, compared to at least 100 ms for the others). note: compatibility information described here is generally correct as of the time this article was written; however, there may be caveats and
exceptions. be sure to refer to the compatibility tables before committing to a given media format. based on this, aac is likely your best choice if you can only support one audio format. of course, if you can provide multiple formats (for example, by using the <source> element within your <audio> and <video> elements), you can avoid many or all of those
exceptions. example: music for download music be...
Same-origin policy - Web security
e these types of urls do not contain information about an origin server. for example, about:blank is often used as a url of new, empty popup windows into which the parent script writes content (e.g. via the window.open() mechanism). if this popup also contains javascript, that script would inherit the same origin as the script that created it. data: urls get a new, empty, security context.
exceptions in internet explorer internet explorer has two major
exceptions to the same-origin policy: trust zones if both domains are in the highly trusted zone (e.g. corporate intranet domains), then the same-origin limitations are not applied. port ie doesn't include port into same-origin checks. therefore, https://company.com:81/index.html and https://company.com/index.html are considered the sam...
... changing origin a page may change its own origin, with some limitations. a script can set the value of document.domain to its current domain or a superdomain of its current domain. if set to a superdomain of the current domain, the shorter superdomain is used for same-origin checks. ...
self - Archive of obsolete content
lf.options.a); port you can use port to receive messages from, and send messages to, the main add-on code. see the documentation for port. methods the self object has four methods, which enable the content script to send messages to, and receive messages from, the main add-on code. this is an older api than the api provided by port, and for most purposes the port api is a better choice. the
exception is the context-menu module, which still uses postmessage. postmessage() send a message from a content script to a listener in the main add-on code: self.postmessage(contentscriptmessage); this takes a single parameter, the message payload, which may be any json-serializable value. on() start listening to messages from the main add-on code: self.on("message", function(addonmessage) { // ...
Content Scripts - Archive of obsolete content
stmessage api before the port object was added, add-on code and content scripts communicated using a different api: the content script called self.postmessage() to send and self.on() to receive the add-on script called worker.postmessage() to send and worker.on()to receive the api is still available and documented, but there's no reason to use it instead of the port api described here. the
exception is the context-menu module, which still uses postmessage. content script to content script content scripts can only communicate with each other directly if they have been loaded into the same context. for example, if a single call to tab.attach() attaches two content scripts, then they can see each other directly, just as page scripts loaded by the same page can. but if you call tab.attach() tw...
Module structure of the SDK - Archive of obsolete content
ame way it would load a local module. for example, to load from main: // main.js code var geo = require("./dependencies/geolocation"); freezing the sdk freezes the exports object returned by require. so a if you import a module using require, you can't change the properties of the object returned: self = require("sdk/self"); // attempting to define a new property // will fail, or throw an
exception in strict mode self.foo = 1; // attempting to modify an existing property // will fail, or throw an
exception in strict mode self.data = "foo"; using modules from outside the add-on sdk you can use commonjs modules outside the add-on sdk, in any environment where you can use components.utils.import. just call the following: const { require } = cu.import("resource://gre/modules/commonjs/toolki...
request - Archive of obsolete content
es the request, the request object emits a "complete" event. registered event listeners are passed a response object. each request object is designed to be used once. attempts to reuse them will throw an error. since the request is not being made by any particular website, requests made here are not subject to the same-domain restriction that requests made in web pages are subject to. with the
exception of response, all of a request object's properties correspond with the options in the constructor. each can be set by simply performing an assignment. however, keep in mind that the same validation rules that apply to options in the constructor will apply during assignment. thus, each can throw if given an invalid value. the example below shows how to use request to get the most recent tweet from...
event/core - Archive of obsolete content
an event listener that is called only once: the next time an event of the specified type is emitted on the given event target. parameters target : object event target object. type : string the type of event. listener : function the listener function that processes the event. emit(target, type, message, arguments) execute each of the listeners in order with the supplied arguments. all the
exceptions that are thrown by listeners during the emit are caught and can be handled by listeners of 'error' event. thrown
exceptions are passed as an argument to an 'error' event listener. if no 'error' listener is registered
exception will be logged into an error console. parameters target : object event target object. type : string the type of event. message : object|number|string|boolean first ...
event/target - Archive of obsolete content
: let { emit } = require('sdk/event/core'); target.on('message', function onmessage(message) { console.log('listener triggered'); target.on('message', function() { console.log('nested listener triggered'); }); }); emit(target, 'message'); // info: 'listener triggered' emit(target, 'message'); // info: 'listener triggered' // info: 'nested listener triggered'
exceptions in the listeners can be handled via 'error' event listeners: target.on('boom', function() { throw error('boom!'); }); target.once('error', function(error) { console.log('caught an error: ' + error.message); }); emit(target, 'boom'); // info: caught an error: boom! if there is no listener registered for error event or if it also throws
exception then such
exceptions are logged into a consol...
io/file - Archive of obsolete content
de. if "b" is not present or mode is not given, the file contents will be returned in text mode. returns string : a string containing the file's entire contents. remove(path) removes a file from the file system. to remove directories, use rmdir. parameters path : string the path of the file to remove. rmdir(path) removes a directory from the file system. if the directory is not empty, an
exception is thrown. parameters path : string the path of the directory to remove. isfile(path) returns true only if this path specifies a file. const fileio = require("sdk/io/file"); let path = "/users/work/"; let list = fileio.list(path); for (i = 0; i < list.length; i++) { let item = fileio.join(path, list[i]); if (fileio.isfile(item)) { console.log(item + " is a file"); } else { ...
loader/sandbox - Archive of obsolete content
to all the xpcom components. optionally the sandbox function can be passed a second argument (see sandbox documentation on mdn for details). evaluate code module provides evaluate function that lets you execute code in the given sandbox: evaluate(scope, 'var a = 5;'); evaluate(scope, 'a + 2;'); //=> 7 more details about evaluated script may be passed via optional arguments that may improve
exception reporting: // evaluate code as if it was loaded from 'http://foo.com/bar.js' and // start from 2nd line. evaluate(scope, 'a ++', 'http://foo.com/bar.js', 2); version of javascript can be also specified via an optional argument: evaluate(scope, 'let b = 2;', 'bar.js', 1, '1.5'); // throws cause `let` is not defined in js 1.5. load scripts this module provides a limited api for loading scripts...
system/unload - Archive of obsolete content
nsures that this wrapper method is called when the object's module is unloaded. therefore, when you register an object with ensure(), you can call its destructor method yourself, you can let it happen for you, or you can do both. the destructor will be called with a single argument describing the reason for the unload; see when(). if object does not have the expected destructor method, then an
exception is thrown when ensure() is called. parameters object : object an object that defines a destructor method. name : string optional name of the destructor method. default is unload. when(callback) registers a function to be called when the module is unloaded. parameters callback : function a function that will be called when the module is unloaded. it is called with a single argument, one ...
system/xul-app - Archive of obsolete content
for more information, see the mdn documentation. globals functions is(name) checks whether the host application is the given application. parameters name : string a host application name. returns boolean : true if the host application is name and false otherwise. isoneof(names) checks whether the host application is one of the given applications. parameters names : array an array of host application names. ...
ui/button/action - Archive of obsolete content
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(). destroying buttons when you've finished with a button, destroy it by calling its destroy() method. after that, any attempts to access any of its properties or to call any of its methods will throw
exceptions. globals constructors actionbutton(options) creates an action button. parameters options : object required options: name type id string the button's id. this is used internally to keep track of this button. the id must be unique within your add-on. label string the button's human-readable label. when the button is in the to...
ui/button/toggle - Archive of obsolete content
window', null); // now that the state hierarchy is clean, set the // tab state for the current tab let { checked } = this.state('tab'); this.state('tab', {checked: !checked}); } }); destroying buttons when you've finished with a button, destroy it by calling its destroy() method. after that, any attempts to access any of its properties or to call any of its methods will throw
exceptions. globals constructors togglebutton(options) creates a toggle button. parameters options : object required options: name type id string the button's id. this is used internally to keep track of this button. the id must be unique within your add-on. label string the button's human-readable label. when the button is in the too...
util/match-pattern - Archive of obsolete content
the regular expression is subject to restrictions based on those applied to the html5 pattern attribute. in particular: the pattern must match the entire value, not just any subset. for example, the pattern /moz.*/ will not match the url http://mozilla.org. the expression is compiled with the global, ignorecase, and multiline flags disabled. the matchpattern constructor will throw an
exception if you try to set any of these flags. example pattern example matching urls example non-matching urls /.*moz.*/ http://foo.mozilla.org/ http://mozilla.org https://mozilla.org http://foo.com/mozilla http://hemozoon.org mozscheme://foo.org http://foo.org /https:\/\/www\.moz.*/ https://www.mozilla.org https://www.mozzarella.com ...
Unit Testing - Archive of obsolete content
which is an assert object. assert is supplied by the test/assert module and implements the commonjs unit testing specification. the first two functions call atob() and btoa() and use assert.ok() to check that the output is as expected. the second function tests the module's error-handling code by passing an empty string into atob() and using assert.throws() to check that the expected
exception is raised. at this point your add-on ought to look like this: /base64 /data icon-16.png package.json readme.md index.js base64.js /test test-base64.js now execute jpm --verbose test from the add-on's root directory. you should see something like this: console.info: jpm-utest: executing './test/test-base64.test atob' console.info: j...
File I/O - Archive of obsolete content
file = components.classes["@mozilla.org/file/local;1"]. createinstance(components.interfaces.nsilocalfile); file.initwithpath("/home"); note: the path should be in the "native" form (for example"c:\\windows"). if you need to use file:// uris as initializers, see discussion of nsiioservice below. note: you can still get a file object even if the specified file does not exist, and no
exception will be thrown. an
exception is thrown only when methods that require the file to exist are called, e.g., isdirectory(), moveto(), and so on. getting files in special directories components.utils.import("resource://gre/modules/fileutils.jsm"); // get the "data.txt" file in the profile directory var file = fileutils.getfile("profd", ["data.txt"]); or the same without using fileutils.jsm: //...
JS XPCOM - Archive of obsolete content
siprefbranch2 interface. determining which interfaces an xpcom component supports to display a list of all interfaces that an xpcom component supports, do the following: // |c| is the xpcom component instance for each (i in components.interfaces) { if (c instanceof i) { alert(i); } } in this context, instanceof is the same as queryinterface except that it returns false instead of throwing an
exception when |c| doesn't support interface |i|. another difference is that queryinterface returns an object, where as instanceof returns a boolean. xpcomutils - about protocol handler this example implements a quick about protocol handler in js using xpcomutils.jsm. components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/xpcomutils.jsm"); const c...
Common Pitfalls - Archive of obsolete content
ns return rv; } or, if the code can include nsnetutil.h: nscomptr<nsiuri> uriobj; nsresult rv = ns_newuri(getter_addrefs(uriobj), uristring, uricharset, baseuri); in all cases the baseuri can be null if the uristring should be treated as an absolute uri and uricharset can be null if there is no clear origin charset for the string (e.g. it's something the user typed in the url bar). the one
exception to all of the above, that is the one case in which creating a specific uri class via createinstance is acceptable, is when one is implementing a protocol handler's newuri method. in that case you may not be able to use the i/o service because that service calls the newuri method on the appropriate protocol handler, which may be your own handler. how to do security checks for uri loads before l...
Default Preferences - Archive of obsolete content
and mozilla will read it and set the appropriate preferences. the actual file, despite having .js extension, is not a javascript file. you may not set variables inside of it, nor may do any kind of program flow control (ifs, loops etc.) nor even calculated values (i.e. 3600 * 24 * 5). doing so will cause mozilla to stop processing your preferences file without any notification, warning, error, or
exception. think of it more as an .ini file. comments are perfectly acceptable. inside your file you set preferences using the pref() function: pref("name", "value") example: pref('extensions.defaultprefs.example.int', 1); pref('extensions.defaultprefs.example.float', 0.1); pref('extensions.defaultprefs.example.string', 'fadf'); pref('extensions.defaultprefs.example.bool', true); notice that unlike when...
Jetpack Processes - Archive of obsolete content
or being unrooted and then unreachable. the callback is only called from the process that the handle was not garbage collected in. read-write. special messages core:process-error(context) when the jetpack process crashes, this message is sent to the parent. if a crash report minidump is available, the context.dumpid property will list the minidump id of the crash report that was collected. core:
exception(error) when an
exception occurs in a jetpack script and is not caught, this message is sent to the parent. the error object contains the following properties: filename, linenumber, and message. history see bug 556846 and bug 578821 for details. sample code for example code, check out the unit tests. see also nsijetpackservice nsijetpack ...
Appendix F: Monitoring DOM changes - Archive of obsolete content
ens before the page is fully loaded. this method works particularly well with services like google instant, and the gawker family of sites. network listeners ajax-based page changes are almost universally tied to xmlhttprequests. these requests can be tracked from chrome code using a variety of methods, including web progress listeners, http observers, and content policies. while these are not
exceptionally efficient (they run for every http request, and considerably more often for some methods), they work very well for certain applications pure css pure css can be more powerful than most people suspect. it is often possible to do things for which people have traditionally resorted to javascript with css alone. in particular, the ::before and ::after pseudo-elements, and pseudo-classes like :h...
Getting Started with Firefox Extensions - Archive of obsolete content
es.required preference in about:config. install hello world click the above link and then click "allow" in the pop-up bubble. you should see another pop-up telling you that you are installing an unverified add-on. click "install". after the extension is installed, you'll be asked to restart firefox. installing, uninstalling, enabling and disabling add-ons require a restart to complete, with the
exception of npapi plugins, add-ons sdk extensions and bootstrapped extensions. this is an important point to keep in mind if you're building an extension that manipulates other extensions or themes. after installing, look at the main firefox window and see if you notice anything different. did you see it? there's a new menu on the main menu, labeled "hello world!". if you open the menu and then the m...
Handling Preferences - Archive of obsolete content
if you are going to use xpcom, you should always set a default value to your preferences, or use a try / catch block to prevent unhandled errors. preference listeners the xpcom way to add a listener was mentioned in the xpcom section when describing the queryinterface method: this._prefservice.queryinterface(ci.nsiprefbranch2); this._prefservice.addobserver(pr...
Intercepting Page Loads - Archive of obsolete content
e the use of the binary mask & operator. to detect if this is a frame being loaded or not, you can do this: if (awebprogress.domwindow != awebprogress.domwindow.top) { // this is a frame. } in this case, the url can be obtained from arequest.name. make sure you access it from inside the state validation if condition. there may be other cases where accessing this property will throw an
exception. canceling the request works just like with onlocationchange. see "recognizing page load failure" at mozilla.dev.extensions for tips on detecting connection failures and http response codes. xpcom solutions there are a couple more solutions you may be interested in trying if the previous ones are insufficient. these require creating xpcom components that implement existing firefox inte...
Local Storage - Archive of obsolete content
is a debug message."); this._logger.trace("this is a trace message."); you can filter the output of the global logger or any specific logger instance by setting the level property. during development you should use the "all" level, but for release versions it's usually better to move the level up to "warn", so that the log is compact and execution is more efficient. note: we recommend that all
exception catch blocks include some logging at the error or warn levels, and in general you should use logging freely in order to have as much information as possible to fix bugs and know what is going on. don't log inside functions that are called too often, such as mouseover event handlers, or certain http activity listeners. this impacts performance and fills the log with useless messages. we normally a...
The Box Model - Archive of obsolete content
s, thus preventing them from growing or shrinking too much. all css properties involving lengths should be handled with caution. we recommended that you use proportional units (em, %) instead of absolute units (px) whenever possible. using the former allows the ui to scale proportionately depending on font size settings, which are often changed by users with accessibility limitations. a common
exception to this rule is when your css is directly related to images, where you'll usually handle measurements in pixels (px). also, just like in html, you can control the dimensions of inflexible elements using the width and height css properties and attributes. these attributes won't have any effect on flexible elements. margins, paddings and spacers margins and paddings are frequently used in both...
Extensions support in SeaMonkey 2 - Archive of obsolete content
in 2.1 url in firefox url in seamonkey chrome://browser/content/bookmarks/bookmarkspanel.xul chrome://communicator/content/bookmarks/bm-panel.xul chrome://browser/content/places/places.xul chrome://communicator/content/bookma...rksmanager.xul thunderbird uses mostly the same chrome urls for overlaying as seamonkey. there are
exceptions, but these are few and far between. seamonkey also uses different ids for the menu items. some important menu ids are listed below, menu ids are based on firefox 3 source code: menu id in firefox menu id in seamonkey 1.x and 2.0 seamonkey 2.1 overlays menu_filepopup menu_filepopup menu_filepopup file menu popup men...
Setting up an extension development environment - Archive of obsolete content
efore the automatic restart happens. to see them, prevent the automatic restart by setting the environment no_em_restart to 1 before starting the application.) nglayout.debug.disable_xul_fastload = true. for gecko 2.0+ (firefox 4.0+). see this bug for more information. although the bug has been closed, it is believed that this pref is still relevant. you might also want to set dom.report_all_js_
exceptions = true. see
exception logging in javascript for details. devtools.errorconsole.deprecation_warnings = true. detect deprecated code use. warning: never set nglayout.debug.disable_xul_fastload to true in a production environment; it exists solely to aid in debugging. in particular, add-ons should never change this preference. note: the error console is disabled by default starting in gecko ...
Tabbed browser - Archive of obsolete content
but if its an ajax call you may end up here } } } }; here's a cleaner example of the same thing: cu.import('resource://gre/modules/services.jsm'); var httprequestobserver = { observe: function (subject...
Notes on HTML Reflow - Archive of obsolete content
nuing frames (or continuations ) created for subsequent lines. html uses a flow based layout model, meaning that most of the time it is possible to compute the geometry in a single pass. elements later "in the flow" typically 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. there are
exceptions to this rule: most notably, html tables may require more than one pass. the xul box layout model, on the other hand, is constraint based , meaning that geometric preferences and constraints of neighboring elements are taken into consideration before the elements' final geometry can be computed. the box is the geometric primitive for the xul layout model. all html reflow, includ...
Same-origin policy for file: URIs - Archive of obsolete content
bar.html and you have navigated to it from the file index.html, the load will succeed only if bar.html is either in the same directory as index.html or in a directory contained within the same directory as index.html. this policy affects anything that does same-origin checks, including xmlhttprequest, xslt, and xbl. for cross-window dom access, each file is treated as a separate origin, with one
exception: if a file is loaded from another file that would otherwise be able to load it following this same-origin policy, they are considered to have the same origin. this load can occur through a subframe, link, location set, call to window.open(), or the like. for example, if the file /home/user/foo.html is a frameset and one of the frames is /home/user/subdir/bar.html, the frame and frameset are cons...
Error Console - Archive of obsolete content
content. the error console is a tool available in most mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. it reports javascript-related errors and warnings, css errors and arbitrary messages from chrome code. in firefox, the error console can be opened from the tools menu or by ctrl-shift-j. for information about what javascript
exceptions get logged into the error console, and how to make all
exceptions get logged, read the article
exception logging in javascript. see setting up extension development environment#development preferences for the preferences you should set if you want to see errors from firefox and extensions in the error console. before gecko 1.8.1 (firefox 2), it was called javascript console (see bug 265871). ...
Java in Firefox Extensions - Archive of obsolete content
one example seems to be the fact that the "java" global is not immediately available if the extension operates in a sidebar (using settimeout solved it at least). i've had problems with stability in the latest xquseme when testing in firefox 3.5b4, especially apparently on linux (i haven't so far been able to...
Basics - Archive of obsolete content
console writes some information to the error console. you can find the console in the extra menu of firefox. the namespace for this api is console. methods info()this method does stuff. log(stringstring)this method writes a notification message to the console. stringthe message to add to the consolestring console.log("hello world!"); arn()this method does stuff. error()this method does stuff.
exception()this method does stuff. logfromcaller()this method does stuff. class notifications the notification box appears at the bottom right corner of the browser and displays important information to the user. the namespace for this class is jetpack.notificaitons. methods show(titlestringbodystringiconstring)draws a notification box. titlethe head of the notification message.string bodythe messagestrin...
Twitter - Archive of obsolete content
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. textstatus is a simple string describing the status. error(xmlhttprequest, textstatus, errorthrown) xmlhttprequest is the xhr used in the request. textstatus is a simple string describing the type of error. errorthrown is an
exception object, if one was thrown. the examples below all use this first, simpler style. the second style will be familiar if you have used jquery.ajax() -- in fact the object is passed as-is (almost) to it. in other words, define a data property that is itself an object whose properties correspond to the parameters of the twitter method. with this style you can use any of the various jquery.ajax() op...
jspage - Archive of obsolete content
.nocache){var f="nocache="+new date().gettime();g=(g)?f+"&"+g:f; }var e=b.lastindexof("/");if(e>-1&&(e=b.indexof("#"))>-1){b=b.substr(0,e);}if(g&&a=="get"){b=b+(b.contains("?")?"&":"?")+g;g=null;}this.xhr.open(a.touppercase(),b,this.options.async); this.xhr.onreadystatechange=this.onstatechange.bind(this);this.headers.each(function(m,l){try{this.xhr.setrequestheader(l,m);}catch(n){this.fireevent("
exception",[l,m]); }},this);this.fireevent("request");this.xhr.send(g);if(!this.options.async){this.onstatechange();}return this;},cancel:function(){if(!this.running){return this; }this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$empty;this.xhr=new browser.request();this.fireevent("cancel");return this;}});(function(){var a={}; ["get","post","put","delete","get","post","put","delete"].each(...
Metro browser chrome tests - Archive of obsolete content
owser/metro/base/tests/mochitest/head.js. you may add additional common utils and helpers to head.js. be careful about changing existing helpers as changes may impact tests in other libraries. static content for tests static content (html files, images, etc.) should be stored in sub directories to avoid polluting the main test directory. sub directories for larger test suites may also be created.
exceptions in tests any
exceptions thrown under test() will be caught and reported as a general failure. setup(), teardown(), and run() each have individual
exception handlers to prevent one method from interfering with the execution of another. an
exception in any of these methods will cause a test failure. additional built-in framework test checks will run after the completion of each individual test ins...
Mozilla Application Framework in Detail - Archive of obsolete content
t browsing anywhere across applications, computing platforms and devices. this innovation in browser technology offers small size, speed and industry leading standards support. gecko is the premier cross-platform, full-featured, mature and well-tested layout engine available, providing robust and high quality support for a massive array of standards. its ability to render web content correctly is
exceptional. gecko consists roughly of an html parser and xml parser, a dom implementation, a css parser and style system, and the code for css-based and html-based layout and rendering. as personal connectivity expands from the desktop computer to new web-enabled products and devices, gecko is a browser engine that has been designed from the ground up to power a new generation of desktop browsers and brow...
LIR - Archive of obsolete content
le conversions 108 i2q quad 64 bit sign-extend int to quad 109 ui2uq quad 64 bit zero-extend unsigned int to unsigned quad 110 q2i integer 64 bit truncate quad to int (removes the high 32 bits) 111 i2d double convert int to double 112 ui2d double convert unsigned int to double 113 d2i integer convert double to int (no
exceptions raised) 114 dasq quad 64 bit interpret the bits of a double as a quad 115 qasd double 64 bit interpret the bits of a quad as a double overflow arithmetic 116 addxovi integer add int and exit on overflow 117 subxovi integer subtract int and exit on overflow 118 mulxovi integer multiply int and exit on overflow 119 addjovi ...
Reading textual data - Archive of obsolete content
should happen with byte sequences that do not correspond to a valid character. the last (4th) argument to init specifies which character they get replaced with; nsiconverterinputstream.default_replacement_character is u+fffd replacement character, which is often a good choice. if you do not want any replacement, you can specify 0x0000 as replacement character; that way, readstring will throw an
exception when reaching unsupported bytes. reading lines the nsiunicharlineinputstream interface provides an easy way to read entire lines from a unichar stream. it can be used like nsilineinputstream, except that it supports non-ascii characters, and has no problems with charsets with embedded nulls (like utf-16 and utf-32). it can be used like this: var charset = /* need to find out what the characte...
Frequently Asked Questions - Archive of obsolete content
ozilla's svg implementation compare to adobe's? mozilla's native implementation is less complete than adobe svg viewer's in general. there are major features such as filters and smil based animation that have still to be implemented in mozilla. however, mozilla's implementation already supports some things that adobe's lacks, particularly parts of the xml and svg doms. for example we support svg
exceptions and svgtransform objects. how do you install adobe's svg viewer in mozilla? the svg project is about mozilla's native implementation of svg, not adobe/corel/whoever's plug-in. however, we might as well answer this question to save you searching for this information elsewhere. see these install instructions on mozdev.org. it's also useful to know that you can check whether mozilla has recognise...
Supporting private browsing mode - Archive of obsolete content
nsiobserverservice); this._os.addobserver(this, "private-browsing", false); this._os.addobserver(this, "quit-application", false); try { var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); this._inprivatebrowsing = pbs.privatebrowsingenabled; } catch(ex) { // ignore
exceptions in older versions of firefox } }, observe : function (asubject, atopic, adata) { if (atopic == "private-browsing") { if (adata == "enter") { this._inprivatebrowsing = true; if (this.watcher && "onenterprivatebrowsing" in this._watcher) { this.watcher.onenterprivatebrowsing(); } } else if (adata == "exit") { this._inpr...
Abc Assembler Tests - Archive of obsolete content
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 "t...
When To Use ifdefs - Archive of obsolete content
lication ifdefs should only be made in application-specific code. this is the trickiest kind of ifdef, because it is frequently hard to determine what code is "shared" and what code is "application-specific". as a general rule, any code in tier 2, tier 9, or tier 50 is shared code, and should not have application-specific ifdefs. any code in later tiers is application-specific. this rule has many
exceptions, some of which are listed here: the code in editor/ui/ is built by the suite, standalone composer, and thunderbird, but it is considered application-specific. the code in xpfe/ (except for xpfe/appshell/ and xpfe/components/shistory/) is a hodgepodge mess of "toolkit" and "application-specific" code. this code is all going to be moved elsewhere (most of it to toolkit/ or suite/), but for the ...
Writing textual data - Archive of obsolete content
ering). passing 0 ensures that data will be immediately written to the underlying stream; however, for better perfomance you should pass a value like 4096 instead. unsupported characters you can specify what should happen with characters that are not supported by the selected character encoding. the last argument to init specifies that: 0x0000 means that writing unsupported characters throws an
exception (with an error code of ns_error_loss_of_significant_data), and no data will be written. to instead write a replacement character in such cases, specify the character instead of 0x00: os.init(fos, charset, 0, "?".charcodeat(0)); you can, of course, replace the "?" in that example with any other character. you can also specify any unicode character u+abcd directly as 0xabcd. note: if the repla...
Anonymous Content - Archive of obsolete content
pped and flow proceeds to the next phase. whenever an event is retargeted, the target field of the event is set to the bound element. the original anonymous content responsible for the event can be obtained from a new field of the event object: originaltarget. the action taken (retarget vs. stop) is specific to the event type. in general, ui events are retargeted and mutation events are stopped.
exceptions to the rule are noted below. focus and blur events when a focus or blur event crosses a scope boundary, the bound element is checked to see if it is focusable (i.e., if the user agent would normally fire a focus or blur event on the element). if the bound element is focusable, then the event is retargeted. if not, then the event is stopped. if anonymous content underneath a focusable bound ele...
XML in Mozilla - Archive of obsolete content
ylesheets with xml documents, and namespaces in xml. the core support is very good with few bugs. dtds and other external entities mozilla does not load external entities from the web. mozilla can load external entities whose system identifier uses the chrome protocol. this feature is used mainly to localize mozilla to different languages (the ui strings are stored in external dtd files). another
exception is an entity whose system identifier is a relative path, and the xml declaration states that the document is not standalone (default), in which case mozilla will try to look for the entity under <bin>/res/dtd directory. mozilla may also make an
exception with xhtml documents, see below. mozilla will read internal (dtd) subsets, and in special circumstances external dtds as explained above and wil...
Install script template - Archive of obsolete content
odes need some memory var err; // error return codes when we try and install to the current browser var errblock1; // error return codes when we try and do a secondary installation var errblock2 = 0; // global variable containing our secondary install location var secondaryfolder; //special error values used by the cycore developers (www.cycore.com) who helped make this install script var
exceptionoccurederror = -4711; var winregisnullerror = -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(so...
Getting File Information - Archive of obsolete content
ject has a number of useful attributes which may be used to retrieve information about a file. two useful attributes filesize and lastmodifiedtime (nsifile.attributes) provide a means of retrieving the size of a file and the time when the file was last changed. file size the filesize (nsifile.attributes) attribute holds the size of a file in bytes. if the file does not exist, a 'file not found'
exception will occur. you can catch this
exception with a try-catch block, but it is better to use nsifile.exists() to check first. this example will check if a file on the desktop exists and set the variable 'filesize' to the size of the file. if the file is not present, the 'filesize' variable will not be changed from the default value of 0. var filesize = 0; var file = io.getfile("desktop", "saved file...
Index - Archive of obsolete content
9 actions xul, xul_template_guide the content to generate in a template is specified using the action element which should either be the next sibling of the query element (if no rules need be specified) or be a direct child of a rule element. the content to generate goes directly inside the action element. this content will be copied for each matching result (though see below for an
exception) and inserted into the document. let's look at a simple example first. 920 additional navigation xul, xul_template_guide the triples used so far have all had variables in both the subject and object. however, a string value may be used instead. since the subject of an rdf arc is always a resource, the subject may be a resource uri. the object attribute may be a resource uri o...
Actions - Archive of obsolete content
« previousnext » the content to generate in a template is specified using the <xul:action> element which should either be the next sibling of the <xul:query> element (if no rules need be specified) or be a direct child of a <xul:rule> element. the content to generate goes directly inside the action element. this content will be copied for each matching result (though see below for an
exception) and inserted into the document. let's look at a simple example first. <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/a"> <template> <query> <content uri="?start"/> <triple subject="?start" predicate="http://www.xulplanet.com/rdf/relateditem" object="?relateditem"/> </query> <action> ...
Multiple Rule Example - Archive of obsolete content
le, despite that they both store the value of the title predicate. there is no reason for this -- it is only used in this example to show that there is no connection between the variables used in the two rules. you can use different variables if it makes sense in the context of the template or the data, although in this example it would seem more reasonable to use the same variable name. the only
exception to this is that the container and member variables (those that are referred to in the uri attributes), must be the same in all rules. in this example, the container variable is ?start and the member variable is ?photo. if different variables were used for these, the rules would not work properly. the reason for this is due to the manner in which the builder processes the data. looking back at the...
Templates - Archive of obsolete content
to guess what would happen if the second rule was removed. the result would be a single spacer displayed but no bookmarks because they don't match any of the rules. put simply, a rule matches if all of the attributes placed on the rule element match the corresponding attributes on the rdf resource. in the case of an rdf file, the resources would be the description elements. there are some small
exceptions however. you cannot match based on the attributes id, rdf:property or rdf:instanceof. because you can just use your own attributes with your own namespace, it probably doesn't really matter anyway. note that a template with no rules in it, as in the first example, is really equivalent functionally to a template with a single rule with no attributes. next, we'll look at using templates with tre...
XPCOM Interfaces - Archive of obsolete content
var alocalfile = components.classes["@mozilla.org/file/local;1"].createinstance(components.interfaces.nsilocalfile); this will do the same thing as the two lines but in one line of code. it eliminates the need to create the instance and then query it for an interface in two separate steps. if you call queryinterface() on an object and the requested interface is not supported by an object, an
exception is thrown. if you're not sure that an interface is supported by a component, you can use the instanceof operator to check: var afile = components.classes["@mozilla.org/file/local;1"].createinstance(); if (afile instanceof components.interfaces.nsilocalfile){ // do something } the instanceof operator returns true if afile implements the nsilocalfile interface. this also has the side effect of...
XUL accessibility guidelines - Archive of obsolete content
rm elements should not be used to label other form elements. when form elements are encapsulated in a groupbox with a caption, assistive technologies such as screen readers will read the caption along with the label to the form element. for example, under the privacy section of preferences there are three groupboxes captioned: history, cookies, and private data. if the user were to tab to the "
exceptions..." button they would hear "cookies {pause}
exceptions {pause} button." the next tab would read "cookies {pause} keep until {pause} they expire {pause} one of three {pause} combobox." if the screen reader only read the label, then the user would have to guess what the "
exceptions" button or the "keep until" combobox was referring to. groupboxes are essential for radiogroups or groups of checkbo...
Building XULRunner with Python - Archive of obsolete content
ton activated') window.addeventlistener('load', onload, false) one possible gotcha is that the default python path used to find modules that areimported explicitly includes the xulrunner executable directory and the directory that is current when xulrunner launches. however it does not include any path related to the xul application being run. some work around will need to be found. unhandled
exceptions are displayed in the javascript error console which can be opened usingxulrunner -jsconsole. one solution is to puttry .... except: print_exc() round any event handler to print tracebacks to stdout and use a python console to catch that output. the jsconsole can also be open and used from code, for example (in javascript) function openjavascriptconsole() { var wwatch = components.classes["@m...
Archived Mozilla and build documentation - Archive of obsolete content
onsole the error console is a tool available in most mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. it reports javascript-related errors and warnings, css errors and arbitrary messages from chrome code. in firefox, the error console can be opened from the tools menu or by ctrl-shift-j.
exception logging in javascript technical review completed. existing content this is a list of existing mozilla.org documentation. it needs to be checked, prioritized, and migrated. extension frequently asked questions this is quick set of answers to the most common issues with extension development. they are currently written with mostly...
2006-11-24 - Archive of obsolete content
nt.mk build_all". joe is asking for help on a possible solution to fix his problem. building xpcom components with msvs 2005 november 21st: buffaloaf is having trouble getting a personal xpcom component to work under xulrunner when compiled with msvs 2005. luke is migrating all of his code to compile with vc8 and is having some problems. he is receiving the following error: error: uncaught
exception: [
exception... "component returned failure code: 0x80570016 (ns_error_xpc_gs_returned_failure) [nsijscid.getservice]" nsresult: "0x80570016 (ns_error_xpc_gs_returned_failure)" location: "js frame :: chrome://modzilla/content/js/pkg_zillacom.js :: <top_level> :: line 1202" data: no] he is running xulrunner v1.8.0.4. luke wants to know if compiling xulrunner with a static crt is better or wor...
NPN_GetURLNotify - Archive of obsolete content
lug-in-private value for associating the request with the subsequent npp_urlnotify() call, which passes this value (see description below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_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() typically handles the url request asynchronously. it returns immediately and only later handles the request and calls npp_urlnotify(). this notification is the only way the plug-in can...
NPN_PostURLNotify - Archive of obsolete content
-private value for associating the request with the subsequent npp_urlnotify call, which returns this value (see description below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_posturlnotify functions identically 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. for more information, see npn_posturl. npn_posturlnotify is typically asynchronous: it returns immediately and only later handles the request and calls npp_urlnotify. if this function is called with a target parameter ...
NPAPI plugin reference - Archive of obsolete content
npn_reloadplugins reloads all of the installed plugins. npn_removeproperty removes a property from the specified npobject. npn_requestread requests a range of bytes from a seekable stream. this initiates a read operation; the actual data is received through subsequent calls to npp_writeready() and npp_write(). npn_retainobject increments the reference count of the given npobject. npn_set
exception a plugin can call this function to indicate that a call to one of the plugin's npobjects generated an error. npn_setproperty sets the value of a property on the specified npobject. npn_setvalue implemented by browsers. this call is used to inform the browser of variable information controlled by the plugin. npn_setvalueforurl allows a plugin to change the stored information associated with...
Using workers in extensions - Archive of obsolete content
which stock is being monitored. if there is no data field, the refreshinformation() method is called to fetch the latest information about the stock and pass it back to the main thread. this provides a way for the main thread to specifically request that the worker update the stock information at once. the refreshinformation() method is fairly similar to the previous versions, with two notable
exceptions: if the ticker symbol has not been set yet, an
exception is thrown (lines 4-6). when the result is received from xmlhttprequest, instead of immediately updating the displayed information in the status bar, a message is sent to the main thread using the worker's postmessage() method. this is because only the main thread is allowed to access the user interface. the main thread the changes h...
Debug - Archive of obsolete content
1 debug.ms_async_op_status_canceled the asynchronous operation was canceled. 2 debug.ms_async_op_status_error the asynchronous operation resulted in an error. 3 properties debug.debuggerenabled determines whether debugging is enabled for the script context. debugging may be enabled or disabled whether or not a debugger is attached. debug.setnonusercode
exceptions determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled. functions debug.mstraceasynccallbackcompleted indicates that the callback stack associated with a previously specified asynchronous operation has completed. debug.mstraceasynccallbackstarting associates the callback stack with a previously specified asynchronous operation. debug.m...
Error.number - Archive of obsolete content
ameters object any instance of the error object. errornumber an integer representing an error. remarks an error number is a 32-bit value. the upper 16-bit word is the facility code, and the lower word is the error code. to determine the error code, use the & (bitwise and) operator to combine the number property with the hexadecimal number 0xffff. example the following example causes an
exception to be thrown and displays the error code that is derived from the error number. try { // cause an error. var x = y; } catch(e) { document.write ("error code: "); document.write (e.number & 0xffff) document.write ("<br />"); document.write ("facility code: ") document.write(e.number>>16 & 0x1fff) document.write ("<br />"); document.write ("error m...
New in JavaScript 1.5 - Archive of obsolete content
3 (from december 1999). new features in javascript 1.5 number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() const is now a reserved word. multiple catch clauses in a try...catch statement are supported. javascript authors can now add getters and setters to their objects. changed functionality in javascript 1.5 runtime errors are now reported as
exceptions. regular expression changes: quantifiers — +, *, ? and {} — can now be followed by a ? to force them to be non-greedy. non-capturing parentheses, (?:x) can be used instead of capturing parentheses, (x). when non-capturing parentheses are used, matched subexpressions are not available as back-references. positive and negative lookahead assertions are supported. both assert a matc...
Reflect.enumerate() - Archive of obsolete content
lect.enumerate() method used to return an iterator with the enumerable own and inherited properties of the target object, but has been removed in ecmascript 2016 and is deprecated in browsers. syntax reflect.enumerate(target) parameters target the target object on which to get the property. return value an iterator with the enumerable own and inherited properties of the target object.
exceptions a typeerror, if target is not an object. description the reflect.enumerate method returns an iterator with the enumerable own and inherited properties of the target object. examples using reflect.enumerate() var obj = { x: 1, y: 2 }; for (var name of reflect.enumerate(obj)) { console.log(name); } // logs "x" and "y" specifications not part of any standard. ...
JavaArray - Archive of obsolete content
summary core object a wrapped java array accessed from within javascript code is a member of the type javaarray. created by any java method which returns an array. in addition, you can create a javaarray with an arbitrary data type using the newinstance method of the array class: public static object newinstance(class componenttype, int length) throws negativearraysize
exception description the javaarray object is an instance of a java array that is created in or passed to javascript. javaarray is a wrapper for the instance; all references to the array instance are made through the javaarray. in javascript 1.4 and later, the componenttype parameter is either a javaclass object representing the type of the array or class object, such as one returned by java.lang.class.forname. in java...
JavaPackage - Archive of obsolete content
ackages.javapackage javapackageis the name of the object's java package. if the package is in the java, netscape, or sun packages, the packages keyword is optional. description in java, a package is a collection of java classes or other java packages. for example, the netscape package contains the package netscape.javascript; the netscape.javascript package contains the classes jsobject and js
exception. in javascript, a javapackage is a reference to a java package. for example, a reference to netscape is a javapackage. netscape.javascript is both a javapackage and a property of the netscape javapackage. a javaclass object is a reference to one of the classes in a package, such as netscape.javascript.jsobject. the javapackage and javaclass hierarchy reflect the java package and class hierarchy...
Old Proxy API - Archive of obsolete content
after a call to fix(), the proxy becomes a regular (non-proxy) object with the properties listed in the return value. the handler is no longer used. moreover, the respective method (freeze(), seal(), or preventextension()) is immediately called on the fixed object. note: the fixed object has the same object identity as the proxy object. if fix() returns undefined, the call throws a typeerror
exception. derived traps default implementation refers to the code that is called for that trap when the trap isn't explicitly defined. in these functions, this refers to the handler object. emulated javascript code handler method default implementation description name in proxy has: function(name) -> boolean function(name) { return !!this.getpropertyde...
XForms Custom Controls - Archive of obsolete content
ndicate to a submit element that it needs to disable/enable due to the beginning/ending of the submission process. currently it has no meaning outside of this context. focus() is used by the processor to tell the control that it is getting focus through one of a variety of ways (i.e. through xf:setfocus action) and that the control needs to ensure that the proper widget is given focus. with rare
exception, your control should only need to implement the nsixformsuiwidget interface. but certain xforms controls need to implement additional interfaces. such elements include upload and case. nsixformsaccessors the nsixformsaccessors interface allows access to the value and the state of the instance node that the control is bound to (see extensions/xforms/nsixformsaccessors.idl). currently interface is:...
Troubleshooting XForms Forms - Archive of obsolete content
are using the noscript plugin you may notice that your put and/or post requests are being converted to get requests. in order to fix this, go to the noscript options dialog (right-click on the 's' icon on the status bar and select 'options...') and select the advanced tab. the xss sub-tab has the following options: turn cross-site post requests into data-less get requests anti-xss protection
exceptions you can temporarily fix the problem by unchecking the turn cross-site post requests into data-less get requests check box. alternatively, for a long term fix you can enter an
exception pattern in the anti-xss protection
exceptions text area. 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...
Using the Right Markup to Invoke Plugins - Archive of obsolete content
he object element is supported for use with the microsoft® windows media player. only the windows media player is supported as an activex control in netscape 7.1. the details are covered in another article. browsers such as netscape 7 will not render the flash plugin if the above kind of markup is used, because netscape 7 does not support activex or activex-based component invocations, with the
exception of windows media player in netscape 7.1. mozilla-based browsers support the netscape plugin architecture, which is not com based like activex (and thus, not invoked via a unique identifier) but rather, mime type based. mozilla-based browsers support the use of the object element along with a mime type. here is an example of this usage, once again for the macromedia flash plugin: <object type="ap...
XQuery - Archive of obsolete content
being open source), but now some problems may exist with bdbxml (unlike saxon). a simple usage example is available. notes for developers wishing to access xquery in their own extensions at present, the extension works simply by using liveconnect to work with berkeley db xml's java api (and via a java wrapper class which circumvents liveconnect's current inability to handle some types of java
exceptions properly). however, use of the approach of the java firefox extension might be used to turn the above extension concept into an xpcom component (giving it access to all open windows), and for berkeley db xml, possibly implementing it in c++ instead, which is that database's original language of development. however, the extension demonstrates a technique which does not depend on using xpcom, w...
Using the DOM File API in chrome code - Extensions
get one bonus feature: you can create file objects specifying the path of the file on the user's computer. this only works from privileged code, so web content can't do it. this protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. if you pass a path to the file constructor from unprivileged code (such as web content), an
exception will be thrown. scope availability in the jsm scope file is available without needing to do anything special. in bootstrap scope, this must be imported in like so: cu.importglobalproperties( [ "file" ] ) accessing a file by hard-coded pathname to reference a file by its path, you can simply use a string literal: var file = file.createfromfilename("path/to/some/file"); cross platform note...
Audio for Web games - Game development
htmlmediaelement api, but it becomes much easier and more flexible with the more advanced web audio api. let's look at this next. element and associated htmlmediaelement api, but it becomes much easier and more flexible with the more advanced web audio api. let's look at this next. web audio api for games the web audio api is supported across all modern desktop and mobile browsers, with the
exception of opera mini. with that in mind, it's an acceptable approach for many situations to use the web audio api (see the can i use web audio api page for more on browser compatibility). the web audio api is an advanced audio javascript api that is ideal for game audio. developers can generate audio and manipulate audio samples as well as positioning sound in 3d game space. a feasible cross-browser st...
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
decoding and encoding base64 strings: btoa(): creates a base-64 encoded ascii string from a "string" of binary data ("btoa" should be read as "binary to ascii"). atob(): decodes a base64 encoded string("atob" should be read as "ascii to binary"). the algorithm used by atob() and btoa() is specified in rfc 4648, section 4. note that btoa() expects to be passed binary data, and will throw an
exception if the given string contains any characters whose utf-16 representation occupies more than one byte. for more details, see the documentation for btoa(). encoded size increase each base64 digit represents exactly 6 bits of data. so, three 8-bits bytes of the input string/binary file (3×8 bits = 24 bits) can be represented by four 6-bit base64 digits (4×6 = 24 bits). this means that the base64...
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
zations. if a variable is declared and initialized after using it, the value will be undefined. for example: console.log(num); // returns undefined, as only declaration was hoisted, no initialization has happened at this stage var num; // declaration num = 6; // initialization the example below only has initialization. no hoisting happens so trying to read the variable results in referenceerror
exception. console.log(num); // throws referenceerror
exception num = 6; // initialization below are more examples demonstrating hoisting. // example 1 // only y is hoisted x = 1; // initialize x, and if not already declared, declare it - but no hoisting as there is no var in the statement. console.log(x + " " + y); // '1 undefined' // this prints value of y as undefined as javascript only hoists decla...
MDN Web Docs Glossary: Definitions of Web-related terms
layer security) dtmf (dual-tone multi-frequency signaling) dynamic programming language dynamic typing e ecma ecmascript effective connection type element empty element encapsulation encryption endianness engine entity entity header event
exception expando f fallback alignment falsy favicon fetch directive fetch metadata request header firefox os firewall first contentful paint first cpu idle first input delay first interactive first meaningful paint first paint first-class function ...
Mobile accessibility - Learn web development
days, mobile devices can usually handle fully-featured websites, and the main platforms even have screenreaders built in to enable visually impaired users to use them successfully. modern mobile browsers tend to have good support for wai-aria, too. to make a website accessible and usable on mobile, you just need to follow general good web design and accessibility best practices. there are some
exceptions that need special consideration for mobile; the main ones are: control mechanisms — make sure interface controls such as buttons are accessible on mobiles (i.e., mainly touchscreen), as well as desktops/laptops (mainly mouse/keyboard). user input — make user input requirements as painless as possible on mobile (e.g., in forms, keep typing to a minimum). responsive design — make sure l...
Organizing your CSS - Learn web development
same rules to something outside of main, or to something other than a <p>, you would have to add another selector to these rules or create a whole new ruleset. instead, you could use the selector .box to apply your rule to any element that has the class box: .box { border: 1px solid #ccc; } there will be times when making something more specific makes sense, however this will generally be an
exception rather than usual practice. break large stylesheets into multiple smaller ones in particular in cases where you have very different styles for distinct parts of the site, you might want to have a stylesheet that includes all the global rules and then smaller ones that include the specific rules needed for those sections. you can link to multiple stylesheets from one page, and the normal rules o...
What do common web layouts contain? - Learn web development
rt mixing them all together: … these are just examples and you're quite free to lay things out as you want. you may notice that, while the content can move around on the screen, we always keep the header (1) on top and the footer (2) at the bottom. also, the main content (a) matters most, so give it most of the space. these are rules of thumb you can draw on. there are complex designs and
exceptions, of course. in other articles we'll discuss how to design responsive sites (sites that change depending on the screen size) and sites whose layouts vary between pages. for now, it's best to keep your layout consistent throughout your site. active learning there is no active learning available yet. deeper dive let's study some more concrete examples taken from well-known websites. one-column...
The HTML5 input types - Learn web development
in html5 to allow collection of specific types of data. prerequisites: basic computer literacy, and a basic understanding of html. objective: to understand the newer input type values available to create native form controls, and how to implement them using html. note: most of the features discussed in this article have wide support across browsers. we'll note any
exceptions. if you want more detail on browser support, you should consult our html forms element reference, and in particular our extensive <input> types reference. because html form control appearance may be quite different from a designer's specifications, web developers sometimes build their own custom form controls. we cover this in an advanced tutorial: how to build custom form widgets. e-mail add...
Sending form data - Learn web development
le out, to get an idea of what's possible. be paranoid: never trust your users so, how do you fight these threats? this is a topic far beyond this guide, but there are a few rules to keep in mind. the most important rule is: never ever trust your users, including yourself; even a trusted user could have been hijacked. all data that comes to your server must be checked and sanitized. always. no
exception. escape potentially dangerous characters. the specific characters you should be cautious with vary depending on the context in which the data is used and the server platform you employ, but all server-side languages have functions for this. things to watch out for are character sequences that look like executable code (such as javascript or sql commands). limit the incoming amount of data to ...
Styling web forms - Learn web development
<textarea>, <input type="submit">, and a <button> in chrome on macos, with the platform's default font style in use. on the right are the same elements, with our above style rule applied. the defaults differed in a number of ways. inheriting should change their fonts to that of the parent's font family — in this case the default serif font of the parent container. they all do, with a strange
exception — <input type="submit"> does not inherit from the parent paragraph in chrome. rather, it uses the font-family: system-ui. this is another reason to use <button> elements over their equivalent input types! there's a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. this decision is yours to make, as the designer o...
Document and website structure - Learn web development
ifferent pages. this is very similar to a technique called card sorting. now try to sketch a rough sitemap — have a bubble for each page on your site, and draw lines to show the typical workflow between pages. the homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are
exceptions. you might also want to include notes about how things might be presented. active learning: create your own sitemap try carrying out the above exercise for a website of your own creation. what would you like to make a site about? note: save your work somewhere; you might need it later on. test your skills! you've reached the end of this article, but can you remember the most important in...
Marking up a letter - Learn web development
to be hosted on a university intranet. the letter is a response from a research fellow to a prospective phd student concerning their application to the university. block/structural semantics use appropriate document structure including doctype, and <html>, <head> and <body> elements. in general, the letter should be marked up as an organization of headings and paragraphs, with the following
exception. there is one top level heading (the "re:" line) and three second level headings. use an appropriate list type to mark up the semester start dates, study subjects, and exotic dances. put the two addresses inside <address> elements. each line of the address should sit on a new line, but not be in a new paragraph. inline semantics the names of the sender and receiver (and tel and email) shou...
Fetching data from the server - Learn web development
text(), to get it to pass its result on to the next link in the chain. which mechanism should you use? this really depends on what project you are working on. xhr has been around for a long time now and has very good cross-browser support. fetch and promises, on the other hand, are a more recent addition to the web platform, although they're supported well across the browser landscape, with the
exception of internet explorer. if you need to support older browsers, then an xhr solution might be preferable. if however you are working on a more progressive project and aren't as worried about older browsers, then fetch could be a good choice. you should really learn both — fetch will become more popular as internet explorer declines in usage (ie is no longer being developed, in favor of microsoft...
Introduction to the server side - Learn web development
with html templates (4), and sends back a response containing the generated html (5,6). are server-side and client-side programming the same? let's now turn our attention to the code involved in server-side and client-side programming. in each case, the code is significantly different: they have different purposes and concerns. they generally don't use the same programming languages (the
exception being javascript, which can be used on the server- and client-side). they run inside different operating system environments. code running in the browser is known as client-side code and is primarily concerned with improving the appearance and behavior of a rendered web page. this includes selecting and styling ui components, creating layouts, navigation, form validation, etc. by contrast, ser...
Componentizing our Svelte app - Learn web development
tracting our filter component we'll begin by creating our filterbutton.svelte. first of all, create a new file — components/filterbutton.svelte. inside this file we will declare a filter prop, and then copy the relevant markup over to it from todos.svelte. ...
Getting started with Vue - Learn web development
used in development code into older syntax that is more cross-browser compatible in production code. you can register additional babel plugins in this file. .browserslistrc: this is a config for browserslist. you can use this to control which browsers your tooling optimizes for. public: this directory contains static assets that are published, but not processed by webpack during build (with one
exception; index.html gets some processing). favicon.ico: this is the favicon for your app. currently, it's the vue logo. index.html: this is the template for your app. your vue app is run from this html page, and you can use lodash template syntax to interpolate values into it. note: this is not the template for managing the layout of your application — this template is for managing static ...
Setting up your own test automation environment - Learn web development
output of your test will be reflected on your lambdatest console. if you wish to extract these results for reporting purpose from lambdatest platform then you can do so by using lambdatest restful api. now if you go to your lambdatest automation dashboard, you'll see your test listed; from here you'll be able to see videos, screenshots, and other such data. you can retrieve network, command,
exception, and selenium logs for every test within your test build. you will also find a video recording of your selenium script execution. note: the help button on lambdatest automation dashboard will provide you with an ample amount of information to help you get started with lambdatest automation. you can also follow our documentation about running first selenium script in node js. note: if you d...
Chrome Worker Modules
and cannot be used for the installation of resources, please see the documentation on moz.build (if your code is part of the platform) or on chrome manifests (if your code is part of an add-on). stack traces unfortunately, the module loader doesn’t play nicely with error stack traces. that is, the following will not show human-readable stacks: try { mymodule.foo(); } catch (ex) { log("
exception raised at " + ex.filename) log("stack: " + ex.stack); } rather, you should use properties modulename and modulestack, as follows: try { mymodule.foo(); } catch (ex) { log("
exception raised at " + ex.modulename) log("stack: " + ex.modulestack); } subtleties you shouldn’t mix both styles exports.foo = bar and module.exports = {foo: bar}. if you do, know that any call to module...
Mozilla accessibility architecture
rovider::getaccessible() or nsiframe::getaccessible(), new accessibles are created by calling back to the accessibility service, and using a specific method for creating each type of accessible. for example, nshtmltablecellframe::getaccessible() will eventually call nsiaccessibilityservice::createhtmltablecellaccessible(), which uses |new nshtmltablecellaccessible(domnode, weakpresshell); special
exception: traversal overloading in some cases the necessary accessible children are not in the dom subtree for a node. this is the case for: nshtmlimageaccessible: in msaa an image accessible can have accessible children if it has an image map. the children are the image map areas, which are in a different part of the dom tree. nshtmlcomboboxaccessible: an html combo box doesn't have a dom node or an...
Browser chrome tests
really do that instead! function test() { // requestlongertimeout accepts an integer factor, that is a multiplier for the the default 30 seconds timeout. // so a factor of 2 means: "wait for at last 60s (2*30s)". requestlongertimeout(2); waitforexplicitfinish(); settimeout(completetest, 40000); } function completetest() { ok(true, "timeout did not run"); finish(); }
exceptions in tests any
exceptions thrown under test() will be caught and reported in the test output as a failure.
exceptions thrown outside of test() (e.g. in a timeout, event handler, etc) will not be caught, but will result in a timed out test if they prevent finish() from being called. cleaning up after yourself if you need to do special clean up after running your test, you can register a cleanup ...
Creating Sandboxed HTTP Connections
k onchannelredirect: function (aoldchannel, anewchannel, aflags) { // if redirecting, store the new channel gchannel = anewchannel; }, // nsiinterfacerequestor getinterface: function (aiid) { try { return this.queryinterface(aiid); } catch (e) { throw components.results.ns_nointerface; } }, // nsiprogresseventsink (not implementing will cause annoying
exceptions) onprogress : function (arequest, acontext, aprogress, aprogressmax) { }, onstatus : function (arequest, acontext, astatus, astatusarg) { }, // nsihttpeventsink (not implementing will cause annoying
exceptions) onredirect : function (aoldchannel, anewchannel) { }, // we are faking an xpcom interface, so we need to implement qi queryinterface : function(aiid) { if (aiid.equals(c...
Eclipse CDT
arch for unresolved includes". for problematic source files, select the file in the project explorer and from the context menu select "index > create parser log file". select your project in the project explorer, then from the context menu select "index > rebuild". when the indexing is done, open the log using "window > show view > other > general > error log" and check the summary and look for
exceptions. searching free text search is not backed by a database, so it is extremely slow. furthermore, the results are not saved so if you immediately search for the exact same text again without any changes to the source files having occurred, eclipse will do a slow search all over again. it is not easy to restrict searches to an arbitrary directory, which is pretty annoying given how slow free tex...
Interface Compatibility
rogramming interfaces change. the rules which govern interface changes are different depending on the consumers and the languages involved. web content apis which are visible to web content are not modified, except as a last resort when inherent security vulnerabilities or incompatibility with other browsers make it the only option. any changes, including new features, must have super-review. one
exception to this rule is apis which are explicitly shipped with mozilla prefixes as a technology preview. this includes css properties that begin with the -moz- prefix (e.g. -moz-box-shadow), or javascript apis that begin with the moz prefix (e.g. canvasrenderingcontext.mozdrawtext). these apis may be removed or replaced with standard interfaces in future releases of mozilla. jetpack the jetpack sdk and...
Commenting IDL for better documentation
monster. * @param cookietoeat the nsicookie to eat. */ void eatcookie(in nsicookie cookietoeat); /** * sings the song "c is for cookie." */ void sing(); /** * returns a string containing a funny quote the cookie monster might say. * * @param number the saying number to return. * * @returns an astring containing the requested funny quote. if the specified * quote number is invalid, an
exception is thrown. * * @throws ns_error_failure unable to locate the requested quote. */ astring getfunnysaying(in integer number); /** * says something appreciative of the tastiness of the cookie in the specified * language. * * @param language the localization identification indicating the language in * which the cookie monster is to express his love of cookies. */ [noscript] void sayyummy(in...
Reviewer Checklist
up to make the fix easier to write and review". if qa needs to verify the fix, you should provide steps to reproduce (str). quality if you can unit-test it, you should unit-test it. if it's js, try to design and build so that xpcshell can exercise most functionality. it's quicker. make sure the patch doesn't create any unused code (e.g., remove strings when removing a feature) all caught
exceptions should be logged at the appropriate level, bearing in mind personally identifiable information, but also considering the expense of computing and recording log output. [fennec: checking for log levels is expensive unless you're using logger.] style follow the style guide for the language and module in question. follow local style for the surrounding code, even if that local style isn't for...
Error codes returned by Mozilla APIs
rror_xpc_scriptable_ctor_failed (0x80570012) ns_error_xpc_cant_call_wo_scriptable (0x80570013) ns_error_xpc_cant_ctor_wo_scriptable (0x80570014) ns_error_xpc_ci_returned_failure (0x80570015) ns_error_xpc_gs_returned_failure (0x80570016) ns_error_xpc_bad_cid (0x80570017) ns_error_xpc_bad_iid (0x80570018) ns_error_xpc_cant_create_wn (0x80570019) ns_error_xpc_js_threw_
exception (0x8057001a) ns_error_xpc_js_threw_native_object (0x8057001b) ns_error_xpc_js_threw_js_object (0x8057001c) ns_error_xpc_js_threw_null (0x8057001d) ns_error_xpc_js_threw_string (0x8057001e) ns_error_xpc_js_threw_number (0x8057001f) ns_error_xpc_javascript_error (0x80570020) ns_error_xpc_javascript_error_with_details (0x80570021) ns_error_xpc_cant_convert_primitive_t...
Cross Process Object Wrappers
this document describes cross process object wrappers (cpows), which enable chrome code to synchronously access content in multiprocess firefox. note that from firefox 47 onwards, unsafe cpow usage is no longer permitted in browser code. if browser code tries an unsafe cpow operation, the browser will throw an
exception and you'll see an "unsafe cpow usage forbidden” error in the browser console. add-on code is still allowed to use cpows "unsafely". however, if an add-on passes a cpow into a platform api, and that platform api then attempts an unsafe operation on it, this will throw an
exception. so as a general rule, add-ons should avoid passing cpows into non-addon code. in multiprocess firefox, chrome code runs in a different process from web content. so chrome code can't direct...
Limitations of chrome scripts
ager. limitations of cpows cross process object wrappers (cpows) are a migration aid giving chrome code synchronous access to content objects. however, there are various limitations on the kinds of things you can do with a cpow. note that from firefox 47 onwards, unsafe cpow usage is no longer permitted in browser code. if browser code tries an unsafe cpow operation, the browser will throw an
exception and you'll see an "unsafe cpow usage forbidden” error in the browser console. add-on code is still allowed to use cpows "unsafely". however, if an add-on passes a cpow into a platform api, and that platform api then attempts an unsafe operation on it, this will throw an
exception. so as a general rule, add-ons should avoid passing cpows into non-addon code. nsicontentpolicy without the shim...
Limitations of frame scripts
ntent process. for example: nsisessionstore nsiwindowmediator <need more examples> places api the places api can't be used inside a frame script. for example: nsinavhistoryservice nsinavbookmarksservice observers in the content process as noted in observers in the chrome process, most observers should be registered in the chrome process and will not work in the content process. the
exceptions are: content-document-global-created document-element-inserted outer-window-destroyed inner-window-destroyed dom-window-destroyed these must be registered in the content process. qi from content window to chrome window there's a particular pattern often used to get from a content window to the associated chrome window. it looks something like this: window.queryinterface(ci.nsiinte...
Limitations of frame scripts
ntent process. for example: nsisessionstore nsiwindowmediator <need more examples> places api the places api can't be used inside a frame script. for example: nsinavhistoryservice nsinavbookmarksservice observers in the content process as noted in observers in the chrome process, most observers should be registered in the chrome process and will not work in the content process. the
exceptions are: content-document-global-created document-element-inserted outer-window-destroyed inner-window-destroyed dom-window-destroyed these must be registered in the content process. qi from content window to chrome window there's a particular pattern often used to get from a content window to the associated chrome window. it looks something like this: window.queryinterface(ci.nsiinte...
Performance
all the previous examples, *even the "better" ones* if your addon is restartless or uses the sdk then updates or the user turning it off and on will load to unload/reload events. not handling those properly can lead to duplicate or conflicting code execution, especially when messages are sent. it can also lead to conflicts between the old and new code. under some circumstances it may even cause
exceptions when attempting to register something twice under the same id. better: // addon.js function onunload() { services.mm.removedelayedframescript("resources://my-addon/framescript.js"); services.ppmm.removedelayedprocessscript("resources://my-addon/processcript.js"); services.mm.broadcastasyncmessage("my-addon:unload"); services.ppmm.broadcastasyncmessage("my-addon:unload"); } in the fra...
Blocked: Custom cookie permission
quest to access cookies or storage on “x” was blocked because of custom cookie permission. what went wrong? a request to access cookies or storage was blocked because there's a custom user-defined permission set. the permission can be changed or removed by: going to preferences > content blocking > cookies and site data clicking on the manage permissions button and updating the listed
exceptions ...
Blocked: All third-party storage access requests
r storage on “x” was blocked because we are blocking all third-party storage access requests and content blocking is enabled. what went wrong? a request to access cookies or storage was blocked because it came from a third-party (a different origin) and content blocking is enabled. the permission can be changed or removed by: going to preferences > content blocking and either adding an
exception with the manage
exceptions… button choosing the custom content blocking and unchecking the cookies checkbox if the resource that is being blocked doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element. ...
Blocked: Storage access requests from trackers
est to access cookies or storage on “x” was blocked because it came from a tracker and content blocking is enabled. what went wrong? a request to access cookies or storage was blocked because the browser identified it as coming from a tracker and content blocking is enabled. the permission can be changed or removed by: going to preferences > content blocking and either adding an
exception with the manage
exceptions… button choosing the custom content blocking and unchecking the tracker checkbox if the blocked resource doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element. ...
Security best practices for Firefox front-end engineers
anonical truth for the list of whitelisted elements is the source code. the last flag ensures that developers will identify and avoid the problems early on in the development cycle and before shipping the code. linter rules against unsanitized dom interaction the security assurance team maintains an eslint rule that disallows unsafe uses of innerhtml and similar dom apis. the linter makes an
exception for code that uses string literals that are hard coded in the source code, assuming benevolent developers. developers are able to avoid tripping the rule by using escaping functions in combination with template strings, for example: bar.innerhtml = escapehtml`<a href='${url}'>about</a>`; in system-privileged chrome code, any kind of remaining scripts will still be removed by our sanitizer. ...
CSS <display-xul> component
see this firefox site compatibility post for more details. the -moz-box and -moz-inline-box values will be removed later in bug 879275. see this firefox site compatibility post for more details. ...
How to get a stacktrace with WinDbg
a. producing a minidump sometimes the stacktrace alone is not enough information for a developer to figure out what went wrong. a developer may ask you for a "minidump" or a "full memory dump", which are files containing more information about the process. you can easily produce minidumps from windbg and provide them to developers. faq q: i am running windows 7 (32-bit or 64-bit) and i see an
exception in the windbg command window that says 'ntdll32!ldrpdodebuggerbreak+0x2c' or 'ntdll32!ldrpdodebuggerbreak+0x30'. what do i do now? a: if you see 'int 3' after either of those
exceptions, you will need to execute the following commands in windbg. bp ntdll!ldrpdodebuggerbreak+0x30 bp ntdll!ldrpdodebuggerbreak+0x2c eb ntdll!ldrpdodebuggerbreak+0x30 0x90 eb ntdll!ldrpdodebuggerbreak+0x2c 0x90 mak...
Implementing Download Resuming
annel interface. the expected way to use it is this: for all downloads that happen, get the entityid from the channel, and store it for later use. the entity id is what ensures that the file remains unchanged. this can also be used to check whether the download is resumable: if it is not (e.g. the server is not using http 1.1), then accessing this attribute will throw an ns_error_not_resumable
exception. if the download gets interrupted, necko will call the stream listener's onstoprequest method with a failure status. (todo: document what webbrowserpersist/exthandler do). the front-end code can then notify the user of this, and offer to resume the download. resuming a download in order to resume a download, you should create a channel as usual (using nsiioservice). then, you can check if it ...
AsyncShutdown.jsm
managing safe shutdown of asynchronous services. firefox shutdown is composed of phases that take place sequentially. typically, each shutdown phase removes some capabilities from the application. for instance, at the end of phase profilebeforechange, no service is permitted to write to the profile directory (with the
exception of telemetry). consequently, if any service has requested i/o to the profile directory before or during phase profilebeforechange, the system must be informed that these requests need to be completed before the end of phase profilebeforechange. failing to inform the system of this requirement can (and has been known to) cause data loss. example at some point during shutdown, the add-on manager needs to ensure that all add-ons have safely written their data to disk...
DeferredTask.jsm
sk cannot be re-entered while running, but can be executed again after a previous run finished. a common use case occurs when a data structure should be saved into a file every time the data changes, using asynchronous calls, and multiple changes to the data may happen within a short time: let savedeferredtask = new deferredtask(function* () { yield os.file.writeatomic(...); // any uncaught
exception will be reported. }, 2000); // the task is ready, but will not be executed until requested. the "arm" method can be used to start the internal timer that will result in the eventual execution of the task. multiple attempts to arm the timer don't introduce further delays: savedeferredtask.arm(); // the task will be executed in 2 seconds from now. yield waitonesecond(); savedeferredtask.arm()...
Downloads.jsm
rk on downloads that were not started from a private browsing window. private work on downloads that were started from a private browsing window. all work on both downloads.private and downloads.public downloads. properties attribute type description error read only constructor constructor for a downloaderror object. when you catch an
exception during a download, you can use this to verify if ex instanceof downloads.error, before reading the
exception properties with the error details. example (using task.jsm): try { yield downloads.fetch(sourceuri, targetfile); } catch (ex if ex instanceof downloads.error && ex.becausetargetfailed) { console.log("unable to write to the target file, ignoring the error."); } methods ...
OS.File.Error
ile.error, setting the platform-specific error number. error closed() error exists() methods os.file.error.closed() return an error representing the fact that a file is closed. os.file.error.exists() return an error representing the fact that a file exists. instances of os.file.error in case of any i/o error, the functions of os.file raise instances of os.file.error. these
exceptions hold both a human-readable error message detailing the i/o error and attributes to help determining the cause of the error. cross-platform attributes operation the human-readable name of the failed operation. becauseexists true if the operation failed because a file or directory exists, false otherwise. becausenosuchfile true if the operation failed because a ...
PerfMeasurement.jsm
nces uint64 the number of memory accesses that occurred. cache_misses uint64 the number of times memory accesses missed the cache. branch_instructions uint64 the number of branch instructions executed. branch_misses uint64 the number of times branch prediction guessed wrong. bus_cycles uint64 the number of memory bus cycles that elapsed. page_faults uint64 the number of page
exceptions the os handled. major_page_faults uint64 the number of times page faults required disk access. context_switches uint64 the number of context switches that occurred involving the thread being profiled. cpu_migrations uint64 the number of times the profiled thread migrated from one cpu core to another. event types measured constant the eventsmeasured constant provides a mask indicat...
Deferred
either to a value, a rejection, or another promise, this method does nothing. note: this function is bound to its associated promise when promise.defer() is called, and can be called with any value of this. void reject( areason ); parameters areason optional the rejection reason for the associated promise. although the reason can be undefined, it is generally an error object, like in
exception handling. note: this argument should not be a promise. specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. backwards and forwards compatible helper this deferred function can be used for backwards and forwards compatibility, due to a change that took place in firefox 30. function deferred() { // update 062115 f...
Deferred
resolved, either to a value, a rejection, or another promise, this method does nothing. note: this function is exactly same as promise constructor's reject argument, and can be called with any value of this. void reject( areason ); parameters areason optional the rejection reason for the associated promise. although the reason can be undefined, it is generally an error object, like in
exception handling. note: this argument should not be a promise. specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. ...
Sqlite.jsm
sive memory usage. therefore, it's recommended to use onrow with select statements. along with a result row, onrow is passed a cancel function as its second argument. consumers of this api can call the cancel function should they want to immediately abort the execution of the statement. when cancelled, subsequent rows will not be processed and no more onrow invocations will be made. if an
exception is thrown by the onrow handler, the
exception is logged and processing of subsequent rows occurs as if nothing happened. the promise is still resolved (not rejected). the return promise will be rejected with an error instance if the statement did not finish execution fully. the error may have an errors property. if defined, it will be an array of objects describing individual errors. each object...
XPCOMUtils.jsm
function generateci( classinfo ); parameters classinfo an object containing the optional properties interfaces, contractid, classdescription, classid, flags. this parameter should not be the component itself because that would cause a memory leak. return value an nsiclassinfo implementation returning the values of the properties from the classinfo parameter in its various properties.
exceptions thrown this method throws an
exception with the message "in generateci, don't use a component for generating classinfo" if classinfo parameter is an xpcom component. generateqi() generates a queryinterface() function implementation. you need to assign the returned function to the queryinterface property of a javascript object. when the generated method is invoked on that object, it checks to...
Mozilla Content Localized in Your Language
second. percentages how are percentages expressed in your language? digit groups how are digit groups expressed in your language? example: 1.23 (decimal separator) or 1,000 (thousand separator) using comma or period. acronyms do you translate widely accepted acronyms such as cd, dvd, mb? if translated, is there an equavilent acronym and widely accepted in the language? gender are there
exceptions to standard gender conventions within your language? if so, what are they? tone/register what is the appropriate tone for your translations? does it vary by product and target audience? if so, how? what are formality to avoid? list products and their tones if different. capitalization what is the appropriate form of expressing capitalization in your language? note: if this doens't apply, ho...
Localizing with Mozilla Translator
stance, '''toolkit/locales/chrome''' in mozilla-central matches '''locale/en-us''' and '''browser/locales/chrome''' matches '''locale/browser'''. so, what you have to do is export partial glossaries in each link point of the ''old'' product and import them in the corresponding link point of the ''new'' point. your keep original and fuzzy flags will be honored for each string. there will be some
exceptions. files hanging directly from the platform neutral platform can't be part of a partial glossary (because they are not components), and platform neutral itself can't be selected either, since it is not a component, but a platform. for these few files, you will have to export them individually and reimport them. if you are a ''not so good'' mt user, however, you can just create a new product (or s...
What every Mozilla translator should know
of the l10n to follow up your bug you should cc: l10n@mozilla.com if you choose to make changes to your localization, you should make the changes local to your disk, push them to your hg repository on merucial, test the changes on a nightly/tinderbox build, fix any errors if some are found and test again, and send the new changeset id as your "opt-in" revisions to the l10-drivers. there is one
exception to this process. if you choose to make any changes to the productization elements (i.e. search plugins, protocol handlers, rss/live bookmarks), you will need to upload a patch with the suggested changes to bugzilla and get approval before pushing those changes to your hg repository. do the changes in your local disk create a diff file with the changes $ hg diff -p -u 8 filename create a...
Writing localizable code
posite strings are often very difficult to translate. when a composite string is needed, try to give the translators "room to move". an example of a well used composite string is firefox's setting for visited pages: the translator can (implicitly) position the text field as he sees fit. don't use preprocessor macros the use of #if #else #endif or #expand is strongly discouraged. there are few
exceptions to this rule, but in general, the localized file should comply with standards and should not require build tools to be transformed. if you want to add build processing to localized files, be sure to request feedback from l10n@. in most cases, you can just as well put the processing into the content code and reference different key-value pairs in l10n. use a good source directory structure be...
MathML3Testsuite
ults of the mathml 3 full testsuite for presentation mathml. the sections are marked with passed, failed, not-tested or some parts pass, giving the status of trunk builds with the appropriate fonts installed. when the markup is intentionally errorous, the correct behavior is not defined by the recommendation and hence the tests are considered passed if there is no fatal error (crash, etc). this
exception also holds for obsolete features (such as macro, mode etc) or for other undefined behaviors (attribute href for example). note that in general, comparing with the "sample rendering" is not enough to conclude on the success/failure of the test. so please do not edit these pages if you are not able to explain gecko's rendering. however, any report is welcome on the tracking bug for the mathml tests...
Mozilla Port Blocking
ports enabled by protocol handlers in mozilla: protocol handler allowed ports ftp 21, 22 ldap 389, 636 nntp any port pop3 any port imap any port smtp any port finger 79 datetime 13 how...
Mozilla Web Developer FAQ
values are normalized to spaces at parse time, so the original white space never makes it to the dom. this affects data round tripping using hidden form inputs. in versions prior to gecko 1.9/firefox 3, the document is not loaded and rendered incrementally. the layout mode is the (full) standards mode regardless of doctype. css works according to the xml+css rules. html-specific css
exceptions do not apply. for example, the body element gets no special treatment. css selectors are case-sensitive. the dom is in the xml mode. namespace-aware variants of methods need to be used when working with elements (eg. createelementns() instead of createelement()). element and attribute names are not normalized to upper case. other namespaces are supported. mathml ...
Activity Monitor, Battery Status Menu and top
ed on these facts it seems reasonable to assume that “energy impact” is again being used to determine which applications are "using significant energy". testing shows that once an energy-intensive application is started it takes less than a minute for it to show up in the battery status menu. and once the application stops using high amounts of energy it takes a few minutes to disappear. the
exception is when the application is closed, in which case it disappears immediately. and it appears that a program with an “energy impact” of roughly 20 or more will eventually show up as significant, and programs that have much higher “energy impact” values tend to show up more quickly. all of these battery status menu observations are difficult to make reliably and so should be treated with cau...
JS::PerfMeasurement
::cache_misses .cache_misses memory accesses that missed the cache ::branch_instructions .branch_instructions branch instructions executed ::branch_misses .branch_misses branch instructions that were not predicted correctly ::bus_cycles .bus_cycles total memory bus cycles ::page_faults .page_faults total page-fault
exceptions fielded by the os ::major_page_faults .major_page_faults page faults that required disk access ::context_switches .context_switches context switches involving the profiled thread ::cpu_migrations .cpu_migrations migrations of the profiled thread from one cpu core to another these events map directly to "generic events" in the linux 2.6.
Debugging out-of-memory problems
gnose with emscripten is where a big game fails due to an out of memory error (oom) somewhere during load time. by the time about:memory is loaded in a new tab and you have clicked the "measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose. this article explains how to debug such problems. out-of-memory
exceptions from js setting memory.dump_reports_on_oom in about:config to true will cause the browser to automatically write about:memory dumps to a temp file printed to the browser console (note: not web console) when an oom crash is encountered. for more information, see bug 969415. out-of-memory crashes in some cases, running out of memory causes the browser to crash. ideally, memory.dump_reports_on_...
NSPR's Position On Abrupt Thread Termination
events, these resources will be allocated by a thread, used for some period of time, and then freed as the stack unwinds. in these cases, the presence of the data is recorded only on the stack, known only to the single thread (normally referred to as encapsulated). the problem with abrupt termination is that it can happen at any time, to a thread that is coded correctly to handle both normal and
exceptional situations, but will be unable to do so since it will be denied the opportunity to complete execution. it can happen because it called out of its own scope into some lazily implemented library. nspr's answer to this is that there is no abrupt thread termination. all threads must unwind and return from their root function. if they cannot, because of some state corruption, then they must assume t...
Optimizing Applications For NSPR
allenge that was met to a large degree, but there is always room for improvement. the casual client may not encounter a need to know the details of the shortcomings to the level described here, but if and when clients become more sophisticated, these issues will certainly surface. this memo is by no way complete. 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. in the combined (mxn) model, which includes nt, irix (sprocs), and pthreads-user, the primordial thread is always a local thread. therefore, if you call a blocking system call from the primordial thread, it is going to block more...
Monitors
count it had before the wait operation. unlike a mutex of type prlock, a mutex of type prmonitor has a single, implicitly associated condition variable that may be used to facilitate synchronization of threads with the change in state of monitored data. for an introduction to nspr thread synchronization, including locks and condition variables, see introduction to nspr. monitor type with the
exception of pr_newmonitor, which creates a new monitor object, all monitor functions require a pointer to an opaque object of type prmonitor. monitor functions all monitor functions are thread-safe. however, this safety does not extend to protecting the monitor object from deletion. pr_newmonitor creates a new monitor. pr_destroymonitor destroys a monitor object. pr_entermonitor enters the lock ass...
JSS Provider Notes
vernment. sun therefore requires that jar files implementing jce algorithms be digitally signed by an approved organization. netscape has this approval and signs the official builds of jss32.jar. at runtime, the jre automatically verifies this signature whenever a jss class is loaded that implements a jce algorithm. the verification is transparent to the application (unless it fails and throws an
exception). if you are curious, you can verify the signature on the jar file using the jarsigner tool, which is distributed with the jdk. if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature. this means you will not be able to use the jss provider for jce algorithms. you have two choices. use the binary release ...
Mozilla-JSS JCA Provider notes
files implementing jce algorithms be digitally signed by an approved organization. the maintainers of jss, sun, red hat, and mozilla, have this approval and signs the official builds of jss4.jar. at runtime, the jre automatically verifies this signature whenever a jss class is loaded that implements a jce algorithm. the verification is transparent to the application (unless it fails and throws an
exception). if you are curious, you can verify the signature on the jar file using the jarsigner tool, which is distributed with the jdk. if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature. this means you will not be able to use the jss provider for jce algorithms. you have two choices. use the binary release of jss f...
NSS 3.12.6 release notes
ification of an alternate library for sqlite bug 524167: crash in [[@ find_objects_by_template - nsstoken_findcertificatebyissuerandserialnumber] bug 526910: maxresponselength (initialized to pkix_default_max_response_length) is too small for downloading some crls. ...
NSS 3.19.2.1 release notes
issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow
exceptionally large allocations to be reported as successful, without actually allocating the requested memory. this may allow attackers to bypass security checks and obtain control of arbitrary memory. new in nss 3.19.2.1 new functionality no new functionality is introduced in this release. this is a patch release to fix security-relevant bugs. compatibility nss 3.19.2.1 shared libraries are backwar...
NSS 3.19.4 release notes
issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow
exceptionally large allocations to be reported as successful, without actually allocating the requested memory. this may allow attackers to bypass security checks and obtain control of arbitrary memory. new in nss 3.19.4 new functionality no new functionality is introduced in this release. this is a patch release to fix security-relevant bugs. compatibility nss 3.19.4 shared libraries are backward co...
NSS 3.20.1 release notes
issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow
exceptionally large allocations to be reported as successful, without actually allocating the requested memory. this may allow attackers to bypass security checks and obtain control of arbitrary memory. new in nss 3.20.1 new functionality no new functionality is introduced in this release. this is a patch release to fix security-relevant bugs. compatibility nss 3.20.1 shared libraries are backward co...
NSS 3.28.3 release notes
e, and will always set it to ecpoint_undefined. see bug 1340103. compatibility nss 3.28.3 shared libraries are backward compatible with most older nss 3.x shared libraries, but depending on your application, may be incompatible, if you application has been compiled against header files of versions 3.28, 3.28.1, or 3.28.2. a program linked with most older nss 3.x shared libraries (excluding the
exceptions mentioned above), will work with nss 3.28.3 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in nss public functions will remain compatible with future versions of the nss shared libraries. if you had compiled your application against header files of nss 3.28, nss 3.28.1 or nss 3.28.2, it it recommended that...
NSS 3.29.1 release notes
branch has also been released with the identical fixes. compatibility nss 3.29.1 shared libraries are backward compatible with most older nss 3.x shared libraries, but depending on your application, may be incompatible, if you application has been compiled against header files of versions 3.28, 3.28.1, 3.28.2 nss 3.29.1. a program linked with most older nss 3.x shared libraries (excluding the
exceptions mentioned above), will work with nss 3.29.1 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in nss public functions will remain compatible with future versions of the nss shared libraries. if you had compiled your application against header files of nss 3.28, nss 3.28.1, nss 3.28.2 or nss 3.29, it it recomm...
NSS Developer Tutorial
ide, list c++ features that are known to be widely available and compatible. you should limit features to those that appear in both guides. ask on nss-dev@ if you think this is restrictive, or if you wish to prohibit a specific feature. nss c abi backward compatibility functions exported functions cannot be removed. the function prototype of an exported function, cannot be changed, with these
exceptions: a foo * parameter can be changed to const foo *. this change is always safe. sometimes an int parameter can be changed to unsigned int, or an int * parameter can be changed to unsigned int *. whether such a change is safe needs to be reviewed on a case-by-case basis. types structs members of an exported struct, cannot be reordered or removed. under certain circumstances, it i...
PKCS11 Implement
e attributes correctly. token initialization software that you supply should also set these fields. use of key ids the nss associates a key with its certificates by its key id (cka-id). it doesn't matter how the key id is generated, as long as it is unique for the token and maps to a certificate to it associated private key. more than one certificate can point to the same private key. the only
exception to this requirement involves key generation for a new certificate, during which an orphan key waits for a brief time for a matching certificate. the nss uses part of the public key (modulus for rsa, value for dsa) as the key id during this time. nss doesn't require token public keys, but if they exist, nss expects the value of the cka_id attribute to be associated with private key and any related...
Multithreading in Necko
thread safe as most of mozilla (and especially most of gecko) run only on the main/primordial thread. in the future, necko may be made thread safe to support changes to gecko that would put some other processing work on background threads (eg. multithreaded image decoding). however, most necko protocols utilize background threads. background threads are used to manage all i/o operations (with the
exception of few cases). most simple protocol handlers (eg. file, finger, datetime) do not worry about threading issues. the internal i/o interfaces default to proxying all callbacks to the main thread. this keeps simple protocol handlers simple :-) more complex protocol handlers (eg. http, ftp) operate partially on the background threads to improve performance. for example, the http protocol handler has c...
Rhino Debugger
the go button on the toolbar press the f5 key on the keyboard execution will resume until a breakpoint is hit or the script completes. break to stop all running scripts and give control to the debugger you may do any of the following: select the debug->break menu item on the menu bar press the break button on the toolbar press the pause/break key on the keyboard break on
exceptions to give control to the debugger whenever a javascript is
exception is thrown select the debug->break on
exceptions checkbox from the menu bar. whenever a javascript
exception is thrown by a script a message dialog will be displayed and control will be given to the debugger at the location the
exception is raised. break on function enter selecting debug->break on function enter will give con...
Tutorial: Embedding Rhino
string, javascript object, or other values. the tostring method converts any javascript value to a string. exiting the context the code } finally { context.exit(); } exits the context. this removes the association between the context and the current thread and is an essential cleanup action. there should be a call to exit for every call to enter. to make sure that it is called even if an
exception is thrown, it is put into the finally block corresponding to the try block starting after context.enter(). expose java apis using java apis no additional code in the embedding needed! the javascript feature calledliveconnect allows javascript programs to interact with java objects: $ java runscript "java.lang.system.out.println(3)" 3.0 undefined implementing interfaces using rhino, javascr...
Rhino FAQ
g.string, 5); then if you wish to assign the string "hi" to the first element, simply execute stringarray[0] = "hi". creating arrays of primitive types is slightly different: you must use the type field. for example, creating an array of seven ints can be done with the code var intarray = java.lang.reflect.array.newinstance(java.lang.integer.type, 7); when i try to execute a script i get the
exception required security context missing. what's going on? you've likely missed placing the security.properties file in your class path at org.mozilla.javascript.resources. can i use rhino in a web browser? rhino is a library for java use, and not for general web browsers. however, a java-based browser may use rhino with scripts from a page in the same manner that any other java program would. ...
Creating JavaScript tests
one of the other appropriate subdirectories of jit-test/tests. jit-tests run only in the shell. jit-tests do not load extra test functionality automatically. writing a new test file have a look at the existing files and follow what they do. all tests, in both suite, can use the asserteq function. asserteq(v1, v2[, message]) check that v1 and v2 are the same value. if they're not, throw an
exception (which will cause the test to fail). if you are writing a jstests, additional testing functionality is provided for you in shell.js files. you can read about them here. performance testing and general advice do not attempt to test the performance of engine features in the test suite. please keep in mind that the javascript test suite is run on a wide variety of wildly varying hardware plafor...
GC Rooting Guide
*> autoscriptvector if your case is not covered by one of these, it is possible to write your own by deriving from js::customautorooter and overriding the virtual trace() method. the implementation should trace all the gc things contained in the object by calling js::traceedge. gc things on the heap js::heap<t> gc thing pointers on the heap must be wrapped in a js::heap<t>. the only
exception to this is if they are added as roots with the js::persistentrooted class, but don't do this unless it's really necessary. js::heap<t> pointers must also continue to be traced in the normal way, which is covered below. js::heap<t> doesn't require a jscontext*, and can be constructed with or without an initial value parameter. like the other template classes, it functions as if it were the gc t...
SpiderMonkey Internals: Thread Safety
in which js objects live. they can't travel to other jscompartments. crucially, any given compartment may only be accessed by one thread at a time. this means that objects cannot be shared across compartments. all js code and most jsapi calls run within a jscontext. the jscontext can be thought of as a machine that knows how to run javascript code, or as an abstraction of the notion of a thread.
exception handling, for example, is per-jscontext. each jscontext must be used by only one thread at a time. a single jscontext can run work with code and objects in multiple compartments as long as no other thread is accessing those compartments. objects may be shared among jscontexts within a jscompartment. there's no fixed association between an object and a context. thread-safety in spidermonkey is tur...
Self-hosted builtins in SpiderMonkey
be installed as the host object's method foreach. making jsnatives available to self-hosted code for a jsnative to be available to self-hosted code, add it to the intrinsic_functions jsfunctionspec array in selfhosting.cpp. debugging self-hosted code self-hosted code by default is hidden from client javascript code; in particular, self-hosted frames will be filtered out of the stack traces of
exceptions. to include self-hosted frames in stack traces (in debug builds only), set the environment variable moz_show_all_js_frames. ...
SpiderMonkey Internals
booleans, dates, functions, numbers, and strings are implemented using the js api. most are jsfastnatives. most string methods are customized to accept a primitive string as the this argument. (otherwise, spidermonkey converts primitive values to objects before invoking their methods, per ecma 262-3 §11.2.1.) error handling spidermonkey has two interdependent error-handling systems: javascript
exceptions (which are not implemented with, or even compatible with, any kind of native c/c++
exception handling) and error reporting. in general, both functions inside spidermonkey and jsapi callback functions signal errors by calling js_reporterror or one of its variants, or js_setpending
exception, and returning js_false or null. public apis the public c/c++ interface, called the jsapi, is in most plac...
JS::CreateError
ame, uint32_t linenumber, uint32_t columnnumber, jserrorreport *report, handlestring message, mutablehandlevalue rval); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. type jsexntype the
exception's type. stack js::handlestring or js::handleobject the value of error.prototype.stack. filename js::handlestring the value of error.prototype.filename. linenumber uint32_t the value of error.prototype.linenumber. columnnumber uint32_t the value of error.prototype.columnnumber. report jserrorreport * a pointer to jserrorrep...
JS::OrdinaryToPrimitive
ev 28 (2014 oct 14) 7.1.1, second algorithm. most users should not call this -- use js::tonumber, js::toboolean, or js::tostring instead. this should only be called from custom convert hooks. it implements the default conversion behavior shared by most objects in js, so it's useful as a fallback. on success, js::ordinarytoprimitive stores the converted value in *vp and returns true. on error or
exception, it returns false, and the value left in *vp is undefined. see also mxr id search for js::ordinarytoprimitive js::tonumber js::toboolean js::tostring bug 1103152 ...
JS::SetOutOfMemoryCallback
data parameter which will be passed to js::outofmemorycallback. added in spidermonkey 38 callback syntax typedef void (* outofmemorycallback)(jscontext *cx, void *data); name type description data void * data parameter passed to js::setoutofmemorycallback. added in spidermonkey 38 description unlike the error reporter, which is only called if the
exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called immediately at the oom site to allow the embedding to capture the current state of heap allocation before anything is freed. if the large-allocation-failure callback is called at all (not all allocation sites call the large-allocation-failure callback on failure), it is called before the out-of-memory callback; the out...
JS::ToInt32
v js::handlevalue the value to convert. out int32_t * out parameter. on success, *out receives the converted floating-point value. description js::toint32 converts a javascript value to a signed 32bit integer. it implements the toint32 operator described in ecma 262-3 §9.5. on success, js::toint32 stores the converted value in *out and returns true. on error or
exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::toint32 bug 739541 ...
JS::ToInt64
afe build, the caller must be in a request on this jscontext. v js::handlevalue the value to convert. out int64_t * out parameter. on success, *out receives the converted floating-point value. description js::toint64 converts a javascript value to a signed 64bit integer. on success, js::toint64 stores the converted value in *out and returns true. on error or
exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::toint64 bug 742188 ...
JS::ToNumber
ontext. v js::handlevalue the value to convert. out double * out parameter. on success, *out receives the converted floating-point value. description js::tonumber converts a javascript value to a number. it implements the tonumber operator described in ecma 262-3 §9.3. on success, js::tonumber stores the converted value in *out and returns true. on error or
exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::tonumber bug 739541 ...
JS::ToPrimitive
ing type as a hint, or jstype_void to pass no hint. do not pass any other type. vp js::mutablehandleobject out parameter. on success, *vp receives the converted value. description js::toprimitive converts a javascript object, obj, to a primitive value using ecmascript 6 toprimitive. on success, js::toprimitive stores the converted value in *vp and returns true. on error or
exception, it returns false, and the value left in *vp is undefined. see also mxr id search for js::toprimitive js::getfirstargumentastypehint js_defaultvalue -- old name of this function bug 1054756 - added ...
JS::ToString
. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handlevalue the value to convert. description js::tostring returns a string representation of a javascript value. if v.isstring() is true, it calls v.tostring(). otherwise, it converts the value to string. on success, js::tostring returns a jsstring instance. on error or
exception, it returns nullptr. see also mxr id search for js::tostring bug 933834 ...
JS::ToUint16
v js::handlevalue the value to convert. out uint16_t * out parameter. on success, *out receives the converted floating-point value. description js::toint16 converts a javascript value to an unsigned 16bit integer. it implements the toint16 operator described in ecma 262-3 §9.7. on success, js::toint16 stores the converted value in *out and returns true. on error or
exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::touint16 bug 779601 ...
JS::ToUint32
js::handlevalue the value to convert. out int32_t * out parameter. on success, *out receives the converted floating-point value. description js::touint32 converts a javascript value to an unsigned 32bit integer. it implements the touint32 operator described in ecma 262-3 §9.5. on success, js::touint32 stores the converted value in *out and returns true. on error or
exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::touint32 bug 739541 ...
JS::ToUint64
build, the caller must be in a request on this jscontext. v js::handlevalue the value to convert. out uint64_t * out parameter. on success, *out receives the converted floating-point value. description js::toint64 converts a javascript value to an unsigned 64bit integer. on success, js::toint64 stores the converted value in *out and returns true. on error or
exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::touint64 bug 742188 ...
JS::Value
presentations are visible using the separate int32/double methods but do not affect observable semantics (ignoring performance). the number mutators attempt to use int32_t representation for compatible input values, returning true when int32 could be used and false when double representation was required. any double value may be stored in a js::value, in one of these two representations. the only
exception is that only a single nan value can be represented. (note that both -0 and +0 are allowed, and the latter may sometimes be stored using the int32_t representation.) js::value further provides these methods combining various aspects of the above methods: js::objectornullvalue(jsobject*) returns an object value corresponding to the given non-null pointer, or a null value if the pointer is null.
JSBool
is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. every instance of jsbool has been replaced by bool. js_true has been replaced by just true and in the same way js_false by false. jsbool is the return type of many jsapi functions and callbacks. js_true indicates success; js_false indicates an error or
exception occurred. jsbool is an integer type. js_true is (jsbool) 1 and js_false is (jsbool) 0. these values must not be used as jsvals. instead, use jsval_true and jsval_false, and use boolean_to_jsval and jsval_to_boolean to convert. ...
JSCheckAccessOp
he object whose properties are being accessed. id jsval the name or index of the property being accessed. mode jsaccessmode the type of access being checked. vp jsval * out parameter. on success, the callback must set *vp to the stored value of the property. description check whether obj[id] may be accessed per mode, returning js_false on error/
exception, js_true on success with obj[id]'s stored value in *vp. as for jspropertyop, id is either a string or an int jsval. jscheckaccessop implementations generally work by using jsdbgapi functions such as js_frameiterator and js_stackframeprincipals to obtain the principals of the code attempting the checked operation, then examining those principals and comparing them with the system's security polic...
JSDeletePropertyOp
rtyop callback is a hook that applications may install to be called at some point during property access. a jsdeletepropertyop may be installed on a jsclass to hook property deletes. if a jsdeletepropertyop does nothing and returns true, then property delete is unaffected. it proceeds as normal. this callback may veto the ongoing property operation by optionally reporting an error or raising an
exception and then returning false. the operation then fails, and the error is propagated to the caller. otherwise the callback must return true, and the property operation proceeds. jsclass hooks jsclass offers the following hook: jsclass.delproperty is called during most property deletions, even when obj has no property named id. if an error occurred, return false as per normal jsapi error pra...
JSExnType
value prototype in javascript jsexn_none an unthrowable error. (lower bound) jsexn_err error jsexn_internalerr internalerror jsexn_evalerr evalerror jsexn_rangeerr rangeerror jsexn_referenceerr referenceerror jsexn_syntaxerr syntaxerror jsexn_typeerr typeerror jsexn_urierr urierror jsexn_limit (upper bound) description these types are part of a jserrorformatstring structure. they define which error to throw in case of a runtime error. jsexn_none marks an unthrowable error. ...
JSExtendedClass.wrappedObject
a string that contains the name of the wrapped object's class rather than the wrapper's class. in typeof expressions and in js_typeofvalue, the type of the wrapped object is returned. (the result may be "object", "function", or "xml".) when assigning to __proto__ or __parent__ from script, the javascript engine checks to see if the assignment would produce a cycle. if so, it fails with an
exception. when walking the chain to do this check, wrappers are automatically unwrapped. a wrapper object is strictly equal to the object it wraps, in the sense of === and !==. two wrapper objects that wrap the same object are also strictly equal. object.prototype.eval unwraps. a wrapper object that wraps an array is considered an array for the purpose of array.prototype.concat and array.conca...
JSFastNative
ly in the return-value slot. js_set_rval(cx, vp, value) sets the return value of the native function. it is safe to call this multiple times within a single call to a jsfastnative. if the jsfastnative returns js_true, the last value passed to this macro will be returned to the caller. on success, the callback must call js_set_rval (at least once) and return js_true. on error or
exception, it must return js_false. to create a jsfunctionspec that points to a jsfastnative, use js_fn. when a jsfastnative is called, no jsstackframe is generated. this is what makes a fast native fast. however, it causes the function not to appear on the stack in javascript debuggers. it also means that applications that use spidermonkey's security features, particularly those that implement jschecka...
JSHasInstanceOp
ich the type check is occurring. obj js::handleobject the "type" in the type check. v js::mutablehandlevalue the value whose type is being checked. bp bool * out parameter. on success, the callback stores the result of the type check in *bp. description jshasinstanceop is called to check whether v is an instance of obj. return false on error or
exception, true on success with true in *bp if v is an instance of obj, false in *bp otherwise. jsclass hooks jsclass offers the following hook: the jsclass.hasinstance callback implements js_hasinstance and the javascript instanceof keyword. see also mxr id search for jshasinstanceop jsclass js_hasinstance ...
JSID_VOID
an additional jsid which is used to indicate the absence of a valid jsid. syntax const jsid jsid_void; const js::handleid jsid_voidhandle; // added in spidermonkey 31 description jsid_void does not occur in js scripts but may be used to indicate the absence of a valid jsid. a void jsid is not a valid id and only arises as an
exceptional api return value, such as in js_nextproperty. embeddings must not pass jsid_void into jsapi entry points expecting a jsid and do not need to handle jsid_void in hooks receiving a jsid except when explicitly noted in the api contract. jsid_voidhandle is the handle to the jsid which value is jsid_void. see also mxr id search for jsid_void mxr id search for jsid_voidhandle bug 912411 ...
JSIteratorOp
should take place. obj jsobject * pointer to the object to iterate over. keysonly jsbool if true, the iterator should yield keys only, not [key, value] pairs. description the javascript engine calls the jsextendedclass.iteratorobject callback to create an iterator object for a given object. the callback should return an iterator object or null if an error or
exception occurred on cx. see also bug 909178 ...
JSObjectOp
obsolete since javascript 1.8.5this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. 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.defaultValue
behavior for ordinary objects is as described in es5 §8.12.8. it calls the javascript methods obj.valueof() and/or obj.tostring(). provide a custom jsobjectops.defaultvalue callback to implement customized [[defaultvalue]] behavior. the jsclass.convert callback should convert obj to the given type, returning js_true with the resulting value in *vp on success, and returning js_false on error or
exception. on success, *vp must be a primitive value: per es5 §8.12.8, every object "must ensure that its [[defaultvalue]] internal method can return only primitive values." debug builds of spidermonkey will assert if a convert callback is successful but leaves *vp holding a primitive value. js_convertstub implements the default behavior for the jsclass.convert hook, which is to call obj.valueof() and ob...
JSObjectOps.getAttributes
re being accessed. id jsid the name or index of the property whose attributes are being accessed. prop jsproperty * the property whose attributes are being accessed. this may be null. attrsp unsigned int * in/out parameter. see the description section below. description get or set attributes of the property obj[id]. returns js_false on error or
exception, else js_true with current attributes in *attrsp. if prop is non-null, it must come from the *propp out parameter of a prior jsobjectops.defineproperty or jsobjectops.lookupproperty call. for more information on property attributes, see js_getpropertyattributes. ...
JSObjectOps.getProperty
e description cx jscontext * pointer to the js context in which the property access is happening. obj jsobject * the object to be accessed. id jsid the name or index of the property to access. vp jsval * in/out parameter. see the description section below. description get, set, or delete obj[id], returning js_false on error or
exception, js_true on success. if getting or setting, the new value is returned in *vp on success. if deleting without error, *vp will be jsval_false if obj[id] is permanent, and jsval_true if id named a direct property of obj that was in fact deleted, or if id names no direct property of obj (id could name a property of a prototype, or no property in obj or its prototype chain). this reflects the quirky ...
JSObjectOps.lookupProperty
p. objp jsobject ** out parameter. if the property is found, the callback stores the object on which the property was found in *objp. propp jsproperty ** out parameter. on success, the callback stores in *propp a pointer to the property, if it exists, or null if it doesn't. description look for id in obj and its prototype chain, returning js_false on error or
exception, js_true on success. on success, return null in *propp if id was not found. if id was found, return the first object searching from obj along its prototype chain in which id names a direct property in *objp, and return a non-null, opaque property pointer in *propp. if jslookuppropop succeeds and returns with *propp non-null, that pointer may be passed as the prop parameter to a jsattributesop, a...
JSObjectPrincipalsFinder
cipals finder callback is a key security feature. the callback returns a pointer to the principals associated with obj, possibly via the immutable parent chain leading from obj to a top-level container (such as a window object in the dom). if there are no principals associated with obj, return null. therefore null does not mean an error was reported; in no event should an error be reported or an
exception be thrown by this callback's implementation. the callback should not call jsprincipals_hold. see also bug 784551 ...
JSPropertyOp
r it may be installed on a jsclass to hook property gets, sets, or adds. these different cases are described in more detail in the sections below. if a jspropertyop or jsstrictpropertyop does nothing and returns true, then property get, set, or add is unaffected. it proceeds as normal. each of these callbacks may veto the ongoing property operation by optionally reporting an error or raising an
exception and then returning false. the operation then fails, and the error is propagated to the caller. otherwise the callback must return true, and the property operation proceeds. getters and setters when a jsapi application creates a property on an object (for example, using js_defineproperty or js_defineproperties) it can specify getter and setter callbacks for the new property. getters. the getter...
JSRuntime
stance of the javascript engine. a program typically has only one jsruntime, even if it has many threads. the jsruntime is the universe in which javascript objects live; they can't travel to other jsruntimes. all javascript code and most jsapi calls run within a jscontext. the jscontext is a child of the jsruntime. a context can run scripts. it contains the global object and the execution stack.
exception handling, error reporting, and some language options are per-jscontext. once created, a context can be used any number of times for different scripts or jsapi queries. for example, a browser might create a separate context for each html page; every script in the page could use the same context. objects may be shared among jscontexts within a jsruntime. there's no fixed association between an obj...
JSTraceOp
unction 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. jstraceop implementation can assume that no other threads mutates object state. it must not change state of the object or corresponding native structures. the only
exception for this rule is the case when the embedding needs a tight integration with gc. 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 tracea...
JS_AlreadyHasOwnProperty
dp is set to true only if lookupproperty reports that the property was found on obj itself and not on some other object (even the corresponding outer object, if any). if the property is found on obj, this sets *foundp to true and returns true. if the property is not found on obj, this sets *foundp to false and returns true (to indicate that no error occurred). if the search fails with an error or
exception, this returns false. see also mxr id search for js_alreadyhasownproperty mxr id search for js_alreadyhasownucproperty mxr id search for js_alreadyhasownpropertybyid mxr id search for js_alreadyhasownelement bug 400793 bug 461163 ...
JS_CheckAccess
, then it is called to perform the check. otherwise, if a runtime-wide check-object-access callback has been installed by calling js_setcheckobjectaccesscallback, then that is called to perform the check. otherwise, access is granted. on success, js_checkaccess returns js_true, *vp is set to the current value of the specified property, and *attrsp is set to the property's attributes. on error or
exception, including if access is denied, js_checkaccess returns js_false, and the values left in *vp and *attrsp are undefined. mxr id search for js_checkaccess ...
JS_CompileFunction
mpilation. similarly, lineno is used to report the line number where an error occurred during compilation. if both obj and name are non-null, the new function becomes a method of obj. (a new property is defined on obj with the given name and the new function object as its value.) on success, js_compilefunction and js_compileucfunction return a pointer to the newly compiled function. on error or
exception, they return null. 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_setbranchcallback js_valuetofunction bug 1089026 ...
JS_CompileFunctionForPrincipals
is the name of the file (or url) containing the function. this information is passed in messages if an error occurs during compilation. similarly, lineno is used to report the line number of the function or file where an error occurred during compilation. on success, js_compilefunctionforprincipals and js_compileucfunctionforprincipals return a pointer to the newly compiled function. on error or
exception, they return null. 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_valuetofunctio...
JS_CompileScriptForPrincipals
ilename is the name of the file (or url) containing the script. this information is included in error messages if an error occurs during compilation. similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. on success, js_compilescriptforprincipals and js_compileucscriptforprincipals return a pointer to the compiled script. on error or
exception, they return null. 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. warning: this api is subject to bug 438633, which can cause crashes in almost any program that uses js_destroyscript(). the workaround is to u...
JS_ConvertValue
tion object that has not been stripped of its lexical scope. it is safe to call the result (e.g. using js_callfunctionvalue). converting to jstype_string works like js::tostring. converting to jstype_number works exactly like js::tonumber. converting to jstype_boolean works exactly like js::toboolean. on success, js_convertvalue stores the converted value in *vp and returns true. on error or
exception, it returns false, and the value left in *vp is undefined. see also mxr id search for js_convertvalue js_convertarguments js_gettypename js_typeofvalue bug 1125784 ...
JS_DefaultValue
cts). objects with a custom jsclass specified by the embedder will invoke that class's convert hook, which must convert the object to a primitive value, to determine the primitive result of conversion. behavior when the convert hook is js_convertstub is identical to that for objects defined by ecmascript. on success, js_defaultvalue stores the converted value in *vp and returns true. on error or
exception, it returns false, and the value left in *vp is undefined. see also mxr id search for js_defaultvalue js::toprimitive bug 1054756 - renamed to js::toprimitive ...
JS_DefineFunction
be exposed to javascript. nargs indicates the number of arguments the function expects to receive. this becomes the new function object's length property and can be accessed using js_getfunctionarity. flags is the logical or of zero or more property attributes, which apply to the new property. on success, js_definefunction and js_defineucfunction return a pointer to the new function. on error or
exception, they return null. see also mxr id search for js_definefunction mxr id search for js_defineucfunction mxr id search for js_definefunctionbyid js_callfunctionname js_callfunctionvalue js_compilefunction js_definefunctions js_defineobject js_defineproperties js_defineproperty js_getfunctionobject js_newfunction bug 607695 - added js_definefunctionbyid ...
JS_DefineFunctions
ain 0 values. (the macro js_fs_end can be used for the last element.) js_definefunctions creates one function for each non-zero element in the array. propertydefinitionbehavior is used to select if properties with jsprop_define_late flag should be defined on the object. normal jsapi consumers probably always want defineallproperties here. on success, js_definefunctions returns true. on error or
exception, it stops defining functions and returns false. see also mxr id search for js_definefunctions js_callfunctionname js_defineobject js_defineproperties js_newfunction bug 959787 - make fs type to const bug 825199 - added propertydefinitionbehavior ...
JS_DefineObject
operty of an existing object, obj. name is the property name to assign to obj to hold the new object, and flags contains the property attributes to set for the newly created property. the new object's parent is obj. js_defineobject does not call clasp->constructor. initialization of the new object is up to the caller. on success, js_defineobject returns a pointer to the new object. on error or
exception (if the object cannot be created, the property already exists, or the property cannot be created), js_defineobject returns null. this function combines two operations: creating an object and storing it in a property of another object. use js_constructobject, js_constructobjectwitharguments, or js_newobject to create a new object without storing it in a property of another object. use js_definepr...
JS_DeleteProperty
r. otherwise obj has a non-permanent own property with the given name or id. in this case, obj's jsclass.delproperty hook is called. if the hook returns false, the error is propagated. otherwise, if obj is not configurable, an error is raised. otherwise, the property is removed. these functions return true on success, regardless of whether a property was actually deleted, and false on error or
exception. (in javascript 1.2 and earlier, attempting to delete a permanent property caused an error. there is no longer any way to get this behavior.) internally, property deletion is implemented by the jsobjectops.deleteproperty callback. to remove all properties from an object, call js_clearscope. see also mxr id search for js_deleteproperty mxr id search for js_deletepropertybyid js_deleteprop...
JS_DeleteProperty2
n this case, *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded). if the hook returns false, the error is propagated. otherwise, if obj is not configurable, an error is raised. otherwise, *succeeded receives true and the property is removed. these functions return true on success, regardless of whether a property was actually deleted. on error or
exception, the return value is false, and the value left in *succeeded is unspecified. jsobjectops.deleteproperty implements this behavior. (in javascript 1.2 and earlier, attempting to delete a permanent property caused an error. there is no longer any way to get this behavior.) to remove all properties from an object, call js_clearscope. see also mxr id search for js_deleteproperty2 mxr id search...
JS_Enumerate
inherited from the object's prototype.) this is not quite the same behavior as a javascript for...in loop, which converts all property ids to strings and also enumerates inherited properties. this calls obj's jsclass.enumerate hook. on success, js_enumerate returns a pointer to the first element of an array of property ids. the application must free this array using js_destroyidarray. on error or
exception, js_enumerate returns null. the property ids in the returned jsidarray are subject to garbage collection. as long as obj is reachable, its current property ids are reachable. 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. the property ids would then become unreachable and c...
JS_ForwardGetPropertyTo
s_forwardgetpropertyto is the base implementation of js_getproperty, js_getucproperty, js_getpropertybyid etc, where onbehalfof is same to obj. onbehalfof is receiver in [[get]] internal method of proxy, defined in es2015 draft spec (rev 29, 9.5.8). on success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and return true. on an error or
exception, these functions return false, and the value left in *vp is undefined. see also mxr id search for js_forwardgetpropertyto js_getproperty bug 698551 ...
JS_GetElement
e of the element, if it exists, and undefined otherwise. description js_getelement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_getelement sets *vp to the element's current value. if not, it sets *vp to undefined and returns true (to indicate no error occurred). if the search fails with an error or
exception, js_getelement returns false, and the value left in *vp is undefined. see also mxr id search for js_getelement js_defineelement js_deleteelement js_getarraylength js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_GetProperty
getter does nothing and returns true, so the property get succeeds and the property's stored value is left in *vp. internally, property retrieval, including all the behavior described above, is implemented by obj's jsobjectops.getproperty callback. on success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and return true. on an error or
exception, these functions return false, and the value left in *vp is undefined. see also mxr id search for js_getproperty mxr id search for js_getucproperty mxr id search for js_getpropertybyid example in the jsapi phrasebook js_defineproperty js_definepropertywithtinyid js_deleteproperty js_deleteproperty2 js_lookupproperty js_propertystub js_setproperty bug 461163 ...
JS_GetPropertyDefault
out parameter. on success, *vp receives the current value of the property, or undefined if no such property is found. description js_getpropertydefault examines a specified js object obj and its prototype chain for a property with the specified name. on success, these functions set *vp to the current value of the property, or def if obj has no such property, and return true. on an error or
exception, these functions return false, and the value left in *vp is undefined. see also bug 905774 ...
JS_GetPrototype
ototype. protop js::mutablehandleobject out parameter. if successful, receives prototype object of obj. description js_getprototype retrieves the prototype of a specified object, obj. a prototype object provides properties inherited by similar js objects. this is the equivalent of object.getprototypeof(obj) from javascript. if js_getprototype returns false, that signals an
exception, which should be handled as usual. otherwise, it stores a pointer to the prototype or null to *protop and returns true. to set an object's prototype, use js_setprototype. see also mxr id search for js_getprototype js_setprototype ...
JS_HasArrayLength
ength returns js_true, and *lengthp receives the current value of the length property. on failure, js_hasarraylength returns js_false, and the value left in *lengthp is undefined. this function differs from js_getarraylength in the treatment of errors and unusual cases, like when an object's length is negative or not a number. this function may return js_false without having reported any error or
exception. see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement bug 657298 ...
JS_HasElement
out parameter. on success, it stores true to *foundp, false otherwise. description js_haselement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_haselement sets *foundp to true. if not, it sets *foundp to false and returns true (to indicate no error occurred). if the search fails with an error or
exception, js_haselement returns false, and the value left in *foundp is undefined. see also mxr id search for js_haselement js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_HasInstance
alue> the value to test. bp bool * out parameter. on success, *bp receives the result of the test. description js_hasinstance determines if a specified js value, v, is an instance of js object, obj. this function is equivalent to v instanceof obj test in javascript. on success, js_hasinstance stores the result of the instanceof test in *bp and returns true. on error or
exception, it returns false, and the value left in *bp is undefined. when providing a prototype as obj, the prototype's jsclass must have its hasinstance method set. otherwise js_hasinstance returns false. see also mxr id search for js_hasinstance js_instanceof ...
JS_IsStopIteration
syntax // added in spidermonkey 42 bool js_isstopiteration(js::value v); // obsolete since spidermonkey 42 bool js_isstopiteration(jsval v); name type description v js::value the value to check. description js_isstopiteration returns true if v is stopiteration, otherwise false. ...
JS_LookupElement
vior: see ecma 262-3 §11.2.1, step 6. so any call to js_lookupelement is equivalent to a call to js_lookupproperty passing a numeric string for the name. if the property obj[index] exists, js_lookupelement sets *vp to the property's stored value and returns true. if no such property exists, js_lookupelement sets *vp to undefined and returns true (to indicate that no error occurred). on error or
exception, js_lookupelement returns false, and the value left in *vp is undefined. js_lookupelement does not distinguish between a property with a value of undefined and a property that does not exist. see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_newarrayobject js_setarraylength js_setelement bug 1094176 ...
JS_LookupProperty
l have similar behavior: the search starts with obj and proceeds along the prototype chain. if the property is found, *vp receives the property's stored value, or true if the property has no stored value; and the return value is true. if neither obj nor any of its prototypes have such a property, *vp receives undefined and the return value is true (to indicate no error occurred). on error or
exception (such as running out of memory during the search), the return value is false, and the value left in *vp is undefined. there is no way to tell the difference between not finding any property and finding a property whose value is undefined. sorry. use js_getpropertydescriptorbyid instead. js_lookupucproperty is the unicode version of js_lookupproperty. flags js_lookuppropertywithflags and js_look...
JS_NewObjectForConstructor
tion js_newobjectforconstructor creates a new object exactly as the given constructor would if invoked with new. this function does not run the code of the constructor function--it just creates the object. if the constructor argument is not an object jsval, this function will assert (in debug builds). if the constructor does not have a prototype property, this function will return null and set an
exception on cx. the standard object creation api, js_newobject, takes explicit arguments for the class, prototype, and parent of the new object. with js_newobjectforconstructor, the prototype and parent are determined by the constructor, and class is still determined by the caller. the prototype is the prototype of the constructor if it is an object, otherwise null. the parent is the constructor's parent.
JS_NewUCString
of the function. the character array, buf, must be allocated on the heap using js_malloc. on success, the javascript engine adopts responsibility for memory management of this region. the application must not read, write, or free the buffer. this allows the javascript engine to avoid needless data copying. on success, js_newstring and js_newucstring return a pointer to the new string. on error or
exception, they return null. see also js_convertvalue js_getemptystringvalue js_getstringbytes js_getstringchars js_getstringlength js_internstring js_internucstring js_internucstringn js_newstringcopyn js_newstringcopyz js_newucstringcopyn js_newucstringcopyz js_valuetostring bug 618262 - removed js_newstring ...
JS_PushArguments
null), and a boolean. on success, js_pusharguments fills in the supplied markp pointer and returns a pointer to the first element of an array of jsval which are automatically rooted as necessary (protected from the gc temporarily). the application must call js_poparguments using the supplied markp stack pointer when done with this stack frame, to free the memory and unroot the jsvals. on error or
exception, js_pusharguments returns null. to perform the opposite conversion, converting an array of jsvals to various native c types, use js_convertarguments. see also js_poparguments bug 542091 ...
JS_SetBranchCallback
n an active request on cx. the callback does not need to call js_beginrequest()). script jsscript the script that is running. this is guaranteed to be non-null, unless the jsoption_native_branch_callback option has been enabled for the context cx using js_setoptions(). if the callback returns js_true, the js engine continues to execute the script. if the callback raises an
exception using js_setpending
exception() and returns js_false, then the javascript engine propagates the
exception to the script that was executing at the time. if the callback returns js_false without raising an
exception, then the javascript engine immediately stops running the script with an uncatchable error. the engine does not execute finally blocks in this case; this is the same behavior as any nat...
JS_SetElement
ue in/out parameter. *vp is the value to assign to the element. js_setelement ordinarily leaves *vp unchanged, but a jsclass.addproperty hook or non-default setter may modify it. obsolete since jsapi 29 description js_setelement assigns a value to a numeric property of an object. it behaves like the javascript expression obj[index] = v. on success, js_setelement returns true. on error or
exception, js_setelement returns false. obsolete since jsapi 29 on success, js_setelement returns true and the value left in *vp is left unchanged unless an addproperty hook or setter modified it. on error or
exception, js_setelement returns false and the value left in *vp is unspecified. see also mxr id search for js_setelement bug 963167 - added v ...
JS_SetErrorReporter
ou define should log the error where appropriate (such as to a log file), and display an error to the user of your application. the error you log and display can make use of the information passed about the error condition in the jserrorreport structure. the error reporter callback must not reenter the jsapi. like all other spidermonkey callbacks, the error reporter callback must not throw a c++
exception. note that js_seterrorreporter has no facility to directly pass a user data pointer to the error reporting function. you can work around this by using the js_setruntimeprivate and js_getruntimeprivate methods. example code with error handling omitted: class myrequest { public: void execute() { auto rt = js_newruntime(memlimit); js_setruntimeprivate(rt, this); ...
JS_SetOptions
r id search for jsoption_moar_xml jsoption_native_branch_callback the branch callback set by js_setbranchcallback may be called with a null script parameter, by native code that loops intensively. mxr id search for jsoption_native_branch_callback jsoption_dont_report_uncaught when returning from the outermost api call, prevent uncaught
exceptions from being converted to error reports. mxr id search for jsoption_dont_report_uncaught jsoption_relimit added in spidermonkey 1.8 throw an
exception if a regular expression backtracks more than n3 times, where n is the length of the input string. mxr id search for jsoption_relimit jsoption_anonfunfix added in spidermonkey 1.8 disallow ...
JS_SetParent
ipt, the object's parent must not change. the javascript engine relies on this invariant. js_setparent has no way to check that this is the case, but nonetheless, applications must not call js_setparent on an object that has already been exposed to a script. if an application does this, the behavior is undefined. on success, js_setparent returns js_true. otherwise, it reports an error or sets an
exception and returns js_false. see also mxr id search for js_setparent bug 1136980 - removed ...
JS_SetProperty
e, if it has a javascript getter, then an error is reported; otherwise the property's setter is called, passing the arguments (cx, obj, id, &v). if the setter succeeds and the property has a stored value, then the value left in v becomes the stored value of the property. on success, js_setproperty returns true, and the value in v is left unchanged unless a hook or setter modified it. on error or
exception, it returns false, and the value left in v is unspecified. internally, property assignment, including all the behavior described above, is implemented by obj's jsobjectops.setproperty callback. see also mxr id search for js_setproperty mxr id search for js_setucproperty mxr id search for js_setpropertybyid bug 461163 ...
JS_ThrowStopIteration
this article covers features introduced in spidermonkey js1.8 throw a stopiteration
exception. syntax bool js_throwstopiteration(jscontext *cx); name type description cx jscontext * the context in which to throw the stopiteration object. description js_throwstopiteration throws the appropriate stopiteration object for the function currently executing in cx. 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 .next method may throw stopiteration when there are no more values left to iterate. the engine automatically catches the
exception and exits the loop. jsclass.enumerate offers a simpler way to customize object iter...
JS_ValueToBoolean
v jsval the value to convert. bp jsbool * out parameter. on success, *bp receives the converted boolean value. description js_valuetoboolean converts a specified javascript value, v, to a boolean value. it implements the toboolean operator specified in ecma 262-3 §9.2. on success, js_valuetoboolean stores the converted value in *bp and returns js_true. on error or
exception, it returns js_false, and the value left in *bp is undefined. for versions greater than jsversion_1_2, all objects convert to js_true, even boolean wrapper objects like the one produced by new boolean(false). this is the behavior specified in ecma 262-3 §9.2. see related discussion on google groups. see also mxr id search for js_valuetoboolean js::toboolean bug 934557 ...
JS_ValueToECMAInt32
e touint16 operator specified in ecma 262-3 9.7. all three functions first convert v to a floating-point number as if by calling js_valuetonumber; nan values are then converted to zero. if that succeeds, the result is then converted to the target integer type. this second conversion cannot fail. on success, js_valuetoecmaint32 stores the converted value in *ip and returns js_true. on error or
exception, it returns js_false, and the value left in *ip is undefined. see also js::touint16 js::toint32 js::touint32 js::toint64 js::touint64 js::tonumber bug 933810 bug 933946 ...
JS_ValueToFunction
s reported and js_valuetofunction returns null. otherwise, v is an object. the javascript engine attempts to convert it to a function. (implementation note: the actual conversion is performed by the object itself. the object's jsobjectops.defaultvalue method is called with hint=jstype_function.) js_valuetofunction returns a pointer to the converted function. if conversion fails with an error or
exception, js_valuetofunction returns null. see also mxr id search for js_valuetofunction mxr id search for js_valuetoconstructor ...
JS_ValueToInt32
648 to 2147483647). first it converts v to a floating-point number as if by calling js::tonumber. if the result is nan, an infinity, or a number outside the 32-bit range, js_valuetoint32 reports an error and conversion fails. otherwise, the floating-point number is rounded to the nearest integer value. on success, js_valuetoint32 stores the converted value in *ip and returns js_true. on error or
exception, it returns js_false, and the value left in *ip is undefined. js_valuetoint32 is pre-ecma-262 edition 1, and rounds differently than js_valuetoecmaint32 and js::toint32. this routine was added for layers-based graphics programming in netscape 4, but unless you know you need its rounding behavior, it is best to avoid it in favour of js::toint32. js::toint32 rounds as specified in ecma 262-3 §9.5...
JS_ValueToSource
scontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handle<js::value> the value to convert. description js_valuetosource converts a specified javascript value, v, to a javascript source. on success, js_valuetosource returns a pointer to a string. on error or
exception, it returns null. this happens, for example, if v is an object and v.tosource() throws an
exception. see also bug 462910 ...
jsid
a 31-bit signed integer, interned string or object. a few jsapi functions use jsids instead of js::values for property names: js_nextproperty, js_enumerate, and all functions with names ending in byid. also, there is an additional jsid value, jsid_void, which does not occur in js scripts but may be used to indicate the absence of a valid jsid. a void jsid is not a valid id and only arises as an
exceptional api return value, such as in js_nextproperty. embeddings must not pass jsid_void into jsapi entry points expecting a jsid and do not need to handle jsid_void in hooks receiving a jsid except when explicitly noted in the api contract. a jsid is not implicitly convertible to or from a jsval; js_valuetoid or js_idtovalue must be used instead. ...
JSDBGAPI
js_getscriptlineextent js_getscriptversion js_gettopscriptfilenameflags js_getscriptfilenameflags js_flagscriptfilenameprefix jsfilename_null jsfilename_system jsfilename_protected evaluating debug code js_evaluateinstackframe 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_setcallhook js_setobjecthook js_setthrowhook js_setdebugerrorhook js_setnewscripthook js_setdestroyscripthook js_getglobaldebughooks js_setcontextdebughooks memory usage ...
SpiderMonkey 1.8.5
been adjusted, losing its third (unused) argument. js_isconstructing, used to differentiate between calls to native constructors with and without the new keyword, now takes a pointer to the native's vp, along with the native's context pointer, to figure out how the function was called. strings js_comparestrings received a new function signature with bug 609440, allowing us to correctly propagate
exceptions when the underlying functions to retrieve the characters in the string failed. additionally, js_newstring, js_getstringbytes, and js_getstringchars were removed, replaced by fallible interfaces like js_getstringcharszandlength and js_encodestringtobuffer (not an exhaustive list). numbers spidermonkey 1.8.5 now stores integers up to 32-bits in the jsval. this means that the int_fits_in_jsval mac...
SpiderMonkey 1.8.7
been adjusted, losing its third (unused) argument. js_isconstructing, used to differentiate between calls to native constructors with and without the new keyword, now takes a pointer to the native's vp, along with the native's context pointer, to figure out how the function was called. strings js_comparestrings received a new function signature with bug 609440, allowing us to correctly propagate
exceptions when the underlying functions to retrieve the characters in the string failed. additionally, js_newstring, js_getstringbytes, and js_getstringchars were removed, replaced by fallible interfaces like js_getstringcharszandlength and js_encodestringtobuffer (not an exhaustive list). numbers spidermonkey 1.8.5 now stores integers up to 32-bits in the jsval. this means that the int_fits_in_jsval mac...
SpiderMonkey 1.8
ng is a new variation on js_getstringbytes that returns a newly allocated, writable buffer which the application must js_free. js_reportallocationoverflow can be used (instead of js_reportoutofmemory) to indicate that the script is trying to do something that would require more memory than the implementation is designed to handle. the main difference is that js_reportallocationoverflow throws an
exception which the application may catch. js_throwstopiteration throws the appropriate stopiteration
exception object for the given context. two new context options can be used with js_setoptions: jsoption_relimit, which causes extremely long-running regular expression searches to fail with an error, and jsoption_anonfunfix, which bans anonymous functions from appearing anyplace where a statement could ...
SpiderMonkey 17
al of jscontext* parameters to many methods the js_getclass method now takes only a jsobject*, where previously it also required a jscontext* in threadsafe builds. (the js_get_class macro abstracting away this difference has accordingly been removed.) garbage collection functions now take runtime argument most garbage collection functions now take a runtime argument instead of a context. the one
exception to this is js_maybegc which still takes a context as argument. javascript shell changes detail added/removed methods here... known issues detail any known issues here... future direction include-followup-on-experimental-library-versioning-scheme-here spidermonkey embedders should also be aware that mozilla has no plans to keep the jsapi, nor the jsdbgapi stable for embedders. we have chosen to ...
SpiderMonkey 24
context. js_getprototype, takes context as first argument js_encodestringtobuffer takes add context as first argument, js_newruntime adds a js_[use|no]_helper_threads flag delete property in jsclass definitions now use js_deletepropertystub garbage collection functions now take runtime argument most garbage collection functions now take a runtime argument instead of a context. the one
exception to this is js_maybegc which still takes a context as argument. javascript shell changes detail added/removed methods here... known issues detail any known issues here... future direction ...insert details on future plans... spidermonkey embedders should be aware that mozilla has no plans to keep the jsapi, nor the jsdbgapi stable for embedders. we have chosen to concentrate on performan...
SpiderMonkey 45
e (bug 1165486) js_checkforinterrupt (bug 1058695) js::mapdelete (bug 1159469) js::mapforeach (bug 1159469) js::newsetobject (bug 1159469) js::setsize (bug 1159469) js::sethas (bug 1159469) js::setdelete (bug 1159469) js::setadd (bug 1159469) js::setclear (bug 1159469) js::setkeys (bug 1159469) js::setvalues (bug 1159469) js::setentries (bug 1159469) js::setforeach (bug 1159469) js::
exceptionstackornull (bug 814497) js::copyasyncstack (bug 1160307) js::getsavedframesource (bug 1216819) js::getsavedframeline (bug 1216819) js::getsavedframecolumn (bug 1216819) js::getsavedframefunctiondisplayname (bug 1216819) js::getsavedframeasynccause (bug 1216819) js::getsavedframeasyncparent (bug 1216819) js::getsavedframeparent (bug 1216819) js::buildstackstring (bug 1133191) js::flushpe...
TPS Tests
wise, a special sync can be performed if one of the following are passed: sync_wipe_server, sync_wipe_client, sync_reset_client. this will cause tps to set the firstsync pref to the relevant value before syncing, so that the described actionwill take place logger.loginfo(msg) logs the given message to the tps log. logger.asserttrue(condition, msg) asserts that condition is true, otherwise an
exception is thrown and the test fails. logger.assertequal(val1, val2, msg) asserts that val1 is equal to val2, otherwise an
exception is thrown and the test fails. custom functions you can also write your own functions to be called as actions. for example, consider the first action in the phase above: [bookmarks.add, bookmarks_initial] you could rewrite this as a custom function so as to add some ...
Using the Places annotation service
ype); from javascript: getpageannotation(auri, aname); getitemannotation(aitemid, aname); these functions will return/throw ns_error_not_available if the annotation requested does not exist. you can use the annotations service's hasannotation method to determine in advance if the page has the requested annotation. however, it is more efficient to just try to do the operation and catch the
exception; the extra check requires an additional database lookup (which has higher overhead). but then again you won't know if the
exception meant that the annotation did not exist or something else is broken. the getter functions return only the value of the annotation (with the
exception of the c++ getpageannotationbinary and getitemannotationbinary methods which return the mimetype as well). four func...
The Publicity Stream API
e activity permissiondenied - if the publicizing site is not allowed to post to the publicity stream networkerror - if the publicity server is unreachable activityparseerror - if the activity contains syntax errors (not proper json) invalidactivity - if the activity contains semantic errors (i.e. missing required properties) finally, the publicizeactivity() function will throw an
exception if required arguments are missing, or if unsupported arguments are present. getpublicitystream( onsuccess: <function>, { [ onerror: <function> ], [ for_apps: <list> ], [ since: <date> ], [ before: <date> ], [ count: <int> ]): provides a means for a web store to receive a list of the current user's socially relevant app activity by being called from an origin which hosts a web store. it is...
extIPreferenceBranch
s supported by the preference subsystem. setvalue() sets the value of a preference with the given name. void setvalue(in astring aname, in nsivariant avalue) parameters aname the name of a preference avalue the value of a preference return value reset() resets all preferences in a branch back to their default values. note: this function has not been implemented and will raise an
exception. see bug 481044 void 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 prefere...
Creating a Python XPCOM component
attribute string yourname; void write( ); void change(in string avalue); }; this is the same as the nsisimple interface used here. theoretically, because several components can share an interface, the same file could be used. pay special attention to types here - python and javascript are both loosely-typed, so it's fairly easy to pass information from one to the other. note: there are
exceptions; see this discussion for information on the use of string and wstring for unicode transfer. see here for info on describing interfaces, and on which types can be used. registering the interface in the "components" directory, execute : ../xpidl -m typelib -w -v -i /usr/share/idl/mozilla/ nsipysimple.idl on windows you must point to the idl directory as part of your mozilla build. for example: xp...
XPCOM changes in Gecko 2.0
ow.delete() function that you need to call. if, on the other hand, all you're doing with content is accessing dom methods and properties, you've never needed to be using xpcnativewrappers=no in the first place, and should simply remove it from your manifest. miscellaneous xpcnativewrapper changes using the delete operator on "expando" properties of an xpcnativewrapper no longer throws a security
exception. xpcomutils.jsm changes the xpcomutils.jsm code module has been updated to let you specify the application ids of the applications you wish to register your component in. xpcom service getters a number of commonly used xpcom services now have service getter functions available in the mozilla::services namespace; these make it much easier to get access to these services from c++ code. ...
Starting WebLock
thods in that interface. this makes changes to the interface when designing a bit simpler, as you do not have to modify any class declarations. there are times, of course, when you cannot use these macros-as when two interfaces share the same method signatures. in these cases you have to manually declare the methods in your class. but in practice, manually declaring class methods in xpcom is the
exception and not the rule. the ns_decl_iweblock declaration macro expands into the following: ns_imethod lock(void); ns_imethod unlock(void); ns_imethod addsite(const char *url); ns_imethod removesite(const char *url); ns_imethod getsites(nsisimpleenumerator * *asites); ns_imethod setsites(nsisimpleenumerator *asites); representing return values in xpcom the code sample above is the c++ ve...
Using XPCOM Components
stance, the javascript code can access the value and name attributes for each cookie. note: cookie-manager-ui note that the interface is not part of the component itself. xpcom makes it easy to use components like cookiemanager from mozilla's cross platform front end (xpfe) and other user interfaces, but the component itself doesn't provide its own ui. note: private-xpcom-interfaces there are
exceptions to this. some xpcom interfaces are also private and not made for general use. private interfaces do not have the same requirements as the ones that are made available publicly in idl. note: cookie-manager-in-tutorial the cookiemanager component is used to persist for the web locking functionality described in this tutorial. « previousnext » copyright (c) 2003 by doug turner and ian ...
Mozilla internal string guide
. astring nsastring utf-16 string. acstring nsacstring 8-bit string. all bits are preserved across xpconnect boundaries. autf8string nsacstring utf-8 string. converted to utf-16 as necessary when value is used across xpconnect boundaries. domstring nsastring utf-16 string type used in the dom. the same as astring with a few odd xpconnect
exceptions: when the special javascript value null is passed to a domstring parameter of an xpcom method, it becomes a void domstring. the special javascript value undefined becomes the string "undefined". c++ signatures in idl, in parameters are read-only, and the c++ signatures for *string parameters follows the above guidelines by using const nsastring& for these parameters. out and inout parame...
Components.ID
00-0000-000000000000}' giving the interface id of the interface description components.id creates interface ids for use in implementing methods like queryinterface, getinterfaces, and other methods that take interface ids as parameters. components.classes, components.classesbyid, components.interfaces provide pretty much all the nsids that most javascript code would ever need to deal with. the
exception to this is the case where a component is written in javascript and needs to register itself with the component manager using its own nsid - an id that is not already registered and thus does not appear in components.classes. ...
Components.isSuccessCode
ates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1. note: a non-zero xpcom return code (that is, not ns_ok) does not necessarily indicate failure. components.issuccesscode() is functionally equivalent to the following javascript: function issuccesscode(returncode) { return (returncode & 0x80000000) === 0; } since failure error codes are turned into
exceptions when encountered in javascript, this function usually is not necessary. however, if you are using asynchronous apis, it may be essential. for example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object which will be notified when the task is completed. if the task is sufficiently complex that it can fail, the notification will include a stat...
Components.returnCode
e javascript method that the method is returning a specific nsresult code. generally, xpconnect does a fine job of making it unnecessary for javascript code to worry about nsresult codes. by default the successful completion of the javascript method will cause xpconnect to return a result code of ns_ok to the caller. if the javascript code needs to signal failure then that is done by throwing an
exception. however, there are a very few xpcom interfaces that specify success code return values. components.returncode exists in order to make it possible to implement these rare interfaces in javascript. example var foo = { bar: function(i) { if (yada_yada) components.returncode = 5; return i * 2; } }; ...
Components.utils.Sandbox
his should be set to false when possible to further reduce possible attack surface. wantexporthelpers a boolean: if true, then createobjectin(), evalinwindow(), and exportfunction() are available in the sandbox. default: false. wantglobalproperties an array of strings. each string is the name of an object that you want to make available as a global to code running in the sandbox. the
exception is "-promise": the promise constructor is available by default for sandboxes, and you use this option to remove it from the sandbox. note that "-promise" is removed in firefox 37. the following objects are supported: -promise (removed in firefox 37) css indexeddb (web worker only) xmlhttprequest textencoder textdecoder ...
Components.utils.evalInSandbox
ents.utils.evalinsandbox("foo.classes", mysandbox); optional arguments you can optionally specify the js version, filename, and line number of the code being evaluated. for instance: var x = components.utils.evalinsandbox( "let x = 1;", sandbox, "1.8", // "latest" is recognized as a special case "http://foo.com/mycode.js", 25 ); the above will execute code using javascript 1.8. any
exceptions raised by the evaluated code will show as originating from the above url. the evaluated code is assumed to start at line 25 of the document at that url. ...
Components.utils.getWeakReference
your object is valid. it might simply not have been garbage collected yet. you might have to check other aspects of the object (like node.parentnode() on a dom node) to verify the object is truly what you want. syntax weakref = components.utils.getweakreference(obj); parameters obj the object for which to obtain a weak reference. note: in gecko 11.0, this method was changed to throw an
exception if obj is null. in gecko 12.0, the previous behavior of silently failing has been restored. example in this example here, a weak reference to a window is held. and then later on it is matched in the array and used. var arr = []; arr.push(cu.getweakreference(window)); //now lets say this code runs in another block: for (var i=0; i<arr.length; i++) { if (arr[i].get() == window) { //foun...
HOWTO
a better solution in xpcshell. using js modules and non-ui javascript chrome files problem you want to write a javascript file, and run it in xpcshell. the file uses js modules. maybe it even uses javascript files from chrome:// urls. e.g., you use: components.utils.import("resource://app/modules/gloda/log4moz.js"); however, you get (for that particular line, which is the first import): uncaught
exception: [
exception... "component returned failure code: 0x80040111 (ns_error_not_available) [nsixpccomponents_utils.import]" nsresult: "0x80040111 (ns_error_not_available)" location: "js frame :: file.js :: <top_level> :: line 12" data: no] solution 1 var loader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); loader.loadsubsc...
NS_InitXPCOM2
umented 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. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom2 (or ns_initxpcom3) before proceeding to use xpcom in a process. the one
exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom2. many of the xpcom glue functions and classes are also available prior to xpcom initialization, including for example nsembedcstring and nscomptr. history this function was finalized for mozilla 0.9.6. see bug 999147 for details. see also ns_initxpcom3, n...
NS_InitXPCOM3
umented 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. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom3 (or ns_initxpcom2) before proceeding to use xpcom in a process. the one
exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom3. many of the xpcom glue functions and classes are also available prior to xpcom initialization, including for example nsembedcstring and nscomptr. initializing xpcom with static modules allows the application to easily define modules that are linked into the ap...
imgICache
header if you call this before any data has been loaded from a uri, it will succeed, but come back empty. nsiproperties findentryproperties( in nsiuri uri ); parameters uri the uri to look up. return value null if the url was not found in the cache. removeentry() evict images from the cache. void removeentry( in nsiuri uri ); parameters uri the uri to remove.
exceptions thrown ns_ok if a uri was removed from the cache. ns_error_not_available if a uri was unable to be removed from the cache. ...
jsdIStackFrame
his context, if it is an nsisupports, |null| otherwise. retrieve the underlying context wrapped by this jsdicontext. top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. this attribute is only valid for contexts which implement nsiscriptcontext. setting or getting this attribute on any other context will throw a ns_error_no_interface
exception. stack frame objects. these are only valid inside the jsdiexecutionhook which gave it to you. after you return from that handler the bottom frame, and any frame you found attached through it, are invalidated via the jsdiephemeral interface. once a jsdistackframe has been invalidated all method and property accesses will throw a ns_error_not_available
exception. method overview boolean eval(in ...
mozIAsyncHistory
einfo the moziplaceinfo object[s] containing the information to store or update. this can be a single object, or an array of objects. acallback optional a mozivisitinfocallback object to be notified for each visit addition, title change, guid change, or error. if more than one operation is performed for a given visit, only one callback will be given (i.e. title change and add visit).
exceptions thrown ns_error_invalid_arg passing in null for aplaceinfo. not providing at least one valid guid or uri for all moziplaceinfo object[s]. not providing an array or nothing for the visits property of moziplaceinfo. not providing a visitdate and transitiontype for each mozivisitinfo. providing an invalid transitiontype (see nsinavbookmarksservice.constants) for a mozivisit...
mozISpellCheckingEngine
rently used. read only. dictionary wstring the name of the current dictionary used by check() and suggest(). this will be either element from the array returned by getdictionarylist() or an empty string if no dictionary is selected. note: setting this value to a value that doesn't match an existing dictionary throws a ns_error_file_not_found
exception. when this attribute's value is changed, a "spellcheck-dictionary-update" notification is sent. if the dictionary was set to "no dictionary" (that is, by specifying an empty string), the observer may select another dictionary before returning. language wstring the language this spell checker is using when checking. this is the language of dictio...
mozIStorageStatementWrapper
seamonkey 1.0) inherits from: nsisupports method overview void initialize(in mozistoragestatement astatement); void reset(); boolean step(); void execute(); attributes attribute type description statement mozistoragestatement the statement that is wrapped. row mozistoragestatementrow the current row. throws an
exception if no row is currently available. useful only from script. the value of this is only valid while the statement is still executing, and is still on the appropriate row. params mozistoragestatementparams the parameters; these can be set in lieu of using the call notation on this. methods initialize() this method initializes this wrapper with astatement. void initialize( in ...
Children
« nsiaccessible page summary array of all this node's children. attribute nsiarray children; remark every child node in the array implements nsiaccessible interface.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessible.firstchild nsiaccessible.lastchild nsiaccessible.childcount nsiaccessible.getchildat() nsiaccessible.parent nsiaccessible.nextsibling nsiaccessible.previoussibling ...
DoAction
« nsiaccessible page summary this method performs the accessible action at the given zero-based index. action number 0 is the default action. void doaction( in pruint8 aindex ); parameters aindex[in] the zero-based index.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ns_error_invalid_arg indicates that the given index is our of range. see also nsiaccessible.numactions nsiaccessible.getactionname() nsiaccessible.getactiondescription() ...
ExtendSelection
« nsiaccessible page summary this method extends the current selection from its current accessible anchor node to this accessible. void extendselection();
exceptions thrown ns_error_not_implemented always. this method isn't implemented. see also nsiaccessible.setselected() nsiaccessible.takeselection() ...
FirstChild
« nsiaccessible page summary returns first child node in accessible tree. attribute nsiaccessible firstchild;
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessible.lastchild nsiaccessible.children nsiaccessible.childcount nsiaccessible.getchildat() nsiaccessible.parent nsiaccessible.nextsibling nsiaccessible.previoussibling ...
GetAccessibleRelated
ssible page summary this method returns an accessible related to this one by the given relation type. nsiaccessible getaccessiblerelated( in unsigned long arelationtype ); parameters arelationtype[in] the relation type between the accessible (see constants listed in relations documentation). ...
GetActionDescription
« nsiaccessible page summary this method retrieves the description (localized name) of the accessible action at the given zero-based index. astring getactiondescription( in pruint8 aindex ); parameters aindex[in] the zero-based index. return value returns the description of the accessible action.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ns_error_invalid_arg indicates that the given index is our of range. see also nsiaccessible.numactions nsiaccessible.getactionname() nsiaccessible.doaction() ...
GetActionName
« nsiaccessible page summary this method retrieves the name of the accessible action at the given zero-based index. astring getactionname( in pruint8 aindex ); parameters aindex[in] the zero-based index. return value returns the name of the accessible action.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree.ns_error_invalid_arg indicates that the given index is our of range. see also nsiaccessible.numactions nsiaccessible.getactiondescription() nsiaccessible.doaction() ...
GetChildAt
« nsiaccessible page summary this method returns nth accessible child using zero-based index. nsiaccessible getchildat( in long achildindex ); parameters achildindex[in] the index of the nth child. return value returns nth accessible child using zero-based index. if child index is less than zero then returns last child. if child index is greater than children count then returns null.
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessible.firstchild nsiaccessible.lastchild nsiaccessible.children nsiaccessible.childcount nsiaccessible.parent nsiaccessible.nextsibling nsiaccessible.previoussibling ...
GetKeyBindings
« nsiaccessible page summary this method provides array of localized string of global keyboard accelerator for the given action index supported by accessible. nsidomdomstringlist getkeybindings( in pruint8 aactionindex ); parameters aactionindex[in] index of the given action. return values returns array of localized string of global keyboard accelerator.
exceptions thrown ns_error_invalid_arg the given index doesn't correspond to default action (not zero). remark key bindings are supported for default action only. see also nsiaccessible.defaultkeybinding nsiaccessible.keyboardshortcut ...
GetRelation
« nsiaccessible page summary this method returns accessible relation for this accessible object by index. nsiaccessiblerelation getrelation( in unsigned long aindex ); parameters aindex[in] the index for which relation is to be retrieved. return value returns nsiaccessiblerelation object for this accessible.
exception thrown ns_error_invalid_arg indicates that the given index is invalid. remark currently we do not support multiple relations so the zero index may be valid only. refer to relations documentation for more info. see also nsiaccessible.relationscount nsiaccessible.getrelations() nsiaccessible.getaccessiblerelation() ...
GetState
« nsiaccessible page summary this method retrieves states of the accessible. void getstate( out unsigned long astate, out unsigned long aextrastate ); parameters astate[out] the first bit field (see state_* constants in states documentation).aextrastate[out] the second bit field (see ext_state_* constants in states documentation).
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. remarks accessible states are stored as bit fields which describe boolean properties of node. many states are only valid given a certain role attribute that supports them. refer to states documentation for more information. ...
LastChild
« nsiaccessible page summary returns last child node in accessible tree. attribute nsiaccessible lastchild;
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessible.firstchild nsiaccessible.children nsiaccessible.childcount nsiaccessible.getchildat() nsiaccessible.parent nsiaccessible.nextsibling nsiaccessible.previoussibling ...
NextSibling
« nsiaccessible page summary returns next sibling in accessible tree. attribute nsiaccessible nextsibling;
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessible.parent nsiaccessible.previoussibling nsiaccessible.firstchild nsiaccessible.lastchild nsiaccessible.children nsiaccessible.childcount nsiaccessible.getchildat() ...
Parent
remarks every accessible in the tree has accessible parent excepting application accessible (top level accessible). ...
PreviousSibling
« nsiaccessible page summary returns previous node in accessible tree. attribute nsiaccessible previoussibling;
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessible.parent nsiaccessible.nextsibling nsiaccessible.firstchild nsiaccessible.lastchild nsiaccessible.children nsiaccessible.childcount nsiaccessible.getchildat() ...
SetSelected
« nsiaccessible page summary this method adds or remove this accessible to the current selection. void setselected( in boolean aisselected ); parameters aisselected[out] the current selection
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessible.takeselection() nsiaccessible.extendselection() ...
TakeSelection
« nsiaccessible page summary this method selects this accessible node only. void takeselection();
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessible.setselected() nsiaccessible.extendselection() ...
nsIAccessibleRelation
lt_button 0x4000 part of a form/dialog with a related default button. it is used for msaa only, no for ia2 nor atk/at-spi. methods gettarget() returns accessible relation target at the given index. nsiaccessible gettarget( in unsigned long index ); parameters index zero-based index of relation target. return value returns an nsiaccessible object.
exceptions thrown ns_error_invalid_arg indicates the given index is out of range. gettargets() returns an array of accessible relation targets. nsiarray gettargets(); parameters none. return value an nsiarray object, each item in the array implements an nsiaccessible. ...
nsIAccessibleText
ersistentproperties gettextattributes( in boolean includedefattrs, in long offset, out long rangestartoffset, out long rangeendoffset ); parameters includedefattrs points whether text attributes applied to the entire accessible should be included or not. offset text offset. rangestartoffset start offset of the range of text. rangeendoffset end offset of the range of text. return value
exceptions thrown missing
exception gettextbeforeoffset() string methods may need to return multibyte-encoded strings, since some locales can't be encoded using 16-bit chars. so this method might return utf-16 strings, or it could return "string" values which are utf-8. astring gettextbeforeoffset( in long offset, in nsaccessibletextboundary boundarytype, out long startoffset, out long endoffset...
nsIAlertsService
available on supported platforms. data optional the value of the cookie parameter passed to showalertnotification. principal optional the principal of the page that created the alert. used for ipc security checks, and to determine whether the alert is actionable. inprivatebrowsing optional controls the image loading behavior. if true, the image url will be loaded in private browsing mode.
exceptions thrown ns_error_not_available unable to display the notification; this may happen, for example, on mac os x if growl is not installed. example simple usage the following code was used to display the above notification. var alertsservice = components.classes["@mozilla.org/alerts-service;1"]. getservice(components.interfaces.nsialertsservice); try { alertsservice.s...
nsIApplicationCacheChannel
derbird 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. the default value is false. this attribute will not be transferred through a redirect.
exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel. inheritapplicationcache boolean true if the channel will ask its notification callbacks for an application cache if one is not explicitly provided. the default value is true.
exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel. loadedfromapplicationcache prbool true if...
nsIAuthInformation
me other way to the user. on return, this parameter should contain the domain entered by the user. this attribute is only used if flags include #need_domain. flags unsigned long flags describing this dialog. a bitwise or of the constants. it is possible that neither #auth_host nor #auth_proxy are set. auth prompts should ignore flags they do not understand; especially, they should not throw an
exception because of an unsupported flag. read only. password astring the initial value should be used to prefill the dialog or be shown in some other way to the user. the password should not be shown in clear. on return, this parameter should contain the password entered by the user. realm astring the server-supplied realm of the authentication as defined in rfc 2617. can be the empty string if the pr...
nsIAuthPromptCallback
cpromptauth() returns successfully. they must not call any method on this interface before nsiauthprompt2.asyncpromptauth() returns. method overview void onauthavailable(in nsisupports acontext, in nsiauthinformation aauthinfo); void onauthcancelled(in nsisupports acontext, in boolean usercancel); methods onauthavailable() authentication information is available. note: any
exceptions thrown from this method should be ignored. void onauthavailable( in nsisupports acontext, in nsiauthinformation aauthinfo ); parameters acontext the context as passed to nsiauthprompt2.asyncpromptauth(). aauthinfo authentication information. must be the same object that was passed to nsiauthprompt2.asyncpromptauth(). onauthcancelled() notification that the prompt was cance...
nsIAuthPromptProvider
thprompt() this method requests a prompt interface for the given prompt reason. void getauthprompt( in pruint32 apromptreason, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result ); parameters apromptreason the reason for the authentication prompt, one of the prompt_* constants. iid the desired interface, for example, ns_get_iid(nsiauthprompt2). result a nsiauthprompt2 interface.
exceptions thrown ns_error_not_available if no prompt is allowed or available for the given reason. ...
nsICachingChannel
ate it. the cache token can be queryinterface'd to a nsicacheentryinfo if more detail about the cache entry is needed. for example, expiration time. offlinecacheclientid acstring the session into which to cache offline data. if not specified, data will be placed in "http-offline". offlinecachetoken nsisupports the same as cachetoken but accessing the offline app cache token if there is any.
exceptions thrown ns_error_not_available when there is not offline cache token. constants constant value description load_no_network_io 1 << 26 this load flag inhibits fetching from the net. an error of ns_error_document_not_cached will be sent to the listener's onstoprequest if network io is necessary to complete the request. this flag can be used to find out whether fetching this url would ca...
nsIClassInfo
et, then the value of this attribute specifies a classid through which this class can be accessed as a service using nsiservicemanager.getservice(). 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. read only. violates the xpcom interface guidelines
exceptions thrown ns_error_not_available if the class does not have a classid contractid string a contractid through which an instance of this class can be created, or null. if the flags attribute has the singleton bit set, then the value of this attribute specifies a contractid through which this class may be accessed as a service using nsiservicemanager.getserviceb...
nsICommandLineRunner
r of arguments being passed. argv an array storing pointers to the arguments workingdir directory where the command will run. this is used to resolve file and uri paths. state the type of command line being processed. this is an nsicommandline state flag. run() processes the command-line handlers in the proper order, and calls nsicommandlinehandler.handle() on each. void run(); parameters none.
exceptions thrown ns_error_abort thrown when the handler aborts. all other errors thrown by handlers will be silently ignored. setwindowcontext() sets the windowcontext parameter. void setwindowcontext( in nsidomwindow awindow ); parameters awindow the dom window object which will be set. it is an nsidomwindow object. ...
nsICompositionStringSynthesizer
ring(), appendclause() and setcaret() to the focused editor. if appendclause() hasn't been called, this dispatches events to set composition string without clause information. in other words, commits composition string. if appendclause() and/or setcaret() are not called properly, e.g., sum of alength of calls of appendclause() is not same as composition string set by setstring(), this throws an
exception. after a call of this, all stored composition string information is cleared. therefore, you can reuse the instance for modifying composition string. boolean dispatchevent(); return value if dispatched event's default is prevented, returns true. however, this must always return false since all dispatching dom events are not cancelable. setcaret() sets caret position in the composition string...
nsIConsoleService
this will prevent the source line showing in the error console. alinenumber and acolumnnumber — specify the exact location of an error. acolumnnumber is used to draw the arrow pointing to the problem character. aflags — one of flags declared in nsiscripterror. at the time of writing, possible values are: nsiscripterror.errorflag = 0 nsiscripterror.warningflag = 1 nsiscripterror.
exceptionflag = 2 and nsiscripterror.strictflag = 4. acategory — a string indicating what kind of code caused the error message. there are quite a few category strings and they do not currently seem to be listed in a single place. hopefully, they will all eventually be listed in nsiscripterror.idl. see also error console (deprecated) web console browser console nsiconsolemessage ...
nsIConverterInputStream
latin 1 is specified as "iso-8859-1". abuffersize defines the buffer size of the converter stream. in case of a buffer size of less than or equal to 0, the default size converter_buffer_size will be used. this is currently set to 8192 bytes. areplacementchar any unknown byte sequence will be replaced with this character. the default replacement character is u+fffd. a value of 0x0000 will cause an
exception to be thrown if unknown byte sequences are encountered in the stream. see also nsiconverteroutputstream see reading textual data for an example. ...
nsIConverterOutputStream
ritten. acharset the character set to use for encoding the characters. a null charset will be interpreted as utf-8. abuffersize how many bytes to buffer. a value of 0 means that no bytes will be buffered. implementations not supporting buffering may ignore this parameter. areplacementcharacter the replacement character to use when an unsupported character is found. a value of 0x0000 will cause an
exception to be thrown upon attempts to write unsupported characters.
exceptions thrown ns_error_loss_of_significant_data if areplacementcharacter is not encodable in the selected character encoding and an attempt is made to write the character. see also nsiconverterinputstream see writing textual data for an example. ...
nsICookieManager
attributes attribute type description enumerator nsisimpleenumerator called to enumerate through each cookie in the cookie list. the objects enumerated over are of type nsicookie. read only. methods remove() this method is called to remove an individual cookie from the cookie list, specified by host, name, and path. if the cookie cannot be found, no
exception is thrown. typically, the arguments to this method will be obtained directly from the desired nsicookie object. void remove( in autf8string ahost, in acstring aname, in autf8string apath, in boolean ablocked, in jsval aoriginattributes ); parameters ahost the host or domain for which the cookie was set. see nsicookiemanager2.add() for a description of acceptable host strings. if ...
nsICookieManager2
ters ahost the host or domain for which the cookie is set. presence of a leading dot indicates a domain cookie; otherwise, the cookie is treated as a non-domain cookie. see rfc2109 for details. the host string will be normalized to ascii or ace; any trailing dot will be stripped. to be a domain cookie, the host must have at least two subdomain parts (e.g. '.foo.com', not '.com'), otherwise an
exception will be thrown. an empty string is acceptable (e.g. file:// uri's). apath the path within the domain for which the cookie is valid. aname the cookie name. avalue the cookie data. aissecure true if the cookie should only be sent over a secure connection. aishttponly true if the cookie should only be sent to, and can only be modified by, an http connection. aissession true if the cookie...
nsIDNSService
for a long period of time. it is extremely unwise to call this function on the user interface thread of an application. nsidnsrecord resolve( in autf8string ahostname, in unsigned long aflags ); parameters ahostname the host name or ip-address-literal to resolve. aflags a bitwise or of the resolve flag constants. return value dns record corresponding to the given host name.
exceptions thrown ns_error_unknown_host if host could not be resolved. shutdown() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) called to shutdown the dns service. any pending asynchronous requests will be canceled, and the local cache of dns records will be cleared. note: the operating system may still have its own cache of dns records, which ...
nsIDOMChromeWindow
w is in full screen mode. methods beginwindowmove() on some operating systems, we must allow the window manager to handle window dragging. this method tells the window manager to start dragging the window. this method will fail unless called while the left mouse button is held down, callers must check this. void beginwindowmove( in nsidomevent mousedownevent ); parameters mousedownevent
exceptions thrown ns_error_not_implemented if the operating system does not support this method. getattention() void getattention(); parameters none. getattentionwithcyclecount() same as getattention method excepting that this can specify the maximum number of times to animate the window per system conventions. void getattentionwithcyclecount( in long acyclecount ); parameters acyclecount the maximu...
nsIDOMFile
ethods offered by this interface in order to ensure future compatibility. content/base/public/nsidomfile.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports this interface implements the dom file object; for complete documentation, read up on that. see also nsidomfilelist nsidomfile
exception datatransfer drag and drop ...
nsIDOMFileReader
an instance, use: var filereader = components.classes["@mozilla.org/files/filereader;1"].createinstance(components.interfaces.nsidomfilereader); this interface implements the dom filereader object; see that documentation for details. examples os.file for the main thread - example - save canvas to disk see also file api specification working draft nsidomfile nsidomfilelist nsidomfile
exception ...
nsIDOMGeoGeolocation
last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports implemented by: @mozilla.org/geolocation;1. ...
nsIDOMHTMLAudioElement
e the sampling rate to use on the stream, in samples per second. for example, specify 44100 for 44.1khz. mozwriteaudio() writes samples to the audio stream. unsigned long mozwriteaudio( in jsval data ); parameters data the samples to write into the audio stream, specified either as a javascript array or as a numeric typed array. return value the actual number of bytes written to the stream.
exceptions thrown ns_error_dom_invalid_state_err the stream has not been initialized for writing by a call to mozsetup(). ns_error_dom_type_mismatch_err the data isn't a valid data type (an array or typed array of numeric values). ns_error_dom_index_size_err the number of samples specified doesn't divide evenly across the number of channels; you must provide exactly the same number of samples for all chan...
nsIDOMOfflineResourceList
void mozremove( in domstring uri ); parameters uri the uri of the item to remove from the list. swapcache() swaps in the newest version of the application cache. the newest version of resources are updated on first refresh. this means already loaded resources should only update after a page refresh. note: versioned application caches are not yet supported; this method will throw an
exception. void swapcache(); parameters none. update() begins the application cache update process. this will check for a new cache manifest but will not tell the browser to use the updated cache. void update(); parameters none. see also offline resources in firefox nsiapplicationcache nsiapplicationcachecontainer nsiapplicationcacheservice nsiapplicationcachechannel nsiapplicationcach...
nsIDOMStorage
urn value an nsidomstorageitem object describing the data corresponding to the specified key, or null if no data exists for the given key. key() returns the key for the item stored at the specified index in the data store. domstring key( in unsigned long index ); parameters index the index for which the corresponding key should be returned. return value a string containing the requested key.
exceptions thrown index_size_err there is no key at the specified index. removeitem() given a key, removes the corresponding entry from the session store. void removeitem( in domstring key ); parameters key the key for which data should be removed from storage. setitem() sets the value corresponding to a given key. if the key does not already exist, a new key is added, associated with the specified ...
nsIDOMStorage2
ld be returned. return value a string containing the data corresponding to the specified key, or null if no data exists for the given key. key() returns the key for the item stored at the specified index in the data store. domstring key( in unsigned long index ); parameters index the index for which the corresponding key should be returned. return value a string containing the requested key.
exceptions thrown index_size_errthere is no key at the specified index. removeitem() given a key, removes the corresponding entry from local storage. void removeitem( in domstring key ); parameters key the key for which data should be removed from storage. setitem() sets the value corresponding to a given key. if the key does not already exist, a new key is added, associated with the specified value.
nsIDOMXPathResult
y available if the result type is unordered_node_snapshot_type or ordered_node_snapshot_type. nsidomnode snapshotitem( in unsigned long index ); parameters index the index of the dom node to return. return value a dom node. see also introduction to using xpath in javascript document object model (dom) level 3 xpath specification nsidomxpathevaluator document.evaluate nsidomxpath
exception ...
nsIDirectoryEnumerator
attribute type description nextfile nsifile the next file in the sequence. the nextfile attribute is the first element upon the first call. this attribute is null if there is no next element. read only. methods close() closes the directory being enumerated, releasing the system resource. it is safe to call this function many times. void close(); parameters none.
exceptions thrown ns_ok if the call succeeded and the directory was closed. ns_error_failure if the directory close failed. ...
nsIDownloadManagerUI
1 when opening the download manager user interface, this value indicates that the user interface is being displayed because a new download is being started. 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. void getattention(); parameters none.
exceptions thrown ns_error_unexpected the user interface isn't currently open. show() shows the download manager's user interface to the user. void show( in nsiinterfacerequestor awindowcontext, optional in unsigned long aid, optional in short areason optional ); parameters awindowcontext optional the parent window context to show the user interface. with this information, it's possible...
nsIDownloadProgressListener
rather, only fill in the code for the ones you need, and leave the others blank as shown. see also nsidownloadmanager nsidownload nsiwebprogresslistener ...
nsIDragService
widget/nsidragservice.idlscriptable implements the drag service for handling drag and drop operations. inherits from: nsisupports last changed in gecko 43 (firefox 43 / thunderbird 43 / seamonkey 2.40) note: using this interface directly from add-on code is deprecated. add-ons should use the standard datatransfer drag and drop api instead. the only
exception is getcurrentsession(), since there's currently no way to check for a drag in progress using standard dom methods or properties. method overview void enddragsession( in prbool adonedrag ) ; void dragmoved(in long ax, in long ay); native code only! void firedrageventatsource(in unsigned long amsg); obsolete since gecko 43 void firedrageventatsource(in mozilla::eventmessage aeventmessage); ...
nsIEventTarget
o be processed while waiting for the given event to be processed. methods dispatch() dispatches an event to this event target. this function may be called from any thread, and it may be called re-entrantly. void dispatch( in nsirunnable event, in unsigned long flags ); parameters event the event to dispatch. flags the dispatch flags modifying the event.
exceptions thrown ns_error_unexpected indicates that the thread is shutting down and has finished processing events, so this event would never run and has not been dispatched. ns_error_invalid_arg indicates that event is null. isoncurrentthread() check to see if this event target is associated with the current thread. boolean isoncurrentthread(); parameters none. return value...
nsIFactory
pports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result ); parameters aouter pointer to a component that wishes to be aggregated in the resulting instance. this can be nsnull if no aggregation is requested. iid the iid of the interface being requested in the component which is being currently created. result pointer to the newly created instance, if successful.
exceptions thrown ns_error_no_interface indicates that the requested interface is not supported. ns_error_no_aggregation indicates that aggregation is not supported. lockfactory() this method provides the client a way to keep the component in memory until it is finished with it. gecko 1.7 note as of gecko 1.7, this method is unused. most implementations do nothing interesting with this metho...
nsIFilePicker
astring the extension for the type of files you want to work with. on some platforms, this is automatically appended to filenames the user enters, if required. specify it without a leading dot, for example "jpg". defaultstring astring the filename, including extension, that should be suggested to the user as a default. this should be set before calling open() or show().
exceptions thrown ns_error_failure if you try to read this attribute. displaydirectory nsilocalfile the directory that the file picker dialog should initially display. this should be set this before calling open() or show() to specify a starting point. file nsilocalfile the currently selected file or directory. read only. files nsisimpleenu...
nsIFileProtocolHandler
uri. nsiuri newfileuri( in nsifile afile ); parameters afile the nsifile to convert. return value a reference to a new nsiuri object. readurlfile() takes a local file and tries to interpret it as an internet shortcut (for example .url files on windows). nsiuri readurlfile( in nsifile file ); parameters file the nsifile to read. return value the nsiuri the file refers to.
exceptions thrown ns_error_not_available the os does not support such files. ns_error_not_available the file is not an internet shortcut. see also code_snippets:file_i/o ...
nsIFrameLoader
y. methods activateframeevent() activates event forwarding from client (remote frame) to parent. void activateframeevent( in astring atype, in boolean capture ); parameters atype the event type for which to enable forwarding. capture whether or not to capture these events. activateremoteframe() activates the remote frame. void activateremoteframe(); parameters none.
exceptions thrown throws an
exception with non-remote frames. destroy() destroys the frame loader and everything inside it. this will clear the weak owner content reference. void destroy(); parameters none. loadframe() starts loading the frame. this method figures out what to load from the owner content in the frame loader. void loadframe(); parameters none. loaduri() loads the specified uri...
nsIFrameLoaderOwner
siframeloader owned by this object. swapframeloaders() swaps frame loaders with the given nsiframeloaderowner. this may only be possible in a very limited set of circumstances, or never, depending on the object implementing this interface. void swapframeloaders( in nsiframeloaderowner aotherowner ); parameters aotherowner the other frame loader owner with which to swap frame loaders.
exceptions thrown ns_error_dom_security_err if the swap is not allowed on security grounds. ns_error_not_implemented if the swapping logic is not implemented for the either the current frame loader owner or the specified one with which you're trying to swap. see also nsiframeloader ...
nsIHTMLEditor
s selected. getparagraphstate() returns what block tag paragraph format is in the selection. astring getparagraphstate( out boolean amixed ); parameters amixed true if there is more than one format. return value name of block tag. "" is returned for none. getselectedelement() return an element only if it is the only node selected, such as an image, horizontal rule, and so on. the
exception is a link, which is more like a text attribute: the anchor tag is returned if the selection is within the textnode(s) that are children of the "a" node. this could be a collapsed selection, that is, a caret within the link text. nsidomelement getselectedelement( in astring atagname ); parameters atagname the html tagname or and empty string to get any element (but only if it is the only ...
nsIHttpHeaderVisitor
col/http/nsihttpheadervisitor.idlscriptable this interface is used to view http request and response headers. 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. this method can throw an
exception to terminate enumeration of the channel's headers. void visitheader( in acstring aheader, in acstring avalue ); parameters aheader a string containing the key for a header such as "content-type" avalue the header's value field such as "text/html". multiple values are separated by a comma. example this example shows how to detect flash content. it implements the nsihttpheadervisito...
nsIInterfaceRequestor
a. method overview void getinterface(in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); methods getinterface() retrieves the specified interface pointer. void getinterface( in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result ); parameters uuid the iid of the interface being requested. result the interface pointer to be filled in if the interface is accessible.
exceptions thrown ns_error_no_interface the requested interface is not available. ...
nsIJSON
dom/interfaces/json/nsijson.idlscriptable this interface provides a convenient way to encode and decode json strings from javascript code. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) note: this interface may only be used from javascript code, with the
exception of the legacydecodetojsval() method. however, you should use native json instead if at all possible. implemented by: @mozilla.org/dom/json;1. to create an instance, use: var nativejson = components.classes["@mozilla.org/dom/json;1"] .createinstance(components.interfaces.nsijson); method overview note: the idl file has portions of the idl commented out because they represent things that can't actu...
nsIJetpack
script( in astring ascript ); parameters ascript the full contents of the script to evaluate in the jetpack process. createhandle() this creates an opaque handle that can transparently be exchanged between processes. nsivariant createhandle(); parameters none. return value the new handle. destroy() this terminates the jetpack process. void destroy(); parameters none. special messages if an
exception goes uncaught in the jetpack process, it will be reported to the chrome process via a message with the name core:
exception. the message comes with one argument, which represents the
exception object that was thrown. warning: bug 589308 prevents this message from being sent in some situations. history see bug 556846 for details. see also nsijetpackservice jetpack processes ...
nsILoadGroup
arequest the request to be added to the load group. acontext the context to be passed to the onstartrequest notification. removerequest() removes a request from the group. 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. void removerequest( in nsirequest arequest, in nsisupports acontext, in nsresult astatus ); parameters arequest the request to be removed from the load group. acontext the context to be passed to the onstoprequest notification. astatus the status to be passed to the onstoprequest notification. ...
nsILoginManager
is(count)] out nsilogininfo logins); void setloginsavingenabled(in astring ahost, in boolean isenabled); methods addlogin() stores a new login in the login manager. note: default values for the nsiloginmetainfo properties are created if the specified login doesn't explicitly specify them. void addlogin( in nsilogininfo alogin ); parameters alogin the login to store.
exceptions thrown an
exception is thrown if the login information is already stored in the login manager. to change a login, you have to use modifylogin(). autocompletesearch() generates results for a user field autocomplete menu. note: this method is provided for use only by the formfillcontroller, which calls it directly. it should not be used for any other purpose. nsiautocompleteresult autoc...
nsIModule
y or a may be query to a nsiclassinfo. void getclassobject( in nsicomponentmanager acompmgr, in nscidref aclass, in nsiidref aiid, [retval, iid_is(aiid)] out nsqiresult aresult ); parameters acompmgr the global component manager. aclass the classid of object instance requested. aiid the iid of interface requested. aresult the resulting interface pointer.
exceptions thrown ns_error_factory_not_registered indicates that the requested class is not available. ns_error_no_interface indicates that the requested interface is not supported. registerself() when the nsimodule is discovered, this method will be called so that any setup registration can be preformed. void registerself( in nsicomponentmanager acompmgr, in nsifile alocation, in s...
nsIMsgAccount
coming server stuff key acstring internal key identifying itself methods addidentity() adds a new identity to this account. void addidentity( in nsimsgidentity identity ); parameters identity the identity to add. clearallvalues() clear all user preferences associated with an account. void clearallvalues(); parameters none. init() initializes an account. void init(); parameters none.
exceptions thrown ns_error_already_opened if it is called more then once removeidentity() removes an identity from this account. void removeidentity( in nsimsgidentity identity ); parameters identity the identity to remove. ...
nsIMsgDatabase
nsioutputstream summaryvalid boolean methods open() opens a database folder. void open(in nsilocalfile afoldername, in boolean acreate, in boolean aleaveinvaliddb); parameters afoldername the name of the folder to create. acreate whether or not the file should be created. aleaveinvaliddb set to true if you do not want the database to bedeleted if it is invalid.
exceptions thrown ns_error_file_target_does_not_exist afoldername doesn't exist and acreate was false. ns_msg_error_folder_summary_out_of_date the database is present (and was opened), but the summary file is out of date. ns_msg_error_folder_summary_missing the database is present (and was opened), but the summary file is missing. forcefolderdbclosed() void forcefolderdbclosed(in nsimsgfolder afolder); ...
nsIMsgMessageService
consumer has to be a stream listener and in your listener's ondataavailable method, you can write out the stream data to a local file or concatenate it to a string. aurllistener an nsiurllistener that is notified when url starts and stops, if we run a url. alocalonly whether data should be retrieved only from local caches. if streaming over the network is required and this is true, then an
exception is thrown. this defaults to false. note if we're offline, then even if alocalonly is false, we won't stream over the network return the url that gets run, if any ismsginmemcache() determines whether a message is in the memory cache. local folders don't implement this. boolean ismsginmemcache(in nsiuri aurl, in nsimsgfolder afolder, out nsi...
nsIMsgSearchValue
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchvalue.idl #include "nsmsgsearchcore.idl" interface nsimsgfolder; [scriptable, uuid(783758a0-cdb5-11dc-95ff-0800200c9a66)] interface nsimsgsearchvalue : nsisupports { // type of object attribute nsmsgsearchattribvalue attrib; // accessing these will throw an
exception if the above // attribute does not match the type! attribute astring str; attribute nsmsgpriorityvalue priority; attribute prtime date; // see nsmsgmessageflags.idl and nsmsgfolderflags.idl attribute unsigned long status; attribute unsigned long size; attribute nsmsgkey msgkey; attribute long age; // in days attribute nsimsgfolder folder; attribute nsmsglabelvalue label; attribute nsmsgjunkstatu...
nsIMsgWindow
tead set the domwindow property instead. messagewindowdocshell nsidocshell readonly: this retrieves the nsidocshell object for the message pane. you should not store this in a global variable. notificationcallbacks 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. mailcharacterset acstring this is used to track the character set of the currently displayed message. if set to an alias, the actual character set is returned. charsetoverride boolean remember the message'...
nsIPrivateBrowsingService
tches) rather than the user interface. read only. privatebrowsingenabled boolean indicates whether or not private browsing mode is currently enabled. you may also turn private browsing mode on and off by setting the value of this attribute. changing this value while handling one of the notifications generated by the private browsing service throws an ns_error_failure
exception. methods removedatafromdomain() removes all data stored for the specified domain, including its subdomains. void removedatafromdomain( in autf8string adomain ); parameters adomain the domain for which data should be removed. ...
nsIProfile
sts( in wstring profilename ); parameters profilename the name of the profile to look for. return value true if there is a profile with the specified name. renameprofile() renames an existing profile. void renameprofile( in wstring oldname, in wstring newname ); parameters oldname the name of the profile to rename. newname the new name to assign to the profile.
exceptions thrown ns_error_failure a profile already exists with the name newname. shutdowncurrentprofile() shuts down the current profile; this essentially "logs out" the current profile. void shutdowncurrentprofile( in unsigned long shutdowntype ); parameters shutdowntype the type of shutdown to perform; see shutdown type constants. see also nsitoolkitprofileservice ...
nsIProfileLock
ry, which exists for the purpose of storing data on the local filesystem, including cache files or other data files that may not represent critical user data. (for example, this directory may not be included as part of a backup scheme.) in some cases, this directory may just be the main profile directory. read only. methods unlock() unlocks the profile. void unlock(); parameters none.
exceptions thrown ns_error_unexpected the profile isn't locked. see also profile management nsitoolkitprofileservice nsitoolkitprofile nsiprofileunlocker ...
nsIProperties
string keys); boolean has(in string prop); void set(in string prop, in nsisupports value); void undefine(in string prop); methods get() gets the xpcom object associated with a particular name. void get( in string prop, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result ); parameters prop the property name. iid the desired interface. result the resulting object instance.
exceptions thrown ns_error_failure if the property does not exist. ns_error_no_interface if the property exists, but does not support the requested interface. getkeys() returns an array of property names. nsmemory.h defines the macro ns_free_xpcom_allocated_pointer_array, which can be used to free akeys when it is no longer needed. void getkeys( out pruint32 count, [array, size_is(count), retval] out...
nsIPropertyBag
attribute type description enumerator nsisimpleenumerator get a nsisimpleenumerator whose elements are nsiproperty objects. read only. methods getproperty() get a property value for the given name. nsivariant getproperty( in astring name ); parameters name the name to return the matching property. return value the property matching the given name.
exceptions thrown ns_error_failure if a property with that name doesn't exist. examples get user agent information (operating system specifics. the window scope is not always accessible so the window.navigator cannot be accessed. goodies obtained from window.navigator are: appcodename:"mozilla" appname:"netscape" appversion:"5.0 (windows)" battery:batterymanager buildid:"20140529161749" cookieenab...
nsIResumableChannel
/ seamonkey 1.0) method overview void asyncopenat(in nsistreamlistener listener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid); obsolete since gecko 1.8 void resumeat(in unsigned long long startpos, in acstring entityid); attributes attribute type description entityid acstring the entity id for this uri. available after onstartrequest. read only.
exceptions thrown ns_error_not_resumable if this load is not resumable. methods asyncopenat() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) open this channel, and read starting at the specified offset. the request given to the nsistreamlistener will be qiable to nsiresumableinfo. void asyncopenat( in nsistreamlistener listener, in nsisupports c...
nsISearchEngine
he parameter to add. value the value to pass. if value is "{searchterms}", it will be substituted with the user-entered data when retrieving the submission. must not be null. responsetype since an engine can have several different request urls, differentiated by response types, this parameter selects a request to add parameters to. if null, will default to "text/html"
exceptions thrown ns_error_invalid_arg if name or value are null. ns_error_failure if the search engine is read-only. getsubmission() gets a nsisearchsubmission object that contains information about what to send to the search engine, including the uri and postdata, if applicable. nsisearchsubmission getsubmission( in astring data, [optional] in astring responsetype, [op...
nsISelectionController
ng reflow. this is dangerous for some objects. see bug 418470, comment 12 for details. void scrollselectionintoview( in short type, in short region, in short flags ); parameters type the selection to scroll into view. (selectiontype) region the region inside the selection to scroll into view. (selectionregion) flags one of the scroll_* constants.
exceptions thrown missing
exception missing description selectall() will select the whole page. void selectall(); parameters none. setcaretenabled() set the caret as enabled or disabled. an enabled caret will draw or blink when made visible. a disabled caret will never show up. can be called any time. void setcaretenabled( in boolean enabled ); parameters enabled pr_true ...
nsISessionStartup
ts constant value description no_session 0 there's no data available from the previous session. recover_session 1 the last session crashed. it will either be restored or about:sessionrestore will be displayed. resume_session 2 the previous session should be restored at startup. defer_session 3 the previous session is viable but shouldn't be restored without explicit action (with the
exception of app tabs, which are always restored in this case). methods dorestore() determines whether or not there is a session to restore. boolean dorestore(); parameters none. return value true if the session should be restored, otherwise false. ...
nsISocketProvider
t apply any credentials when establishing a connection. for example, an ssl connection would not send any client-certificates if this flag is set. 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. for example, ssl via a socks proxy. parameters are the same as newsocket() with the
exception of afiledesc, which is an input parameter instead. void addtosocket( in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, in prfiledescstar afiledesc, out nsisupports asecurityinfo ); parameters afamily the address family for this socket (pr_af_inet or pr_af_inet6). ahost the hostname for this connect...
nsIStackFrame
inherits from: nsisupports last changed in gecko 1.7 method overview string tostring(); attributes attribute type description caller nsistackframe read only. filename string filename location. this is the location that caused the error, which may or may not be a source file location. for example, standard language errors would generally have the same location as their top stack entry. file parsers may put the location of the file they were parsing, and so forth. null indicates "no data" read only. language pruint32 see nsiprogramminglanguage for a list of language constants. read only. languagename string see nsiprogramminglanguage for a list of language constants. ...
nsIStreamListener
a is to be read. aoffset number of bytes that were sent in previous ondataavailable() calls for this request. in other words, the sum of all previous count parameters. if that number is greater than or equal to 2^32, this parameter will be pr_uint32_max (2^32 - 1). acount the number of bytes available for reading. you must read all of these bytes before returning to the caller. note: throwing an
exception will cancel the request. ...
nsIStringBundleOverride
tring bundle. note that these keys may not exist in the original string bundle. getstringfromname() get the override value for a particular key in a particular string bundle. astring getstringfromname( in autf8string url, in acstring key ); parameters url the url of the original string bundle whose keys are to be overridden. key the key to be overridden. return value the override value. an
exception is thrown if the key has not been overridden. however, no
exception is thrown if the original string bundle did not have the key. ...
nsIStringEnumerator
re(); methods getnext() called to retrieve the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmoreelements() which returns pr_true. this method is generally called within a loop to iterate over the strings in the enumerator. astring getnext(); parameters none. return value the next string in the enumerator. throws an
exception if there are no more strings. hasmore() called to determine whether or not the enumerator has any strings that can be returned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getnext() calls. does not affect internal state of enumerator. boolean hasmore(); parameters none. r...
nsISupports
face pointer, aresult, returned by queryinterface must be released by a call to release() when it is no longer needed. queryinterface is a symmetric, transitive, and reflexive operator. void queryinterface( in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result ); parameters uuid the uuid of the requested interface result the resulting interface pointer.
exceptions thrown ns_error_no_interface the requested interface is not available. violates the xpcom interface guidelines release() notifies the object that an interface pointer has been destroyed and any resources the object held on behalf of the client can be released. nsrefcnt release(); parameters none. return value an integer value that is generally ignored. remarks the method d...
nsISupportsPriority
.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) this interface does not strictly define what happens when the priority of an object is changed. an implementation of this interface is free to define the side-effects of changing the priority of an object. in some cases, changing the priority of an object may be disallowed (resulting in an
exception being thrown) or may simply be ignored. method overview void adjustpriority(in long delta); attributes attribute type description priority long the object's priority. it can be modified to change the priority of the object. typical priority values are defined in the idl file as priority_highest ... priority_lowest. the implementation is free to truncate a given priority value to whatev...
nsITaskbarPreview
ver it. by default, this is an empty string. visible boolean indicates whether or not the preview is visible; by default, this is false. note: changing this value is computationally expensive for tab previews, because doing so causes the proxy window to be destroyed and rebuilt, then re-registered with the taskbar. if any step of that process fails, an
exception is thrown. for window previews, changing this value is computationally trivial. methods invalidate() invalidates the taskbar's cached image of the preview, forcing a redraw if necessary. void invalidate(); parameters none. see also nsitaskbarpreviewcontroller nsitaskbartabpreview nsitaskbarwindowpreview nsitaskbarpreviewbutton nsiwintaskbar ...
nsITaskbarProgress
and maxvalue parameters are optional and should be supplied when state is one of state_normal, state_error or state_paused. void setprogressstate( in nstaskbarprogressstate state, in unsigned long long currentvalue, optional in unsigned long long maxvalue optional ); parameters state one of the state constants. currentvalue the current progress value. maxvalue the maximum progress value.
exceptions thrown ns_error_illegal_value if currentvalue is greater than maxvalue. ns_error_invalid_arg if state is state_no_progress or state_indeterminate, and either currentvalue or maxvalue is not 0. see also nsiwintaskbar windows 7 taskbar apis ...
nsIToolkitProfile
lfile the location of the profile directory. read only. methods lock() locks the profile using platform-specific locking methods. nsiprofilelock lock( out nsiprofileunlocker aunlocker ); parameters aunlocker on error, contains an nsiprofileunlocker object you can use to unlock the profile. note: the unlocker object cannot be returned to javascript as the error causes an
exception to be thrown. the unlocker object is only available in gecko 34 or later when running on windows vista or later. return value an nsiprofilelock object which holds a profile lock as long as you hold a reference to it. example: var profile = profilelist.getnext().queryinterface(ci.nsitoolkitprofile); var locker = profile.lock({}); remove() removes the profile from the registry of profiles. voi...
nsIURIFixup
racter set. fixup_flag_fix_scheme_typos 8 fix common scheme typos. methods createexposableuri() converts an internal uri (for example a wysiwyg uri) into one which we can expose to the user, for example on the url bar. nsiuri createexposableuri( in nsiuri auri ); parameters auri the uri to be converted. return value the converted, exposable uri, as an nsiuri.
exceptions thrown ns_error_unknown_protocol when we can not get a protocol handler service for the uri scheme. ns_error_malformed_uri when the exposable portion of auri is malformed. createfixupuri() converts the specified string into a uri, first attempting to correct any errors in the syntax or other vagaries. returns a well formed uri or nsnull if it cannot. nsiuri createfixupuri( in autf8st...
nsIUTF8StringEnumerator
boolean hasmore(); methods getnext() returns the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmore(), which returns pr_true. this method is generally called within a loop to iterate over the strings in the enumerator. autf8string getnext(); parameters none. return value the next string in the enumerator. throws an
exception if there are no more strings. hasmore() reports whether or not the enumerator has any strings that can be returned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getnext() calls. calling this method doesn't affect the internal state of the enumerator. boolean hasmore(); pa...
nsIWeakReference
to look and act exactly like (a proxied) nsisupports.queryinterface(). do not hold on to the produced interface permanently; that would defeat the purpose of using a non-owning nsiweakreference in the first place. void queryreferent( in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result ); parameters uuid the uuid of the requested interface. result the resulting interface pointer.
exceptions thrown ns_error_null_pointer the referent no longer exists. ns_error_no_interface the requested interface is not available. remarks this interface was frozen for gecko 0.9.9. see bug 48726 for details. from gecko 2.0 interfaces are no longer frozen. see also nsisupports.queryinterface() nsisupportsweakreference ...
nsIWritablePropertyBag
introduced gecko 1.8 inherits from: nsipropertybag last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void deleteproperty(in astring name); void setproperty(in astring name, in nsivariant value); methods deleteproperty() delete a property with the given name. void deleteproperty( in astring name ); parameters name property to delete.
exceptions thrown ns_error_failure if a property with that name doesn't exist. setproperty() set a property with the given name to the given value. if a property already exists with the given name, it is overwritten. void setproperty( in astring name, in nsivariant value ); parameters name property to set the value of. value value to set the property to. ...
nsIXFormsModelElement
.5 / thunderbird 1.5 / seamonkey 1.0) method overview nsidomdocument getinstancedocument(in domstring instanceid); void rebuild(); void recalculate(); void refresh(); void revalidate(); methods getinstancedocument() nsidomdocument getinstancedocument( in domstring instanceid ); parameters instanceid the id of the instance element to be returned. return value an nsidomdocument.
exceptions thrown dom
exception if there is no matching instance data. rebuild() signals the xforms processor to rebuild any internal data structures used to track computational dependencies within the given xforms model. void rebuild(); parameters none. recalculate() signals the xforms processor to perform a full recalculation of the given xforms model. note: script invocation is not necessarily equival...
nsIXmlRpcClient
ld any of the supported input types. return value will be converted as follows: i4 or int: nsisupportsprint32 boolean: nsisupportsprbool string: nsisupportscstring double: nsisupportsdouble datetime.iso8601: nsisupportsprtime base64: nsisupportscstring array: nsisupportsarray struct: nsidictionary faults (server side errors) are indicated by returning ns_error_failure. via nsixpconnect::getpending
exception()->data a nsixmlrpcfault object can be retreieved with more information on the fault. parameters listener a nsixmlrpcclientlistener that will get notified of xml-rpc events ctxt a context to be passed on to the listener methodname remote method to call arguments array of arguments to pass to the remote method count void asynccall ( in nsixmlrpcclientlistener listener, in nsisup...
nsIXmlRpcFault
obsolete since gecko 1.9 (firefox 3)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. extensions/xml-rpc/idl/nsixmlrpcclient.idlscriptable an xml-rpc
exception. xml-rpc server fault codes are returned wrapped in this; access it using nsixpconnect.getpending
exception->data. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void init(in print32 faultcode, in string faultsring); string tostring(); attributes attribute type description faultcode print32 read only. faultstring string read only. methods init() void getdata( in print32 faultco...
nsIMsgSearchValue
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchvalue.idl #include "nsmsgsearchcore.idl" interface nsimsgfolder; [scriptable, uuid(783758a0-cdb5-11dc-95ff-0800200c9a66)] interface nsimsgsearchvalue : nsisupports { // type of object attribute nsmsgsearchattribvalue attrib; // accessing these will throw an
exception if the above // attribute does not match the type! attribute astring str; attribute nsmsgpriorityvalue priority; attribute prtime date; // see nsmsgmessageflags.idl and nsmsgfolderflags.idl attribute unsigned long status; attribute unsigned long size; attribute nsmsgkey msgkey; attribute long age; // in days attribute nsimsgfolder folder; attribute nsmsglabelvalue label; attribute nsmsgjunkstatus...
XPIDL Syntax
-7a / %x30-39 / "_") parens = "(" 1*(any char except ")") ")" functionality not used in xpidl the libidl parser we use is more powerful than xpidl itself can understand. the following is a list of potential features which are parseable but may not result in expected code: struct, union, and enumerated types array declarators (appears to be supported in xpidl_header.c but not xpidl_typelib.c)
exception declarations module declarations variable arguments (that makes the abnf get more wonky) sequence types max-length strings fixed-point numbers "any" and "long double" types. pyxpidl syntax idlfile = *(cdata / include / interface / typedef / native) typedef = "typedef" identifer identifier ";" native = [attributes] "native" identifier "(" nativeid ")" interface = [attributes] "interfac...
Xray vision
out examples like this, you can use the scratchpad in browser context for the code snippet, and the browser console to see the expected output. because code running in scratchpad's browser context has chrome privileges, any time you use it to run code, you need to understand exactly what the code is doing. that includes the code samples in this article. xray semantics for object and array the
exceptions are object and array: their interesting state is in javascript, not c++. this means that the semantics of their xrays have to be independently defined: they can't simply be defined as "the c++ representation". the aim of xray vision is to make most common operations simple and safe, avoiding the need to access the underlying object except in more involved cases. so the semantics defined for obj...
Address Book examples
a card with a particular email address, you can use the cardforemailaddress function that will match against multiple email addresses stored in one card. again, this function returns the first match that it finds in the collection, or null. let collection = ... let card = collection.cardforemailaddress("foo@bar.invalid.com"); note: both of these functions may raise an ns_error_not_implemented
exception if the collection has not implemented that function. this is currently true in the case of ldap, but may be true in other cases as well. how do i search for multiple contacts? formulate a boolean search string (see nsiabcard for built-in property names): var searchquery = "(or(primaryemail,bw,@v)(nickname,bw,@v)(and(ismaillist,=,true)(notes,bw,@v)))"; searchquery = searchquery.replace(/@v/g, e...
Index
nd creation of an extension please read building a thunderbird extension. 84 demo addon this demo add-on has been created by jonathan protzenko for his presentation at mozcamp 2011. it shows how to achieve various goals in a working live example, such as working with gloda. 85 error reporting tools thunderbird currently, thunderbird tends to eat a lot of
exceptions. some make it to the error console, most don't. there are deep fixes to the platform needed (e.g. bug 493414), but in the meantime, it would be helpful to be able to get useful output on stderr about
exceptions, events and pretty-printed objects. 86 faq add-ons, extensions, thunderbird the old contents of this faq page were duplicated in the setting up extension development ...
Mail composition back end
lder) as well as the ability to store messages for features like "drafts" and "templates". several (but not all) of these interfaces are specified in idl. this will change in the coming weeks and allow for developers to write javascript to take advantage of the back end services. also, i will talk about some features though they may not be complete as of yet. i will try to make comments for these
exceptions. sending messages the primary responsibility of the back end is for the creation and sending of rfc822 messages. the interface that accomplishes this task is the nsimsgsend interface. 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...
Mailnews and Mail code review requirements
riate person. super-review is required in certain situations: significant architectural refactoring, any change to any api, all changes that affect how code modules interact. see the full super-review policy for more details. unit test rules patches are required to include automated tests which are run during make check or via mozmill in thunderbird, but submitters are encouraged to request
exceptions from reviewers in cases where the cost is believed to outweigh the benefit. once unit tests are committed, the in-testsuite+ flag should be set on the bug. unit tests must be included in patches and reviewed just like any other code. if an automated test framework is needed but is not yet available, the developer is encouraged to write appropriate test code and commit it. a bug should be filed...
Using JS in Mozilla code
js language features proper tail calls are not implemented. js standard library features feature standard can be used in code new proxy(target, handler) es2015 yes, but getprototypeof and setprototypeof handlers are not yet implemented. ...
Using tab-modal prompts
es here', input, 'check text, if no text, checkbox is not shown', check]); //this here is just an alert, showing the values of the prompt prompt.alert.apply(null, ['title not shown in modal', 'user clicked ok: ' + ok + '\n' + 'checked: ' + check.value + '\ninput value: ' + input.value]); note: because the prompts are shown in a tab, if the tab is closed while the prompt is open it will throw an
exception. /*
exception: prompt aborted by user undefined:425 */ ...
Library
the defined api, if it's a function. this parameter should not be provided if the api is an exported data symbol. argtype1...argtypen zero or more parameter ctype may be specified for the parameters of the function being declared. these should not be provided if the api is an exported data symbol rather than a function. return value a functiontype cdata object representing the declared api.
exceptions thrown ctypes ctype functiontype abi typeerror the return type was specified as an array. alternative syntax another use for ctypes.declare is to get non-function/non-methods from libraries. the syntax for this is seen in firefox codebase here: //github.com/realityripple/uxp/blob/master/js/src/ctypes/library.cpp?offset=0#271 this shows that we can also supply only two arguments t...
Initialization and Destruction - Plugins
n. this table is filled out by the plug-in during the initialization call. the function tables also contain version information that the plug-in checks to verify that it is compatible with the api capabilities provided by the application. to check this information, use npn_version. no plug-in api calls can take place in either direction until the initialization completes successfully, with the
exception of the functions np_initialize and np_shutdown, which are not in the function tables. however, because np_initialize is called at the end of the initialization process, you can call other methods, such as npn_memalloc and npn_status, from np_initialize. instance creation after initialization, the plug-in instance is created. more than one instance of the same plug-in can exist if a single page ...
Scripting plugins - Plugins
entifier npn_identifierisstring npn_utf8fromidentifier npn_intfromidentifier npobject npn_construct (since firefox 3.0b1) npn_createobject npn_retainobject npn_releaseobject npn_invoke npn_invokedefault npn_enumerate (since mozilla 1.9a1) npn_evaluate npn_getproperty npn_setproperty npn_removeproperty npn_hasproperty npn_hasmethod npn_set
exception npclass « previousnext » ...
Gecko Plugin API Reference - Plugins
n_getstringidentifiers npn_getintidentifier npn_identifierisstring npn_utf8fromidentifier npn_intfromidentifier npobject npn_createobject npn_retainobject npn_releaseobject npn_invoke npn_invokedefault npn_evaluate npn_getproperty npn_setproperty npn_removeproperty npn_hasproperty npn_hasmethod npn_set
exception npclass structures npanycallbackstruct npbyterange npembedprint npevent npfullprint npp np_port npprint npprintcallbackstruct nprect npregion npsaveddata npsetwindowcallbackstruct npstream npwindow constants error codes result codes plug-in version constants version feature constants external resources external projects and articles for plugin crea...
DOM Inspector internals - Firefox Developer Tools
generic ui fixture.) toolboxoverlay.xul this overlay fills in the inspector toolbox, including toolbar buttons and the location bar and its "inspect" button. toolboxoverlay.xul also defines the structure of the menubar, without defining the contents of any of the menus themselves. popupoverlay.xul this overlay defines most of the static structure of the menus in the menubar, with some
exceptions. for obvious reasons, the contents of dynamic menus are not defined here. the dynamic menus include the inspect menus' ("inspect content document" and "inspect chrome document") popups from the file menu, and the "document viewer" and "object viewer" menus from the view menu. the preference menuitems in the view menu that affect only the dom nodes viewer ("blink selected element", et cetera) are...
Ignore a source - Firefox Developer Tools
the details of selected sources. you can enable or disable ignoring a source file in a couple of ways: in the source list pane, right-click the filename and choose ignore source (or unignore source). if the source file is displayed in the source pane, click the "eye" icon at the bottom. when a source file is ignored: any breakpoints it may have defined are disabled. when “pause on
exceptions” is enabled in the debugger settings, the debugger won’t pause when an
exception is thrown in the ignored source; instead it waits until (and if) the stack unwinds to a frame in a source that isn’t ignored. the debugger skips through ignored sources when stepping. ...
Debugger.Memory - Firefox Developer Tools
ler functions, debugger.memory inherits accessor properties that store handler functions for spidermonkey to call when given events occur in debuggee code. unlike debugger‘s hooks, debugger.memory’s handlers’ return values are not significant, and are ignored. the handler functions receive the debugger.memory’s owning debugger instance as their this value. the owning debugger’s uncaught
exceptionhandler is still fired for errors thrown in debugger.memory hooks. on a new debugger.memory instance, each of these properties is initially undefined. any value assigned to a debugging handler must be either a function or undefined; otherwise a typeerror is thrown. handler functions run in the same thread in which the event occurred. they run in the compartment to which they belong, not in a deb...
Debugger-API - Firefox Developer Tools
it is for use by javascript code. javascript is both the debuggee language and the tool implementation language, so the qualities that make javascript effective on the web can be brought to bear in crafting tools for developers. as is expected of javascript apis, debugger is a sound interface: using (or even misusing) debugger should never cause gecko to crash. errors throw proper javascript
exceptions. it is an intra-thread debugging api. both the debuggee and the code using debugger to observe it must run in the same thread. cross-thread, cross-process, and cross-device tools must use debugger to observe the debuggee from within the same thread, and then handle any needed communication themselves. (firefox’s builtin tools have a protocol defined for this purpose.) in gecko, the d...
The Firefox JavaScript Debugger - Firefox Developer Tools
to guides. open the debugger pretty-print a minified file search use a source map pause execution you probably want to pause the execution of your code, in order to see what is going on at various points. there are multiple ways to tell the debugger how and when to pause: set a breakpoint set a conditional breakpoint set an xhr breakpoint set event listener breakpoints break on
exceptions use watchpoints for property reads and writes break on dom mutation disable breakpoints control execution what can you do after execution pauses? step through code black box a source debug worker threads debug eval sources look at values you probably want to see the value of variables or expressions, either during execution or when it is paused. set a logpoint set watch exp...
Index - Firefox Developer Tools
key down as well (so to open the profiler, use shift + function + f5). 117 how to these articles describe how to use the debugger. 118 access debugging in add-ons 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): 119 breaking on
exceptions when an
exception occurs, the line where it occurs is highlighted in the source pane, with a squiggly red line under the problematic code. a tooltip describes the
exception. starting in firefox 80, a disclosure triangle within the tooltip reveals a stack trace. 120 debug eval sources you can debug javascript code that is evaluated dynamically, either as a string ...
Migrating from Firebug - Firefox Developer Tools
panel. those panels allow you to enable and disable single or all breakpoints and to remove single breakpoints or all of them at once. they do currently only allow to set script breakpoints. xhr, dom, cookie and error breakpoints are not supported yet (see bug 821610, bug 1004678, bug 895893 and bug 1165010). while there are no breakpoints for single javascript errors, there is a setting pause on
exceptions within the debugger panel options. step through code once the script execution is stopped, you can step through the code using the continue (f8), step over (f10), step into (f11) and step out (shift+f11) options. they work the same in both tools. examine call stack when the script execution is paused, firebug displays the function call stack within its stack side panel. in there the function...
Network request details - Firefox Developer Tools
se header, if one is available. a raw toggle button in the section heading controls whether the headers are shown with formatting, or as plain, unformatted text. note that the keys in the response header are all in lowercase, while the request headers keys are not. http/2 requires that all headers be lowercase; response headers are shown as they are received from the server. (there may be some
exceptions, such as x-firefox-spdy, which is added by firefox.) you can copy some or all of the response header in json format by using the context menu: if you select copy, a single key word, value pair is copied. if you select copy all, the entire header is copied in json format, giving you something like this (after running the results through a json validator): { "response headers (1.113 kb)": ...
Console messages - Firefox Developer Tools
uting, check out the metabug and its dependencies. logging messages logged from shared workers, service workers, add-ons, and chrome workers are not shown by default. use the filtering feature to show them. the logging category includes messages logged using the console api. the web console supports the following console api messages: assert() clear() count() dir() dirxml() error()
exception() group() groupend() info() log() table() time() timeend() trace() warn() the console prints a stack trace for all error messages, like this: function foo() { console.error("it explodes"); } function bar() { foo(); } function dostuff() { bar(); } dostuff(); server server-side log messages was introduced in firefox 43, but removed in firefox 56. you can install the chrome ...
ANGLE_instanced_arrays.drawArraysInstancedANGLE() - Web APIs
line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. primcount a glsizei specifying the number of instances of the range of elements to execute. return value none.
exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if first, count or primcount are negative, a gl.invalid_value error is thrown. if gl.current_program is null, a gl.invalid_operation error is thrown. examples var ext = gl.getextension('angle_instanced_arrays'); ext.drawarraysinstancedangle(gl.points, 0, 8, 4); specifications specification status...
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
ay buffer. possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying an offset in the element array buffer. must be a valid multiple of the size of the given type. primcount a glsizei specifying the number of instances of the set of elements to execute. return value none.
exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if offset is a invalid multiple of the size of the given type, a gl.invalid_operation error is thrown. if count or primcount are negative, a gl.invalid_value error is thrown. examples var ext = gl.getextension('angle_instanced_arrays'); ext.drawelementsinstancedangle(gl.points, 2, gl.unsigned_short, 0, 4); sp...
AbortController - Web APIs
tn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is called, the fetch() promise rejects with a dom
exception named aborterror. you can find a full working example on github — see abort-api (see it running live also). specifications specification status comment domthe definition of 'abortcontroller' in that specification. living standard initial definition ...
AbortSignal - Web APIs
click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is called, the fetch() promise rejects with an aborterror. current version of firefox rejects the promise with a dom
exception you can find a full working example on github — see abort-api (see it running live also). specifications specification status comment domthe definition of 'abortsignal' in that specification. living standard initial definition ...
AesGcmParams - Web APIs
alongside the encrypted message. additionaldata optional a buffersource. this contains additional data that will not be encrypted but will be authenticated along with the encrypted data. 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. this gives you a way to authenticate associated data without having to encrypt it. the bit length of additionaldata must be ≤ 264-1. the additionaldata property is optional and may be omitted without compromising the security of the encryption operation. taglength optional a number. this determines the size in bits of the authentication tag generated in the encryption operation and u...
AnalyserNode.fftSize - Web APIs
epresenting the window size of the fft, given in number of samples. a higher value will result in more details in the frequency domain but fewer details in the time domain. must be a power of 2 between 252^5 and 2152^15, so one of: 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, and 32768. defaults to 2048. note: if its value is not a power of 2, or it is outside the specified range, a dom
exception with the name indexsizeerror is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 ...
AnalyserNode.maxDecibels - Web APIs
ng the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc. the default value is -30 db. when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of maxdecibels or higher will be returned as +1.0 or 255, respectively. note: if a value less than or equal to analysernode.mindecibels is set, an indexsizeerror
exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audi...
AnalyserNode.minDecibels - Web APIs
e for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc. the default value is -100 db. when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of mindecibels or lower will be returned as 0.0 or 0, respectively. note: if a value greater than analysernode.maxdecibels is set, an index_size_err
exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var aud...
AnalyserNode.smoothingTimeConstant - Web APIs
erlap the previous and current buffer quite a lot while computing the value", which essentially smoothes the changes across analysernode.getfloatfrequencydata/analysernode.getbytefrequencydata calls. in technical terms, we apply a blackman window and smooth the values over time. the default value is good enough for most cases. note: if a value outside the range 0–1 is set, an index_size_err
exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). if you ...
Animation.cancel() - Web APIs
the web animations api's cancel() method of the animation interface clears all keyframeeffects caused by this animation and aborts its playback. when an animation is cancelled, its starttime and currenttime are set to null. syntax animation.cancel(); parameters none. return value none.
exceptions this method doesn't directly throw
exceptions; however, if the animation's playstate is anything but "idle" when cancelled, the current finished promise is rejected with a dom
exception named aborterror. specifications specification status comment web animationsthe definition of 'animation.cancel()' in that specification. working draft editor's draft. ...
Animation.pause() - Web APIs
throws an invalidstateerror if the animation's currenttime is unresolved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. ...
AudioBuffer() - Web APIs
e in hz for the buffer. the default is the sample rate of the context used in constructing this object. user agents are required to support sample rates from 8,000 hz to 96,000 hz (but are allowed to go farther outside this range). deprecated parameters context a reference to an audiocontext. this parameter was removed from the spec. return value a new audiobuffer object instance.
exceptions notsupportederror one or more of the options are negative or otherwise has an invalid value (such as numberofchannels being higher than supported, or a samplerate outside the nominal range). rangeerror there isn't enough memory available to allocate the buffer. specifications specification status comment web audio apithe definition of 'audiobuffer' in that specif...
AudioBuffer.copyFromChannel() - Web APIs
); parameters destination a float32array to copy the channel's samples to. channelnumber the channel number of the current audiobuffer to copy the channel data from. startinchannel optional an optional offset into the source channel's buffer from which to begin copying samples. if not specified, a value of 0 (the beginning of the buffer) is assumed by default. return value undefined.
exceptions indexsizeerror one of the input parameters has a value that is outside the accepted range: the value of channelnumber specifies a channel number which doesn't exist (that is, it's greater than or equal to the value of numberofchannels on the channel). the value of startinchannel is outside the current range of samples that already exist in the source buffer; that is, it's greater than ...
AudioBuffer.getChannelData() - Web APIs
var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var nowbuffering = myarraybuffer.getchanneldata(channel); parameters channel the channel property is an index representing the particular channel to get data for. an index value of 0 represents the first channel. if the channel index value is greater than of equal to audiobuffer.numberofchannels, an index_size_err
exception will be thrown. return value a float32array. example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryse...
AudioBufferSourceNode.start() - Web APIs
hrough a 10-second audio buffer is still 5. duration optional the duration of the sound to be played, specified in seconds. if this parameter isn't specified, the sound plays until it reaches its natural conclusion or is stopped using the stop() method. using this parameter is functionally identical to calling start(when, offset) and then calling stop(when+duration). return value undefined.
exceptions typeerror a negative value was specified for one or more of the three time parameters. please don't attempt to tamper with the laws of temporal physics. invalidstateerror start() has already been called. you can only call this function once during the lifetime of an audiobuffersourcenode. examples the most simple example just starts the audio buffer playing from the beginning — you do...
AudioContext.close() - Web APIs
ences 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. the returned promise resolves when all audiocontext-creation-blocking resources have been released. this method throws an invalid_state_err
exception if called on an offlineaudiocontext. syntax var audioctx = new audiocontext(); audioctx.close().then(function() { ... }); await audioctx.close(); returns a promise that resolves with void. example the following snippet is taken from our audiocontext states demo (see it running live.) when the stop button is clicked, close() is called. when the promise resolves, the example is reset to its ...
AudioContext.resume() - Web APIs
syntax completepromise = audiocontext.resume(); parameters none. return value a promise that resolves when the context has resumed. the promise is rejected if the context has already been closed. ...
AudioContext.suspend() - Web APIs
the suspend() method of the audiocontext interface suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing cpu/battery usage in the process — this is useful if you want an application to power down the audio hardware when it will not be using an audio context for a while. this method will cause an invalid_state_err
exception to be thrown if called on an offlineaudiocontext. syntax var audioctx = new audiocontext(); audioctx.suspend().then(function() { ... }); returns a promise that resolves with void. the promise is rejected if the context has already been closed. 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 ...
AudioDestinationNode - Web APIs
of an audio graph in a given context — usually the speakers of your device. it can also be the node that will "record" the audio data when used with an offlineaudiocontext. audiodestinationnode has no output (as it is the output, no more audionode can be linked after it in the audio graph) and one input. the number of channels in the input must be between 0 and the maxchannelcount value or an
exception is raised. the audiodestinationnode of a given audiocontext can be retrieved using the audiocontext.destination property. number of inputs 1 number of outputs 0 channel count mode "explicit" channel count 2 channel interpretation "speakers" properties inherits properties from its parent, audionode. audiodestinationnode.maxch...
AudioScheduledSourceNode.start() - Web APIs
ing-point number indicating the offset, in seconds, into the audio buffer where playback should begin. if 0 is passed then the playback will start from the beginning. duration optional a floating-point number indicating the duration, in seconds, to be played. if no value is passed then the duration will be equal to the length of the audio buffer minus the offset value return value undefined
exceptions invalidstatenode the node has already been started. this error occurs even if the node is no longer running because of a prior call to stop(). rangeerror the value specified for when is negative. example this example demonstrates how to create an oscillatornode which is scheduled to start playing in 2 seconds and stop playing 1 second after that. the times are calculated by adding the d...
AudioScheduledSourceNode.stop() - Web APIs
ioscheduledsourcenode.stop([when]); parameters when optional the time, in seconds, at which the sound should stop playing. this value is specified in the same time coordinate system as the audiocontext is using for its currenttime attribute. omitting this parameter, specifying a value of 0, or passing a negative value causes the sound to stop playback immediately. return value undefined
exceptions invalidstatenode the node has not been started by calling start(). rangeerror the value specified for when is negative. example this example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second. the stop time is determined by taking the audio context's current time from audiocontext.currenttime and adding 1 second. context = new...
AudioWorkletGlobalScope.registerProcessor - Web APIs
or of a class derived from audioworkletprocessor. note: a key-value pair { name: constructor } is saved internally in the audioworkletglobalscope once the processor is registered. the name is to be referred to when creating an audioworkletnode based on the registered processor. a new processor by the given name is internally created and associated with the new node. return value undefined
exceptions notsupportederror the name is an empty string, or a constructor under the given name is already registered. registering the same name twice is not allowed. 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. examples in this examp...
AudioWorkletNode() - Web APIs
tional an object containing the initial values of custom audioparam objects on this node (in its parameters property), with key being the name of a custom parameter and value being its initial value. processoroptions optional any additional data that can be used for custom initialization of the underlying audioworkletprocessor. return value the newly constructed audioworkletnode instance.
exceptions notsupportederror the specified options.outputchannelcount is 0 or larger than the current implementation supports. indexsizeerror the length of options.outputchannelcount array does not match options.numberofoutputs. example for a complete example demonstrating user-defined audio processing, see the audioworkletnode page. specifications specification status comment ...
AudioWorkletNode.onprocessorerror - Web APIs
the onprocessorerror property of the audioworkletnode interface defines an event handler function to be called when the processorerror event fires. this occurs when the underlying audioworkletprocessor behind the node throws an
exception in its constructor, the process method, or any user-defined class method. once an
exception is thrown, the processor (and thus the node) will output silence throughout its lifetime. syntax audioworkletnode.onprocessorerror = function() { ... }; examples // fill in example snippet specifications specification status comment web audio apithe definition of 'onprocessorerror' in that specification. working draft ...
AudioWorkletProcessor.process - Web APIs
me, beginning as soon as inputs are found that contain zero-channels. an example of such a node is the delaynode — it has a tail-time equal to its delaytime property. note: an absence of the return statement means that the method returns undefined, and as this is a falsy value, it is like returning false. omitting an explicit return statement may cause hard-to-detect problems for your nodes.
exceptions as the process() method is implemented by the user, it can throw anything. if an uncaught error is thrown, the node will emit an onprocessorerror event and will output silence for the rest of its lifetime. examples in this example we create an audioworkletprocessor that outputs white noise to its first output. the gain can be controlled by the customgain parameter. class whitenoiseprocessor ...
BaseAudioContext.createBuffer() - Web APIs
the size of a sample in bytes multiplied by numofchannels). to determine the length to use for a specific number of seconds of audio, use numseconds * samplerate. samplerate the sample rate of the linear audio data in sample-frames per second. all browsers must support sample rates in at least the range 8,000 hz to 96,000 hz. returns an audiobuffer configured based on the specified options.
exceptions notsupportederror one or more of the options are negative or otherwise has an invalid value (such as numberofchannels being higher than supported, or a samplerate outside the nominal range). rangeerror there isn't enough memory available to allocate the buffer. examples first, a couple of simple trivial examples, to help explain how the parameters are used: var audioctx = new audiocont...
BaseAudioContext.createIIRFilter() - Web APIs
of this array is 20, and at least one value must be nonzero. feedback an array of floating-point values specifying the feedback (denominator) coefficients for the transfer function of the iir filter. this array may have up to 20 members, the first of which must not be zero. return value an iirfilternode implementing the filter with the specified feedback and feedforward coefficient arrays.
exceptions invalidstateerror all of the feedforward coefficients are 0, and/or the first feedback coefficient is 0. notsupportederror one or both of the input arrays exceeds 20 members. specifications specification status comment web audio apithe definition of 'createiirfilter()' in that specification. working draft ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
an. these are unitless values. phaseresponseoutput a float32array to receive the computed phase response values in radians for each frequency value in the input frequencyarray. for any frequency in frequencyarray whose value is outside the range 0.0 to samplerate/2 (where samplerate is the sample rate of the audiocontext), the corresponding value in this array is nan. return value undefined
exceptions invalidaccesserror the three arrays provided are not all of the same length. example in the following example we are using a biquad filter on a media stream (for the full demo, see our stream-source-buffer demo live, or read the source.) as part of this demo, we get the frequency responses for this biquad filter, for five sample frequencies. we first create the float32arrays we need, one ...
Blob.arrayBuffer() - Web APIs
blob interface returns a promise that resolves with the contents of the blob as binary data contained in an arraybuffer. syntax var bufferpromise = blob.arraybuffer(); blob.arraybuffer().then(buffer => /* process the arraybuffer */); var buffer = await blob.arraybuffer(); parameters none. returns a promise that resolves with an arraybuffer that contains the blob's data in binary form.
exceptions while this method doesn't throw
exceptions, it may reject the promise. this can happen, for example, if the reader used to fetch the blob's data throws an
exception. any
exceptions thrown while getting the data will be converted into rejections. usage notes while similar to the filereader.readasarraybuffer() method, arraybuffer() returns a promise rather than being an event-based api, as is t...
Bluetooth.getAvailability() - Web APIs
value). note: user might not allow use of web bluetooth api, even if getavailability() returned true (navigator.bluetooth.requestdevice() might not resolve with a bluetoothdevice). also, user can configure user agent to return a fixed value instead of a real one. syntax var readerpromise = bluetooth.getavailability(); parameters none. return value a promise that resolves with boolean.
exceptions this method doesn't throw any
exceptions. examples the following snippet prints out a message in the console specifying wheter or not bluetooth is supported: navigator.bluetooth.getavailability().then(available => { if (available) console.log("this device supports bluetooth!"); else console.log("doh! bluetooth is not supported"); }); specifications specification ...
Bluetooth.getDevices() - Web APIs
currently allowed to access, even the ones that are out of range or powered off. the program can detect when a device comes online or into range by watching for bluetooth advertisements by calling bluetoothdevice.watchadvertisements() on that device. syntax var readerpromise = bluetooth.getdevices(); parameters none. return value a promise that resolves with an array of bluetoothdevices.
exceptions this method doesn't throw any
exceptions. specifications specification status comment web bluetooththe definition of 'getdevices()' in that specification. draft initial definition. ...
Bluetooth.requestDevice() - Web APIs
ptions for the device request. the available options are: filters[]: an array of bluetoothscanfilters. this filter consists of an array of bluetoothserviceuuids, a name parameter, and a nameprefix parameter. optionalservices[]: an array of bluetoothserviceuuids. acceptalldevices: a boolean indicating that the requesting script can accept all bluetooth devices. the default is false.
exceptions typeerror the provided options do not makes sense. for example, options.filters is present and options.acceptalldevices is true, or if options.filters is not present and options.acceptalldevices is false. or options.filters is []. notfounderror there is no bluetooth device that matches the specified options. securityerror this operation is not permitted in this context due to security co...
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
y object instance. syntax var bytelengthqueuingstrategy = new bytelengthqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property. this is a non-negative integer defining the total number of chunks that can be contained in the internal queue before backpressure is applied. return value an instance of the bytelengthqueuingstrategy object.
exceptions none. examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... }, cancel(err) { console.log("stream error:", err); } }, queuingstrategy); var size = queuingstrategy.size(chunk); specifications specification status comment ...
CSS.registerProperty() - Web APIs
ing the name of the property being defined. syntax optional a domstring representing the expected syntax of the defined property. defaults to "*". inherits a boolean value defining whether the defined property should be inherited (true), or not (false). defaults to false. initialvalue optional a domstring representing the initial value of the defined property. return value undefined.
exceptions invalidmodificationerror the given name has already been registered. syntaxerror the given name isn't a valid custom property name (starts with two dashes, e.g. --foo). typeerror the required name and/or inherits dictionary members were not provided. examples the following will register a custom property, --my-color, using registerproperty(), as a color, give it a default value, and h...
CSSKeyframesRule - Web APIs
s rules in the media rule. methods as a cssrule, csskeyframesrule also implements the methods of that interface. it has three specific methods: csskeyframesrule.appendrule() inserts a new keyframe rule into the current csskeyframesrule. the parameter is a domstring containing a keyframe in the same format as an entry of a @keyframes at-rule. if it contains more than one keyframe rule, a dom
exception with a syntax_err is thrown. csskeyframesrule.deleterule() deletes a keyframe rule from the current csskeyframesrule. the parameter is the index of the keyframe to be deleted, expressed as a domstring resolving as a number between 0% and 100%. csskeyframesrule.findrule() returns a keyframe rule corresponding to the given key. the key is a domstring containing an index of the keyframe to be re...
CSSNumericValue.add() - Web APIs
the add() method of the cssnumericvalue interface adds a supplied number to the cssnumericvalue. syntax var cssmathsum = cssnumericvalue.add(double | cssnumericvalue); parameters number either a number or a cssnumericvalue. return value a cssmathsum
exceptions typeerror indicates that an invalid type was passed to the method. examples let mathsum = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); // prints "calc(23px + 4% + 3cm + 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'add' in that specification. working draft initial definition. ...
CSSNumericValue.div() - Web APIs
the div() method of the cssnumericvalue interface divides the cssnumericvalue by the supplied value. syntax var cssnumericvalue = cssnumericvalue.div(number); parameters number either a number or a cssnumericvalue. return value a cssmathproduct.
exceptions typeerror indicates that an invalid type was passed to the method. examples let mathproduct = css.px("24").div(css.percent("4")); // prints "calc(24px / 4%)" mathproduct.tostring(); specifications specification status comment css typed om level 1the definition of 'div' in that specification. working draft initial definition. ...
CSSNumericValue.equals() - Web APIs
cvalue interface returns a boolean indicating whether the passed value are strictly equal. to return a value of true, all passed values must be of the same type and value and must be in the same order. this allows structural equality to be tested quickly. syntax var boolean = cssnumericvalue.equals(number); parameters number either a number or a cssnumericvalue. return value a boolean.
exceptions none. examples as stated earlier, all passed values must be of the same type and value and must be in the same order. some of the following examples illustrate what happens when they are not. let cssmathsum = new cssmathsum(css.px(1), css.px(2)); let matchingcssmathsum = new cssmathsum(css.px(1), css.px(2)); // prints true console.log(cssmathsum.equals(matchingcssmathsum)); let othercssmath...
CSSNumericValue.mul() - Web APIs
the mul() method of the cssnumericvalue interface multiplies the cssnumericvalue by the supplied value. syntax var cssmathproduct = cssnumericvalue.mul(number); parameters number either a number or a cssnumericvalue. return value a cssmathproduct
exceptions typeerror indicates that an invalid type was passed to the method. examples let mathsum = css.px("23").mul(css.percent("4")).mul(css.cm("3")).mul(css.in("9")); // prints "calc(23px * 4% * 3cm * 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'mul' in that specification. working draft initial definition. ...
CSSNumericValue.parse() - Web APIs
the parse() method of the cssnumericvalue interface converts a value string into an object whose members are value and the units. syntax var cssnumericvalue = cssnumericvalue.parse(csstext); parameters csstext a string containing numeric and unit parts. return value a cssnumericvalue.
exceptions syntaxerror tbd examples the following returns a cssunitvalue object with a unit property equal to "px" and a value property equal to 42. let numvalue = cssnumericvalue.parse("42.0px"); specifications specification status comment css typed om level 1the definition of 'parse' in that specification. working draft initial definition. ...
CSSNumericValue.sub() - Web APIs
the sub() method of the cssnumericvalue interface subtracts a supplied number from the cssnumericvalue. syntax var cssmathsum = cssnumericvalue.sub(number); parameters number either a number or a cssmathsum. return value a cssmathsum
exceptions typeerror indicates that an invalid type was passed to the method. examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification. working draft initial definition. ...
CSSNumericValue.sum() - Web APIs
the sub() method of the cssnumericvalue interface subtracts a supplied number from the cssnumericvalue. syntax var cssmathsum = cssnumericvalue.sub(number); parameters number either a number or a cssmathsum return value a cssmathsum
exceptions typeerror indicates that an invalid type was passed to the method. examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification. working draft initial definition. ...
CSSNumericValue.toSum() - Web APIs
the tosum() method of the cssnumericvalue interface converts the object's value to a cssmathsum object to values of the specified unit. syntax var cssmathsum = cssnumericvalue.tosum(units); parameters units the units to convert to. return value a cssnumericvalue.
exceptions syntaxerror undefined typeerror indicates that an invalid type was passed to the method. examples let v = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); v.tostring() // => "calc(23px + 4% + 3cm + 9in)" v.tosum("px", "percent").tostring() // => "calc(1000.39px + 4%)" specifications specification status comment css typed om level 1the definition of 'tosum' in that specification. working draft initial definition. ...
CSSNumericValue.type - Web APIs
the type() method of the cssnumericvalue interface returns the type of cssnumericvalue, one of angle, flex, frequency, length, resolution, percent, percenthint, or time. syntax var cssnumerictype = cssnumericvalue.type(); parameters none. return value a cssnumerictype object.
exceptions none. examples let mathsum = css.px("23").sub(css.percent("4")).sub(css.cm("3")).sub(css.in("9")); // returns an object with the structure: {length: 1, percenthint: "length"} let cssnumerictype = mathsum.type(); specifications specification status comment css typed om level 1the definition of 'type' in that specification. working draft initial definition. ...
CSSPrimitiveValue.getStringValue() - Web APIs
the getstringvalue() method of the cssprimitivevalue interface is used to get a string value. if this css value doesn't contain a string value, a dom
exception is raised. syntax var stringvalue = cssprimitivevalue.getstringvalue(); return value a string value.
exceptions type description dom
exception an invalid_access_err is raised if the css value doesn't contain a string value. example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("display"); console.log(cssvalue.getstringvalue()); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.getstringvalue' in that specification. obsolete initial definition ...
CSSStyleDeclaration.item() - Web APIs
syntax var propertyname = style.item(index); parameters index is the index of the node to be fetched. the index is zero-based. return value propertyname is a domstring that is the name of the css property at the specified index. ...
CSSStyleDeclaration.removeProperty() - Web APIs
perty() method interface removes a property from a css style declaration object. syntax var oldvalue = style.removeproperty(property); parameters property is a domstring representing the property name to be removed. note that multi-word property names are hyphenated and not camel-cased. return value oldvalue is a domstring equal to the value of the css property before it was removed.
exceptions dom
exception no_modification_allowed_err: if the property or declaration block is read only. example the following javascript code removes the background-color css property from a selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specification status comment ...
CSSStyleDeclaration.setProperty() - Web APIs
the empty string. note: value must not contain "!important" -- that should be set using the priority parameter. priority optional is a domstring allowing the "important" css priority to be set. if not specified, treated as the empty string. the following values are accepted: string value "important" keyword undefined string empty value "" return value undefined
exceptions dom
exception (nomodificationallowederror): if the property or declaration block is read only. 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 dynamically alter our box paragraph's border, background color, a...
CSSStyleSheet.addRule() - Web APIs
defined. index optional an optional index into the stylesheet's cssrulelist at which to insert the new rule. if index is not specified, the next index after the last item currently in the list is used (that is, the value of cssstylesheet.cssrules.length). return value always returns -1. note that due to somewhat estoteric rules about where you can legally insert rules, it's possible that an
exception may be thrown. see insertrule() for more information. usage notes this method is implemented by browsers by constructing a string using the template literal `${selector}{${styleblock}}`, then passing it into the standard insertrule() method. therefore, given existing code such as the following: cssstylesheet.addrule(selector, styles, 0); you can rewrite this to use the more standard insertru...
CSSStyleSheet.insertRule() - Web APIs
g the newly inserted rule's position in cssstylesheet.cssrules. the default is 0. (in older implementations, this was required. see browser compatibility for details.) return value the newly inserted rule's index within the stylesheet's rule-list. restrictions css has some intuitive and not-so-intuitive restrictions affecting where rules can be inserted. violating them will likely raise a dom
exception. if index > cssrulelist.length, the method aborts with an indexsizeerror. if rule cannot be inserted at index 0 due to some css constraint, the method aborts with a hierarchyrequesterror. if more than one rule is given in the rule parameter, the method aborts with a syntaxerror. if trying to insert an @import at-rule after a style rule, the method aborts with a hierarchyrequesterror. if ru...
Using the CSS Painting API - Web APIs
) function can take three arguments. here we have provided one argument: the rendering context (we'll look at more in due course), often refered to by the variable name ctx. 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. we define the fillstyle as being hsla(55, 90%, 60%, 1.0), which is a shade of yellow, and then call fillrect() to create a rectangle of that color. the fillrect() parameters are, in order, x-axis origin, y-axis origin, width, and height. fillrect(0, 15, 200, 20) results in the creation of a rectangle that ...
Cache.add() - Web APIs
u'll need to use cache.put() directly. note: add() will overwrite any key/value pair previously stored in the cache that matches the request. syntax cache.add(request).then(function() { // request has been added to the cache }); parameters request the request you want to add to the cache. this can be a request object or a url. return value a promise that resolves with undefined.
exceptions
exception happens when typeerror the url scheme is not http or https. 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...
Cache.addAll() - Web APIs
operation would overwrite a previous cache entry stored by the same addall() method. syntax cache.addall(requests[]).then(function() { // requests have been added to the cache }); parameters requests an array of string urls that you want to be fetched and added to the cache. you can specify the request object instead of the url. return value a promise that resolves with undefined.
exceptions
exception happens when typeerror the url scheme is not http or https. 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...
Cache.match() - Web APIs
asically 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]). examples this example is taken from the custom offline page example (live demo). it uses a cache to supply selected data when a request fails. a catch() clause is triggered when the call to fetch() throws an
exception. inside the catch() clause, match() is used to return the correct response. in this example, only html documents retrieved with the get http verb will be cached. if our if() condition is false, then this fetch handler won't intercept the request. if there are any other fetch handlers registered, they will get a chance to call event.respondwith(). if no fetch handlers call event.respondwith(), th...
CacheStorage.has() - Web APIs
es the following example first checks whether a cache called 'v1' exists. if so, we add a list of assets to it. if not then we run some kind of cache set-up function. caches.has('v1').then(function(hascache) { if (!hascache) { somecachesetupfunction(); } else { caches.open('v1').then(function(cache) { return cache.addall(myassets); }); } }).catch(function() { // handle
exception here. }); specifications specification status comment service workersthe definition of 'cachestorage: has' in that specification. working draft initial definition. ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
directly specify when it's time to capture a frame. to prevent automatic capture of frames, so that frames are only captured when requestframe() is called, specify a value of 0 for the capturestream() method when creating the stream. syntax stream.requestframe(); return value undefined usage notes there is currently an issue flagged in the specification pointing out that at this time, no
exceptions are being thrown if the canvas isn't origin-clean. this may change in the future, so it would be wise to plan ahead and watch for
exceptions such as securityerror (although the specific error that might be thrown is not mentioned in the spec, this is a likely candidate). example // find the canvas element to capture var canvaselt = document.getelementsbytagname("canvas")[0]; // get the stream...
CanvasRenderingContext2D.drawImage() - Web APIs
e the top-left corner of the source image. dwidth optional the width to draw the image in the destination canvas. this allows scaling of the drawn image. if not specified, the image is not scaled in width when drawn. dheight optional the height to draw the image in the destination canvas. this allows scaling of the drawn image. if not specified, the image is not scaled in height when drawn.
exceptions thrown index_size_err if the canvas or source rectangle width or height is zero. invalid_state_err the image has no image data. type_mismatch_err the specified source element isn't supported. ns_error_not_available the image is not loaded yet. use .complete === true and .onload to determine when it is ready. examples drawing an image to the canvas this example draws an image to the...
CanvasRenderingContext2D.getImageData() - Web APIs
the right, and negative to the left. sh the height of the rectangle from which the imagedata will be extracted. positive values are down, and negative are up. return value an imagedata object containing the image data for the rectangle of the canvas specified. the coordinates of the rectangle's top-left corner are (sx, sy), while the coordinates of the bottom corner are (sx + sw, sy + sh).
exceptions indexsizeerror thrown if either sw or sh are zero. securityerror the canvas contains or may contain pixels which were loaded from an origin other than the one from which the document itself was loaded. to avoid securityerror being thrown in this situation, configure cors to allow the source image to be used in this way. see allowing cross-origin use of images and canvas. example getting...
Transformations - Web APIs
mation matrix. transform(a, b, c, d, e, f) multiplies the current transformation matrix with the matrix described by its arguments. the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] if any of the arguments are infinity the transformation matrix must be marked as infinite instead of the method throwing an
exception. the parameters of this function are: a (m11) horizontal scaling. b (m12) horizontal skewing. c (m21) vertical skewing. d (m22) vertical scaling. e (dx) horizontal moving. f (dy) vertical moving. settransform(a, b, c, d, e, f) resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments. this basically undoes the current tr...
Using images - Web APIs
reate new htmlimageelement objects in our script. to do this, you can use the convenient image() constructor: var img = new image(); // create new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading. 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). so you need to be sure to use the load event so you don't try this before the image has loaded: var img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one external image this can be a good approach, but once you need to track more than one w...
ChannelMergerNode() - Web APIs
ed with. options optional a channelmergeroptions dictionary object defining the properties you want the channelmergernode to have (also inherits parameters from the audionodeoptions dictionary): numberofinputs: a number defining the number of inputs the channelmergernode should have. if not specified, the default value used is 6. return value a new channelmergernode object instance.
exceptions invalidstateerror an option such as channelcount or channelcountmode has been given an invalid value. example var ac = new audiocontext(); var options = { numberofinputs : 2 } var mymerger = new channelmergernode(ac, options); specifications specification status comment web audio apithe definition of 'channelmergernode' in that specification. working draft...
ChildNode.after() - Web APIs
the childnode.after() method inserts a set of node or domstring objects in the children list of this childnode's parent, just after this childnode. domstring objects are inserted as equivalent text nodes. syntax [throws, unscopable] void childnode.after((node or domstring)... nodes); parameters nodes a set of node or domstring objects to insert.
exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. examples inserting an element var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.after(span); console.log(parent.outerhtml); // "<div><p></p><span></span></div>" inserting text var parent = document.createelement("div"); var chil...
ChildNode.before() - Web APIs
the childnode.before() method inserts a set of node or domstring objects in the children list of this childnode's parent, just before this childnode. domstring objects are inserted as equivalent text nodes. syntax [throws, unscopable] void childnode.before((node or domstring)... nodes); parameters nodes a set of node or domstring objects to insert.
exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. examples inserting an element var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.before(span); console.log(parent.outerhtml); // "<div><span></span><p></p></div>" inserting text var parent = document.createelement("div"); var ...
ChildNode.replaceWith() - Web APIs
the childnode.replacewith() method replaces this childnode in the children list of its parent with a set of node or domstring objects. domstring objects are inserted as equivalent text nodes. syntax [throws, unscopable] void childnode.replacewith((node or domstring)... nodes); parameters nodes a set of node or domstring objects to replace.
exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. examples using replacewith() var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.replacewith(span); console.log(parent.outerhtml); // "<div><span></span></div>" childnode.replacewith() is unscopable the replacewith() method is not scope...
Console.timeLog() - Web APIs
timer that was previously started by calling console.time() to the console. see timers in the documentation for details and examples. note: this feature is available in web workers. syntax console.timelog(label); parameters label the name of the timer to log to the console. return if no label parameter included: default: 1042ms if an existing label is included: timer name: 1242ms
exceptions if there is no running timer, timelog() returns the warning: timer “default” doesn’t exist. if a label parameter is included, but there is no corresponding timer: timer “timer name” doesn’t exist. examples console.time("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.timeend("answer time"); the output...
console - Web APIs
a specified javascript object. this listing lets you use disclosure triangles to examine the contents of child objects. console.dirxml() displays an xml/html element representation of the specified object if possible or the javascript object view if it is not possible. console.error() outputs an error message. you may use string substitution and additional arguments with this method. console.
exception() an alias for error(). console.group() creates a new inline group, indenting all following output by another level. to move back out a level, call groupend(). console.groupcollapsed() creates a new inline group, indenting all following output by another level. however, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. to mo...
ContentIndex.add() - Web APIs
, this is the default. homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image. sizes: optional a string representation of the image size. type: optional the mime type of the image. return value returns a promise that resolves with undefined
exceptions typeerror if the service worker's registration is not present or the service worker does not contain a fetchevent. if the id, title, description or url are missing, not of type string, or an empty string. if icons images are not of image type. examples here we're declaring an item in the correct format and creating an asynchronous function which uses the add method to register it with t...
ContentIndex.delete() - Web APIs
the delete() method of the contentindex interface unregisters an item from the currently indexed content. calling delete() only affects the index. it does not delete anything from the cache. syntax contentindex.delete(id).then(...); parameters this method receives no parameters. return value returns a promise that resolves with undefined
exceptions no
exceptions are thrown. examples below is an asynchronous function, that removes an item from the content index. we receive a reference to the current serviceworkerregistration, which allows us to access the index property and thus access the delete method. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if ...
ContentIndex.getAll() - Web APIs
ng the category of content. can be: '' an empty string, this is the default. homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image. sizes: optional a string representation of the image size. type: optional the mime type of the image.
exceptions no
exceptions are thrown. if there are no items in the content index, an empty array is returned. examples the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. async function createreadinglist() { // access our service worker registration const registration = await navigator.service...
ConvolverNode() - Web APIs
: audiobuffer: a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect. disablenormalization: a boolean controlling whether the impulse response from the buffer will be scaled by an equal-power normalization, or not. the default is 'false'. return value a new convolvernode object instance.
exceptions
exception explanation notsupportederror the referenced audiobuffer does not have the correct number of channels, or it has a different sample rate to the associated audiocontext. specifications specification status comment web audio apithe definition of 'convolvernode()' in that specification. working draft initial definition. ...
ConvolverNode.buffer - Web APIs
ple recording of as-close-to-an-impulse as can be found in the space you want to model. for example, if you want to model the reverb in your bathroom, you might set up a microphone near the door to record the sound of a balloon pop or synthesized impulse from the sink. that audio recording could then be used as the buffer. this audiobuffer must have the same sample-rate as the audiocontext or an
exception will be thrown. at the time when this attribute is set, the buffer and the state of the attribute will be used to configure the convolvernode with this impulse response having the given normalization. the initial value of this attribute is null. syntax var audioctx = new audiocontext(); var convolver = audioctx.createconvolver(); convolver.buffer = myaudiobuffer; value an audiobuffer. exam...
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
tqueuingstrategy object instance. syntax var countqueuingstrategy = new countqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property. this is a non-negative integer defining the total number of chunks that can be contained in the internal queue before backpressure is applied. return value an instance of the countqueuingstrategy object.
exceptions none. examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); var size = queuingstrategy.size(); specifications specification status comment s...
CredentialsContainer.get() - Web APIs
lues are "silent", "optional", or "required". unmediated: a boolean indicating the returned credential instance should not require user mediation. signal: an instance of abortsignal that can indicate that an ongoing get() operation should be halted. an aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with an "aborterror" dom
exception. returns a promise that resolves with a credential instance that matches the provided parameters. if a single credential cannot be unambigiously obtained, the promise will resolve to null. specifications specification status comment credential management level 1the definition of 'get()' in that specification. working draft initial definition. web au...
CredentialsContainer - Web APIs
t credentials and notify the user agent when events such as successful sign in or sign out happen. this interface is accessible from navigator.credentials. properties none. event handlers none. methods credentialscontainer.create()secure context returns a promise that resolves with a new credential instance based on the provided options, or null if no credential object can be created. in
exceptional circumstances, the promise may reject. credentialscontainer.get()secure context returns a promise that resolves with the credential instance that matches the provided parameters. credentialscontainer.preventsilentaccess()secure context sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty promise. for example, you might...
Crypto.getRandomValues() - Web APIs
ters typedarray an integer-based typedarray, that is an int8array, a uint8array, an int16array, a uint16array, an int32array, or a uint32array. all elements in the array are overwritten with random numbers. return value the same array passed as typedarray but with its contents replaced with the newly generated random numbers. note that typedarray is modified in-place, and no copy is made.
exceptions this method can throw an
exception under error conditions. dom
exception (name: quotaexceedederror) the requested length exceeds 65,536 bytes. usage notes don't use getrandomvalues() to generate encryption keys. instead, use the generatekey() method. there are a few reasons for this; for example, getrandomvalues() is not guaranteed to be running in a secure context. there is no minimum d...
CryptoKey - Web APIs
ivate half of an asymmetric algorithm's cryptokeypair. "public": this key is the public half of an asymmetric algorithm's cryptokeypair. cryptokey.extractable boolean indicating whether or not the key may be extracted using subtlecrypto.exportkey() or subtlecrypto.wrapkey(). true: the key may be extracted. false the key may not be extracted. exportkey() or wrapkey() will throw an
exception if used to extract this key. cryptokey.algorithm an object describing the algorithm for which this key can be used and any associated extra parameters. aeskeygenparams if the algorithm is any of the aes variants. rsahashedkeygenparams if the algorithm is any of the rsa variants. eckeygenparams if the algorithm is any of the ec variants. hmackeygenparams if the algorithm is hmac...
CustomElementRegistry.define() - Web APIs
name name for the new custom element. note that custom element names must contain a hyphen. constructor constructor for the new custom element. options optional object that controls how the element is defined. one option is currently supported: extends: string specifying the name of a built-in element to extend. used to create a customized built-in element. return value void.
exceptions
exception description notsupportederror the customelementregistry already contains an entry with the same name or the same constructor (or is otherwise already defined), or extends is specified and it is a valid custom element name, or extends is specified but the element it is trying to extend is an unknown element. syntaxerror the provided name is not a...
CustomElementRegistry.whenDefined() - Web APIs
the whendefined() method of the customelementregistry interface returns a promise that resolves when the named element is defined. syntax promise<> customelements.whendefined(name); parameters name custom element name. return value a promise that resolves to undefined when the custom element is defined. if the custom element is already defined, the promise is resolved immediately.
exceptions
exception description syntaxerror if the provided name is not a valid custom element name, the promise rejects with a syntaxerror. examples this example uses whendefined() to detect when the custom elements that make up a menu are defined. the menu displays placeholder content until the actual menu content is ready to display. <nav id="menu-container"> <div...
DOMMatrix - Web APIs
pecified skew transformation along the y-axis. returns itself. static methods this interface inherits methods from dommatrixreadonly. fromfloat32array() creates a new mutable dommatrix object given an array of single-precision (32-bit) floating-point values. if the array has six values, the result is a 2d matrix; if the array has 16 values, the result is a 3d matrix. otherwise, a typeerror
exception is thrown. fromfloat64array() creates a new mutable dommatrix object given an array of double-precision (64-bit) floating-point values. if the array has six values, the result is a 2d matrix; if the array has 16 values, the result is a 3d matrix. otherwise, a typeerror
exception is thrown. frommatrix() creates a new mutable dommatrix object given an existing matrix or a dommatrixinit dictiona...
DataTransferItemList.add() - Web APIs
data a string representing the drag item's data. type a string of the drag item's type. some example types are text/html and text/plain. file a file object. no type needs to be given in this case. return value a datatransferitem containing the specified data. if the drag item couldn't be created (for example, if the associated datatransfer object has no data store), null is returned.
exceptions notsupportederror a string data parameter was provided, and the list already contains an item whose kind is "plain unicode string" and whose type is equal to the specified type parameter. example this example shows the use of the add() method. html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, dr...
DataTransferItemList.remove() - Web APIs
index from the list. if the index is less than zero or greater than one less than the length of the list, the list will not be changed. syntax datatransferitemlist.remove(index); parameters index the zero-based index number of the item in the drag data list to remove. if the index doesn't correspond to an existing item in the list, the list is left unchanged. return value undefined.
exceptions invalidstateerror the drag data store is not in read/write mode, so the item can't be removed. example this example shows the use of the remove() method. javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree var datalist = ev.datatransfer.items; datali...
DirectoryReaderSync - Web APIs
{ var data = e.data; // ignore everything else except our 'list' command. if (!data.cmd || data.cmd != 'list') { return; } try { var fs = requestfilesystemsync(temporary, 1024*1024 /*1mb*/); getallentries(fs.root.createreader()); self.postmessage({entries: paths}); } catch (e) { onerror(e); } }; method overview entrysync readentries () raises (file
exception); method readentries() returns a lost of entries from a specific directory. call this method until an empty array is returned. entrysync readentries ( ) raises (file
exception); returns parameter none
exceptions this method can raise a file
exception with the following codes:
exception description not_found_err the directory does not exist. inval...
DisplayMediaStreamConstraints.video - Web APIs
o property is used to configure the video track in the stream returned by getdisplaymedia(). this value may simply be a boolean, where true specifies that a default selection of input source be made (typically the entire display area of the device in use, spanning every screen in a multiple screen configuration). since a video track must always be included, a value of false results in a typeerror
exception being thrown. more precise control over the format of the returned video track may be exercised by instead providing a mediatrackconstraints object, which is used to process the video data after obtaining it from the device but prior to adding it to the stream. syntax displaymediastreamconstraints.video = allowvideoflag; displaymediastreamconstraints.video = mediatrackconstraints; displaymedi...
Document.createAttribute() - Web APIs
ute node, and returns it. the object created a node implementing the attr interface. the dom does not enforce what sort of attributes can be added to a particular element in this manner. the string given in parameter is converted to lowercase. syntax attribute = document.createattribute(name) parameters name is a string containing the name of the attribute. return value a attr node.
exceptions invalid_character_err if the parameter contains invalid characters for xml attribute. example var node = document.getelementbyid("div1"); var a = document.createattribute("my_attrib"); a.value = "newval"; node.setattributenode(a); console.log(node.getattribute("my_attrib")); // "newval" specifications specification status comment domthe definition of 'document.cr...
Document.createCDATASection() - Web APIs
docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err. will throw a ns_error_dom_invalid_character_err
exception if one tries to submit the closing cdata sequence ("]]>") as part of the data, so unescaped user-provided data cannot be safely used without with this method getting this
exception (createtextnode() can often be used in its place). specifications specification status comment domthe definition of 'document.createcdatasection' in that specification. living standard...
Document.createProcessingInstruction() - Web APIs
essinginstruction(target, data) parameters pinode is the resulting processinginstruction node. target is a string containing the first part of the processing instruction (i.e., <?target … ?>) data is a string containing any information the processing instruction should carry, after the target. the data is up to you, but it can't contain ?>, since that closes the processing instruction.
exceptions dom_invalid_character throws if either of the following are true: the processing instruction target is invalid — it should be a valid xml name that doesn't contain "xml", "xml", or any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>. the closing processing instruction sequence (?>) is part of the data. example var doc = new domparser().par...
Document.domain - Web APIs
the domain property of the document interface gets/sets the domain portion of the origin of the current document, as used by the same origin policy. if this property is successfully set, the port part of the origin is also set to null. syntax const domainstring = document.domain document.domain = domainstring value the domain portion of the current document's origin. ...
Document.execCommand() - Web APIs
point. this requires an integer from 1-7 as a value argument. forecolor changes a font color for the selection or at the insertion point. this requires a hexadecimal color value string as a value argument. formatblock adds an html block-level element around the line containing the current selection, replacing the block element containing the line if one exists (in firefox, <blockquote> is the
exception — it will wrap any containing block element). requires a tag-name string as a value argument. virtually all block-level elements can be used. (internet explorer and edge support only heading tags h1–h6, address, and pre, which must be wrapped in angle brackets, such as "<h1>".) forwarddelete deletes the character ahead of the cursor's position, identical to hitting the delete key on a windo...
Document.requestStorageAccess() - Web APIs
rompt the user. the maximum number of concurrent storage access grants an origin can obtain is a positive integer currently defined as one percent of the number of top-level origins visited in the current session or 5, whichever is higher. the threshold is enforced on the level of etld+1, so for example two storage access grants for foo.example.com and bar.example.com will only count as a single
exception against the limit. at the time of a requeststorageaccess() call, if the requesting origin has storage access to... ...fewer origins than the maximum: the user is not prompted. the origin is given an ephemeral storage access grant for the current top-level origin. the number of origins the requesting origin has storage access to is incremented by one. note that this number is also inc...
DocumentFragment.querySelector() - Web APIs
() method returns the first element, or null if no matches are found, within the documentfragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors. if the selector matches an id and this id is erroneously used several times in the document, it returns the first matching element. if the selectors specified in parameter are invalid a dom
exception with a syntax_err value is raised. syntax element = documentfragment.queryselector(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is returned: var el = documentfragment.queryselector(".myclass"); css syntax and t...
EffectTiming.duration - Web APIs
tion should take. the default is "auto". this value must not be negative; otherwise, it can have any value (including positive infinity). currently, a value of "auto" is the same as specifying 0.0. this is a forwards-compatiblity measure since in the future, "auto" will be expanded to take into account the duration of any child effects. consider using "auto" rather than 0 if that makes sense.
exceptions typeerror the specified value is either a string other than "auto", a number less than zero, nan, or some other type of object entirely. examples in the pool of tears example, each tear is passed a random duration via its timing object: // randomizer function var getrandommsrange = function(min, max) { return math.random() * (max - min) + min; } // loop through each tear tears.foreach...
EffectTiming.iterations - Web APIs
terations: numberofiterations }; timingproperties.iterations = numberofiterations; value a floating-point value specifying the number of times the animation sequence will play through. any value from 0 (don't play the animation at all) to positive infinity (run the animation indefinitely) is supported. defaults to 1, meaning the animation sequence plays through once then stops automatically.
exceptions typeerror an attempt was made to set the value of this property to a negative number or nan. the property's value is left unchanged. examples in the forgotten key example, alice waves her arm up and down the entire time the page is open by passing infinity as the value for her iterations property: // get alice's arm, and wave it up and down document.getelementbyid("alice_arm").animate([ ...
Element.attachShadow() - Web APIs
de it: element.shadowroot; // returns null delegatesfocus a boolean that, when set to true, specifies behavior that mitigates custom element issues around focusability. when a non-focusable part of the shadow dom is clicked, the first focusable part is given focus, and the shadow host is given any available :focus styling. return value returns a shadowroot object.
exceptions
exception explanation invalidstateerror the element you are trying to attach to is already a shadow host. notsupportederror you are trying to attach a shadow root to an element outside the html namespace, or the element cannot have a shadow attached to it (see above). examples the following example is taken from our word-count-web-component demo (...
Element.closest() - Web APIs
s the provided selector string. will return itself or the matching ancestor. if no such element exists, it returns null. syntax var closestelement = targetelement.closest(selectors); parameters selectors is a domstring containing a selector list. ex: p:hover, .toto + q return value closestelement is the element which is the closest ancestor of the selected element. it may be null.
exceptions syntaxerror is thrown if the selectors is not a valid selector list string. example html <article> <div id="div-01">here is div-01 <div id="div-02">here is div-02 <div id="div-03">here is div-03</div> </div> </div> </article> javascript var el = document.getelementbyid('div-03'); var r1 = el.closest("#div-02"); // returns the element with the id=div-02 var r2 = el.cl...
Element.getAttributeNS() - Web APIs
dom 1) removeattributens removeattributenode - specifications specification status comment domthe definition of 'element.getattributens()' in that specification. living standard document object model (dom) level 3 core specificationthe definition of 'element.getattributens()' in that specification. obsolete specifies that a not_supported_err
exception is thrown if the ua does not support the "xml" feature. also specifies that null must be passed to have no namespace. document object model (dom) level 2 core specificationthe definition of 'element.getattributens()' in that specification. obsolete initial definition ...
Element.innerHTML - Web APIs
eplace the contents of an element, use the method insertadjacenthtml(). syntax const content = element.innerhtml; element.innerhtml = htmlstring; value a domstring containing the html serialization of the element's descendants. setting the value of innerhtml removes all of the element's descendants and replaces them with nodes constructed by parsing the html given in the string htmlstring.
exceptions syntaxerror an attempt was made to set the value of innerhtml using a string which is not properly-formed html. nomodificationallowederror an attempt was made to insert the html into a node whose parent is a document. usage notes the innerhtml property can be used to examine the current html source of the page, including any changes that have been made since the page was initially loade...
Element.insertAdjacentElement() - Web APIs
f the following strings: 'beforebegin': before the targetelement itself. 'afterbegin': just inside the targetelement, before its first child. 'beforeend': just inside the targetelement, after its last child. 'afterend': after the targetelement itself. element the element to be inserted into the tree. return value the element that was inserted, or null, if the insertion failed.
exceptions
exception explanation syntaxerror the position specified is not a recognised value. typeerror the element specified is not a valid element. visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> note: the beforebegin and afterend positions work only if the node is in a tree...
Element.insertAdjacentText() - Web APIs
resenting the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself. 'afterbegin': just inside the element, before its first child. 'beforeend': just inside the element, after its last child. 'afterend': after the element itself. element a domstring representing the text to be inserted into the tree. return value void.
exceptions
exception explanation syntaxerror the position specified is not a recognised value. visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> note: the beforebegin and afterend positions work only if the node is in a tree and has an element parent. example beforebtn.addeventlistener('cl...
Element.matches() - Web APIs
the matches() method checks to see if the element would be selected by the provided selectorstring -- in other words -- checks if the element "is" the selector. syntax var result = element.matches(selectorstring); parameters selectorstring is a string representing the selector to test. return value result is a boolean.
exceptions syntax_err the specified selector string is invalid. example <ul id="birds"> <li>orange-winged parrot</li> <li class="endangered">philippine eagle</li> <li>great white pelican</li> </ul> <script type="text/javascript"> var birds = document.getelementsbytagname('li'); for (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('the ' + birds[i].textcontent + ' is endangered!'); } } </script> this ...
Element.releasePointerCapture() - Web APIs
erface releases (stops) pointer capture that was previously set for a specific (pointerevent) pointer. see the element.setpointercapture() method for a description of pointer capture and how to set it for a particular element. syntax targetelement.releasepointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object. return value this method returns undefined.
exceptions
exception explanation invalidpointerid pointerid does not match any of the active pointers. example this example sets pointer capture on a <div> when you press down on it. this lets you slide the element horizontally, even when you pointer moves outside of its boundaries. html <div id="slider">slide me</div> css div { width: 140px; height: 50px; dis...
Element.setAttribute() - Web APIs
t is non-standard). see the example below for a practical demonstration. since the specified value gets converted into a string, specifying null doesn't necessarily do what you expect. instead of removing the attribute or setting its value to be null, it instead sets the attribute's value to the string "null". if you wish to remove an attribute, call removeattribute(). return value undefined.
exceptions invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, setattribute() is used to set attributes on a <button>. html <button>hello world</button> javascript var b = document.queryselector("button"); b.setattribute("name", "hellobutton"); b.setattribute("disabled", ""); this demonstr...
Element.setPointerCapture() - Web APIs
f the normal (or hit test) target at a pointer's location. this can be used to ensure that an element continues to receive pointer events even if the pointer device's contact moves off the element (such as by scrolling or panning). syntax targetelement.setpointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object. return value this method returns undefined.
exceptions
exception explanation invalidpointerid pointerid does not match any of the active pointers. example this example sets pointer capture on a <div> when you press down on it. this lets you slide the element horizontally, even when you pointer moves outside of its boundaries. html <div id="slider">slide me</div> css div { width: 140px; height: 50px; dis...
Element.toggleAttribute() - Web APIs
te to be toggled. the attribute name is automatically converted to all lower-case when toggleattribute() is called on an html element in an html document. force optional a boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. return value true if attribute name is eventually present, and false otherwise.
exceptions invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, toggleattribute() is used to toggle the readonly attribute of a <input>. html <input value="text"> <button>toggleattribute("readonly")</button> javascript var button = document.queryselector("button"); var input = document.queryse...
EventTarget.dispatchEvent() - Web APIs
voke. return value the return value is false if event is cancelable and at least one of the event handlers which received event called event.preventdefault(). otherwise it returns true. the dispatchevent() method throws unspecified_event_type_err if the event's type was not specified by initializing the event before the method was called, or if the event's type is null or an empty string.
exceptions
exceptions thrown by event handlers are reported as uncaught
exceptions. the event handlers run on a nested callstack; they block the caller until they complete, but
exceptions do not propagate to the caller. notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via the event loop, dispatchevent() invokes event handlers synchronously. all applicable...
ExtendableEvent - Web APIs
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. the promise resolves when all resources have been fetched and cached, or else when any
exception occurs. the code snippet also shows a best practice for versioning caches used by the service worker. though there's only one cache in this example, the same approach can be used for multiple caches. it maps a shorthand identifier for a cache to a specific, versioned cache name. note: in chrome, logging statements are visible via the "inspect" interface for the relevant service worker accessed...
FetchEvent.request - Web APIs
m the service worker fetch sample (run the fetch sample live). the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code fetches a response from the network. the code also handles
exceptions thrown from the serviceworkerglobalscope.fetch operation. note that an http error response (e.g., 404) will not trigger an
exception. it will return a normal response object that has the appropriate error code set. self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(res...
FetchEvent.respondWith() - Web APIs
ing the request url for the resulting window.location. this means sites can still provide an "alternate" view of a web page when offline without changing the user-visible url. syntax fetchevent.respondwith( // promise that resolves to a response. ); parameters a response or a promise that resolves to a response. otherwise, a network error is returned to fetch. return value undefined.
exceptions
exception notes networkerror a network error is triggered on certain combinations of fetchevent.request.mode and response.type values, as hinted at in the "global rules" listed above. invalidstateerror the event has not been dispatched or respondwithwith() has already been invoked. examples this fetch event tries to return a response from the cac...
FileError - Web APIs
a fileerror represents error conditions that you might encounter while accessing the file system using the asynchronous api. it extends the fileerror interface described in file writer and adds several new error codes. fileerror objects are passed to error callbacks. the objects have a code that shows the type of error that occurred. best practices most people don't read the page on errors and
exceptions unless they're stumped. so the following are a few tips that could help you avoid some pitfalls. 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. a web app could fail for various reasons, so you don't want to spend the rest of your day guessing what's going o...
FileReader.abort() - Web APIs
the abort method aborts the read operation. upon return, the readystate will be done. 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). specifications specification status comment file apithe definition of 'abort()' in that specification. working draft initial definition ...
FileReader.error - Web APIs
the filereader error property returns the error that occurred while reading the file. syntax var error = instanceoffilereader.error value a domerror containing the relevant error. in chrome 48+/firefox 58+ this property returns a dom
exception because domerror has been removed from the dom standard. specifications specification status comment file apithe definition of 'filereader: error' in that specification. working draft initial definition ...
FileReader - Web APIs
ystem. to read files by pathname in javascript, standard ajax solutions should be used to do server-side file reading, with cors permission if reading cross-domain. note: this feature is available in web workers. constructor filereader() returns a newly constructed filereader. see using files from web applications for details and examples. properties filereader.error read only a dom
exception representing the error that occurred while reading the file. filereader.readystate read only a number indicating the state of the filereader. this is one of the following: empty 0 no data has been loaded yet. loading 1 data is currently being loaded. done 2 the entire read request has been completed. filereader.result rea...
FileReaderSync.readAsArrayBuffer() - Web APIs
ersync interface allows to read file or blob objects in a synchronous way into an arraybuffer. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax arraybuffer readasarraybuffer( in blob blob ); parameters blob the dom file or blob to read into the file or arraybuffer. return value an arraybuffer representing the file's data.
exceptions the following
exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by th...
FileReaderSync.readAsBinaryString() - Web APIs
string() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an domstring. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax readasbinarystring(file); readasbinarystring(blob); parameters blob the dom file or blob to read. return value an domstring representing the input data.
exceptions the following
exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by th...
FileReaderSync.readAsDataURL() - Web APIs
eadersync interface allows to read file or blob objects in a synchronous way into an domstring representing a data url. this interface is only available in workers as it enables synchronous i/o that could potentially block. syntax readasdataurl(file); readasdataurl(blob); parameters blob the dom file or blob to read. return value an domstring representing the input data as a data url.
exceptions the following
exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by th...
FileReaderSync.readAsText() - Web APIs
t could potentially block. syntax readastext(file); readastext(blob); readastext(file, encoding); readastext(blob, encoding); parameters blob the dom file or blob to read. encoding the optional parameter specifies encoding to be used (e.g., iso-8859-1 or utf-8). if not present, the method will apply a detection algorithm for it. return value an domstring representing the input data.
exceptions the following
exceptions can be raised by this method: notfounderror is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. securityerror is raised when one of the following problematic situation is detected: the resource has been modified by a third party; too many read are performed simultaneously; the file pointed by th...
File and Directory Entries API - Web APIs
d by other interfaces which represent files or directories. filesystemfileentrysync represents a single file in a file system. filesystemdirectoryentrysync represents a single directory in a file system. filesystemdirectoryreadersync created by calling filesystemdirectoryentrysync.createreader(), this interface provides the functionality which lets you read the contents of a directory. file
exception represents an error which is generated by synchronous file system calls. there are also two global functions (which are not part of the specification at this time and are implemented only by google chrome). they're available on the worker object and implemented in localfilesystemsync: requestfilesystemsync() and resolvelocalfilesystemsyncurl(). other interfaces localfilesystem gives you...
FontFace.load - Web APIs
ont based on current object's constructor-passed requirements, including a location or source buffer, and returns a promise that resolves with the current fontface object. syntax var promise = fontface.load(); parameters none. return value a promise that resolves with a reference to the current fontface object when the font loads or rejects with a networkerror if the loading process fails.
exceptions networkerror indicates that the attempt to load the font failed. specifications specification status comment css font loading module level 3the definition of 'load' in that specification. working draft initial definition. ...
GlobalEventHandlers.onerror - Web APIs
the onerror property of the globaleventhandlers mixin is an eventhandler that processes error events. error events are fired at various targets for different kinds of errors: when a javascript runtime error (including syntax errors and
exceptions thrown within handlers) occurs, an error event using interface errorevent is fired at window and window.onerror() is invoked (as well as handlers attached by window.addeventlistener (not only capturing)). when a resource (such as an <img> or <script>) fails to load, an error event using interface event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. these error events do not bubble up to window, but (at least in firefox) can be handled with a window.addeventlistener configured with usecapture set ...
HTMLCanvasElement.captureStream() - Web APIs
ating-point value that indicates the rate of capture of each frame. if not set, a new frame will be captured each time the canvas changes; if set to 0, frames will not be captured automatically; instead, they will only be captured when the returned track's requestframe() method is called. return value a reference to a mediastream object, which has a single canvascapturemediastreamtrack in it.
exceptions notsupportederror the value of framerate is negative. example // find the canvas element to capture var canvaselt = document.queryselector('canvas'); // get the stream var stream = canvaselt.capturestream(25); // 25 fps // do things to the stream // e.g. send it to another computer using an rtcpeerconnection // pc is an rtcpeerconnection created elsewhere pc.addstream(stream); sp...
HTMLCanvasElement.toBlob() - Web APIs
ument. mimetype optional a domstring indicating the image format. the default type is image/png. qualityargument optional a number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. if this argument is anything else, the default values 0.92 and 0.80 are used for image/jpeg and image/webp respectively. other arguments are ignored. return value none.
exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents come from secure examples getting a file representing the canvas once you have drawn content into a canvas, you can convert it into a file of any supported image format. the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image,...
HTMLCanvasElement.toDataURL() - Web APIs
fault format type is image/png. encoderoptions optional a number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. if this argument is anything else, the default value for image quality is used. the default value is 0.92. other arguments are ignored. return value a domstring containing the requested data uri.
exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded. examples given this <canvas> element: <canvas id="canvas" width="5" height="5"></canvas> you can get a data-url of the canvas with the following lines: var canvas = document.getelementbyid('canvas');...
HTMLDialogElement.showModal() - Web APIs
the showmodal() method of the htmldialogelement interface displays the dialog as a modal, over the top of any other dialogs that might be present. it displays into the top layer, along with a ::backdrop pseudo-element. interaction outside the dialog is blocked and the content outside it is rendered inert. syntax dialoginstance.showmodal(); parameters none. return value void.
exceptions if the dialog is already open (i.e. if the open attribute is already set on the <dialog> element), an invalidstateerror is thrown. examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close() method), or submit the form via the submit...
HTMLFormElement.elements - Web APIs
moved from the form, this collection will update to reflect the change. the form controls in the returned collection are in the same order in which they appear in the form by following a preorder, depth-first traversal of the tree. this is called tree order. the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the
exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. example quick syntax example in this example, we see how to obtain the list of form controls as well as how to access its membe...
HTMLFormElement.length - Web APIs
ontrols in the <form> element. you can access the list of the form's controls using the elements property. this includes both elements that are descendents of the <form> element as well as elements that are made members of the form using their form property. the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the
exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. syntax numcontrols = form.length; value numcontrols is the number of form controls within the <form>. this is the same as the...
HTMLFormElement.requestSubmit() - Web APIs
pecific submit button. syntax htmlformelement.requestsubmit(submitter); parameters submitter optional the submit button whose attributes describe the method by which the form is to be submitted. this may be either an <input> or <button> element whose type attribute is submit. if you omit the submitter parameter, the form element itself is used as the submitter. return value none.
exceptions typeerror the specified submitter is not a submit button. notfounderror the specified submitter isn't a member of the form on which requestsubmit() was called. the submitter must be either a descendant of the form element or must have an form attribute referring to the form. usage notes the obvious question is: why does this method exist, when we've had the submit() method since the daw...
HTMLFormElement - Web APIs
ames: always use the elements collection to avoid ambiguity between an element name and a form property. never use "elements" as an element name. if you are not using javascript, this will not cause a problem. elements that are considered form controls the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the
exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. examples creating a new form element, modifying its attributes, then submitting it: const f = document.createelement("form"); /...
HTMLImageElement.decode() - Web APIs
ing it to the dom as a new element), so that the image can be rendered immediately upon being added to the dom. this, in turn, prevents the rendering of the next frame after adding the image to the dom from causing a delay while the image loads. syntax var promise = htmlimageelement.decode(); parameters none. return value a promise which is resolved once the image data is ready to be used.
exceptions encodingerror a dom
exception indicating that an error occurred while decoding the image. usage notes one potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to ...
HTMLInputElement.setSelectionRange() - Web APIs
m the end of the selected text toward the beginning. this method updates the htmlinputelement.selectionstart, selectionend, and selectiondirection properties in one call. note that accordingly to the whatwg forms spec selectionstart, selectionend properties and setselectionrange method apply only to inputs of types text, search, url, tel and password. chrome, starting from version 33, throws an
exception while accessing those properties and method on the rest of input types. for example, on input of type number: "failed to read the 'selectionstart' property from 'htmlinputelement': the input element's type ('number') does not support selection". if you wish to select all text of an input element, you can use the htmlinputelement.select() method instead. syntax element.setselectionrange(selecti...
HTMLInputElement.stepDown() - Web APIs
mple, if it doesn't match the constraints set by the step attribute, invoking the stepdown() method will return a value that does match the form controls constraints. if the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if the step value is set to any, an invalidstateerror
exception is thrown. htmlinputelement.stepdown() decrements the value by (step * n), where n defaults to 1 if not specified. throws an invalid_state_err
exception: if the method is not applicable to for the current type value, if the element has no step value, if the value cannot be converted to a number, if the resulting value is above the max or below the min. syntax eleme...
HTMLInputElement.stepUp() - Web APIs
ample, if it doesn't match the constraints set by the step attribute—invoking the stepup() method will return a value that does match the form controls constraints. if the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if the step value is set to any, an invalidstateerror
exception is thrown. syntax element.stepup( [ stepincrement ] ); parameters stepincrement the optional stepincrement paremeter is a numeric value. if no parameter is passed, stepincrement defaults to 1. example click the button in this example to increment the number input type: html <p> <label>enter a number between 0 and 400 that is divisible by 5: <input type="number" step...
HTMLMediaElement.defaultPlaybackRate - Web APIs
the htmlmediaelement.defaultplaybackrate property indicates the default playback rate for the media. syntax var dspeed = video.defaultplaybackrate; audio.defaultplaybackrate = 1.0; value a double. 1.0 is "normal speed," values lower than 1.0 make the media play slower than normal, higher values make it play faster. the value 0.0 is invalid and throws a not_supported_err
exception. example var obj = document.createelement('video'); console.log(obj.defaultplaybackrate); // 1 specifications specification status comment html living standardthe definition of 'htmlmediaelement.defaultplaybackrate' in that specification. living standard no change from html5 html5the definition of 'htmlmediaelement.defaultplaybackrate' in that specification. recommendati...
HTMLMediaElement.load() - Web APIs
attribute or child <source> element(s). this is described in more detail in supporting multiple formats in video and audio content. the process of aborting any ongoing activities will cause any outstanding promises returned by play() being resolved or rejected as appropriate based on their status before the loading of new media can begin. pending play promises are aborted with an "aborterror" dom
exception. appropriate events will be sent to the media element itself as the load process proceeds: if the element is already in the process of loading media, that load process is aborted and the abort event is sent. if the element has already been initialized with media, the emptied event is sent. if resetting the playback position to the beginning of the media actually changes the playback positio...
HTMLMediaElement.pause() - Web APIs
the htmlmediaelement.pause() method will pause playback of the media, if the media is already in a paused state this method will have no effect. syntax htmlmediaelement.pause() parameters none. return value none.
exceptions none. specifications specification status comment html living standardthe definition of 'pause()' in that specification. living standard initial definition; living specification. html5the definition of 'pause()' in that specification. recommendation initial definition. ...
HTMLMediaElement.readyState - Web APIs
f the media. syntax var readystate = audioorvideo.readystate; value an unsigned short. possible values are: constant value description have_nothing 0 no information is available about the media resource. have_metadata 1 enough of the media resource has been retrieved that the metadata attributes are initialized. seeking will no longer raise an
exception. have_current_data 2 data is available for the current playback position, but not enough to actually play more than one frame. have_future_data 3 data for the current playback position as well as for at least a little bit of time into the future is available (in other words, at least two frames of video, for example). have_enough_data 4 enough data is ...
HTMLObjectElement.checkValidity - Web APIs
the checkvalidity() method of the htmlobjectelement interface returns a boolean that always is true, because object objects are never candidates for constraint validation. syntax const valid = htmlobjectelement.checkvalidity(); parameters none. return value true
exceptions none. specifications specification status comment html living standardthe definition of 'checkvalidity' in that specification. living standard initial definition. ...
HTMLObjectElement.setCustomValidity - Web APIs
examples in this example, we pass the id of an input element, and set different error messages depending on whether the value is missing, too low or too high. additionally you must call the reportvalidity method on the same element or nothing will happen. ...
HTMLOptionsCollection - Web APIs
t { fill: #0095dd; pointer-events: all;} properties name type description length unsigned long as optionally allowed by the spec, this property isn't read-only. you can either remove options from the end by lowering the value, or add blank options at the end by raising the value. mozilla allows this, while other implementations could potentially throw a dom
exception. methods this interface inherits the methods of its parent, htmlcollection. specifications specification status comment html living standardthe definition of 'htmloptionscollection' in that specification. living standard ...
HTMLTableElement.deleteRow() - Web APIs
er representing the row that should be deleted. however, the special index -1 can be used to remove the very last row of a table. return value no return value errors thrown if the number of the row to delete, specified by the parameter, is greater or equal to the number of available rows, or if it is negative and not equal to the special index -1, representing the last row of the table, the
exception index_size_err is thrown. example this example uses javascript to delete a table's second row. html <table> <tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td><td>cell 2.3</td></tr> <tr><td>cell 3.1</td><td>cell 3.2</td><td>cell 3.3</td></tr> </table> javascript let table = document.queryselector('table'); // delete second row table.del...
HTMLTableElement.insertRow() - Web APIs
f document.createelement() had been used to create the new <tr> element. syntax var newrow = htmltableelement.insertrow(index); htmltableelement is a reference to an html <table> element. parameters index optional the row index of the new row. if index is -1 or equal to the number of rows, the row is appended as the last row. if index is greater than the number of rows, an indexsizeerror
exception will result. if index is omitted it defaults to -1. return value newrow is an htmltablerowelement that references the new row. example this example uses insertrow(-1) to append a new row to a table. we then use htmltablerowelement.insertcell() to insert a new cell in the new row. (to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using docu...
HTMLTableRowElement.insertCell() - Web APIs
l() to create a new <th> element though. syntax var newcell = htmltablerowelement.insertcell(index); htmltablerowelement is a reference to an html <tr> element. parameters index optional index is the cell index of the new cell. if index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. if index is greater than the number of cells, an indexsizeerror
exception will result. if index is omitted it defaults to -1. return value newcell is an htmltablecellelement that references the new cell. example this example uses htmltableelement.insertrow() to append a new row to a table. we then use insertcell(0) to insert a new cell in the new row. (to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using docum...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
possible to enqueue microtasks in the past (such as by creating a promise that resolves immediately), the addition of the queuemicrotask() method adds a standard way to introduce a microtask safely and without tricks. by introducing queuemicrotask(), the quirks that arise when sneaking in using promises to create microtasks can be avoided. for instance, when using promises to create microtasks,
exceptions thrown by the callback are reported as rejected promises rather than being reported as standard
exceptions. also, creating and destroying promises takes additional overhead both in terms of time and memory that a function which properly enqueues microtasks avoids. simply pass the javascript function to call while the context is handling microtasks into the queuemicrotask() method, which is expo...
History.replaceState() - Web APIs
state object can be null. title most browsers currently ignore this parameter, although they may use it in the future. passing the empty string here should be safe against future changes to the method. alternatively, you could pass a short title for the state. url optional the url of the history entry. the new url must be of the same origin as the current url; otherwise replacestate throws an
exception. examples suppose https://www.mozilla.org/foo.html executes the following javascript: const stateobj = { foo: 'bar' }; history.pushstate(stateobj, '', 'bar.html'); the explanation of these two lines above can be found in the example of pushstate() method section of the working with the history api article. then suppose https://www.mozilla.org/bar.html executes the following javascript: hist...
History - Web APIs
e without having to wait for a popstate event. methods the history interface doesn't inherit any methods. back() this asynchronous method goes to the previous page in session history, the same action as when the user clicks the browser's back button. equivalent to history.go(-1). calling this method to go back beyond the first page in the session history has no effect and doesn't raise an
exception. forward() this asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's forward button; this is equivalent to history.go(1). calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an
exception. go() asynchronously loads a page from the session history, identified by i...
IDBCursor.advance() - Web APIs
the advance() method of the idbcursor interface sets the number of times a cursor should move its position forward. note: this feature is available in web workers. syntax cursor.advance(count); parameters count the number of times to move the cursor forward.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbcursor's transaction is inactive. typeerror the value passed into the count parameter was zero or a negative number. invalidstateerror the cursor is currently being iterated or has iterated past its end. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through the records i...
IDBCursor.continue() - Web APIs
method of the idbcursor interface advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. if no key is specified, the cursor advances to the immediate next position, based on its direction. note: this feature is available in web workers. syntax cursor.continue(key); parameters key optional the key to position the cursor at.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbcursor's transaction is inactive. dataerror the key parameter may have any of the following conditions: the key is not a valid key. the key is less than or equal to this cursor's position and the cursor's directi...
IDBCursor.continuePrimaryKey() - Web APIs
because the cursor’s got value flag has been unset. this method is only valid for cursors coming from an index. using it for cursors coming from an object store will throw an error. note: this feature is available in web workers. syntax cursor.continueprimarykey(key, primarykey); parameters key the key to position the cursor at. primarykey the primary key to position the cursor at.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbcursor's transaction is inactive. dataerror the key parameter may have any of the following conditions: the key is not a valid key. the key is less than or equal to this cursor's position and the cursor's directi...
IDBCursor.delete() - Web APIs
ull. be aware that you can't call delete() (or idbcursor.update()) on cursors obtained from idbindex.openkeycursor(). for such needs, you have to use idbindex.opencursor() instead. note: this feature is available in web workers. syntax myidbcursor.delete(); returns an idbrequest object on which subsequent events related to this operation are fired. the result attribute is set to undefined.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbcursor's transaction is inactive. readonlyerror the transaction mode is read-only. invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end. e...
IDBCursor.source - Web APIs
note: this feature is available in web workers. syntax var source = cursor.source; value the idbobjectstore or idbindex that the cursor is iterating over. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. ...
IDBCursor.update() - Web APIs
te()) on cursors obtained from idbindex.openkeycursor(). for such needs, you have to use idbindex.opencursor() instead. note: this feature is available in web workers. syntax var anidbrequest = myidbcursor.update(value); parameters value the new value to be stored at the current position. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbcursor's transaction is inactive. readonlyerror the transaction mode is read only. invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end. ...
IDBCursor - Web APIs
object representing a given cursor. operations are performed on the underlying index or object store. note: this feature is available in web workers. properties note: idbcursorwithvalue is an idbcursor interface with an additional value property. idbcursor.source read only returns the idbobjectstore or idbindex that the cursor is iterating. this function never returns null or throws an
exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active. idbcursor.direction read only returns the direction of traversal of the cursor. see constants for possible values. idbcursor.key read only returns the key for the record at the cursor's position. if the cursor is outside its range, this is set to undefined. the cursor's key can be a...
IDBDatabase.createObjectStore() - Web APIs
keypath the key path to be used by the new object store. if empty or not specified, the object store is created without a key path and uses out-of-line keys. you can also pass in an array as a keypath. autoincrement if true, the object store has a key generator. defaults to false. unknown parameters are ignored. returns a new idbobjectstore.
exceptions this method may raise a dom
exception 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. transactioninactiveerror occurs if a request is made on a source database that doesn't exist (e.g. has b...
IDBDatabase.deleteObjectStore() - Web APIs
interface destroys the object store with the given name in the connected database, along with any indexes that reference it. as with idbdatabase.createobjectstore, this method can be called only within a versionchange transaction. note: this feature is available in web workers. syntax dbinstance.deleteobjectstore(name); parameters name the name of the object store you want to delete.
exceptions this method may raise a dom
exception 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. transactioninactiveerror occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or ...
databases - Web APIs
note: this method is introduced in a draft of a specifications and browser compatibility is limited. syntax const promise = indexeddb.databases() parameters the method does not take in any parameters. return value a promise that resolves either to an error or a list of dictionaries, each with two elements, name and version. name the database name. version the database version.
exceptions this method may raise a dom
exception of the following types: attribute description securityerror the method is called from an opaque origin. other error specification does not describe all possible errors. example const promise = indexeddb.databases() promise.then(databases => { console.log(databases) }) specifications specification ...
IDBFactory.deleteDatabase() - Web APIs
ange event. note: this feature is available in web workers. syntax for the current standard: var request = indexeddb.deletedatabase(name); for the experimental version with options (see below): var request = indexeddb.deletedatabase(name, options); parameters name the name of the database you want to delete. note that attempting to delete a database that doesn't exist does not throw an
exception, in contrast to idbdatabase.deleteobjectstore(), which does throw an
exception if the named object store does not exist. optionsnon-standard in gecko, since version 26, you can include a non-standard optional storage parameter that specifies whether you want to delete a permanent (the default value) indexeddb, or an indexeddb in temporary storage (aka shared pool.) return value a idbopendbre...
IDBFactory.open() - Web APIs
will soon be removed from gecko. you should use storagemanager.persist() to get persistent storage instead. note: you can find out more information on the different available storage types, and how firefox handles client-side data storage, at browser storage limits and eviction criteria. return value a idbopendbrequest object on which subsequent events related to this request are fired.
exceptions this method may raise a dom
exception of the following types:
exception description typeerror the value of version is zero or a negative number or not a number. 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 dat...
IDBIndex.count() - Web APIs
bject, and in a separate thread, returns the number of records within a key range. note: this feature is available in web workers. syntax var request = myindex.count(); var request = myindex.count(key); parameters key optional the key or key range that identifies the record to be counted. return value a idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a tra...
IDBIndex.get() - Web APIs
e record the key is associated with. note: this feature is available in web workers. syntax var request = myindex.get(key); parameters key optional a key or idbkeyrange that identifies the record to be retrieved. if this value is null or missing, the browser will use an unbound key range. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a tra...
IDBIndex.getKey() - Web APIs
whole record as idbindex.get does. note: this feature is available in web workers. syntax var request = myindex.getkey(key); parameters key optional a key or idbkeyrange that identifies a record to be retrieved. if this value is null or missing, the browser will use an unbound key range. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been deleted or removed. example in the following example we open a tra...
IDBIndex.openCursor() - Web APIs
(range, direction); parameters range optional a key or idbkeyrange to use as the cursor's range. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional the cursor's direction. see idbcursor constants for possible values. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. typeerror the value for the direction parameter is invalid. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been de...
IDBIndex.openKeyCursor() - Web APIs
(range, direction); parameters range optional a key or idbkeyrange to use as the cursor's range. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional the cursor's direction. see idbcursor constants for possible values. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbindex's transaction is inactive. typeerror the value for the direction parameter is invalid. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbindex has been de...
IDBKeyRange.bound() - Web APIs
arameters lower specifies the lower bound of the new key range. upper specifies the upper bound of the new key range. loweropen optional indicates whether the lower bound excludes the endpoint value. the default is false. upperopen optional indicates whether the upper bound excludes the endpoint value. the default is false. return value idbkeyrange: the newly created key range.
exceptions this method may raise a dom
exception of the following type:
exception description dataerror the following conditions raise an
exception: the lower or upper parameters were not passed a valid key. the lower key is greater than the upper key. the lower key and upper key match and either of the bounds are open. example the fol...
IDBKeyRange.includes() - Web APIs
the includes() method of the idbkeyrange interface returns a boolean indicating whether a specified key is inside the key range. note: this feature is available in web workers. syntax var isincluded = mykeyrange.includes(key) parameters key the key you want to check for in your key range. this can be any type. return value a boolean.
exceptions this method may raise a dom
exception of the following type: attribute description dataerror the supplied key was not a valid key. example var keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns false polyfill the includes() method was added in the second edition of the indexed db specifica...
IDBKeyRange.lowerBound() - Web APIs
note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.lowerbound(lower); var myidbkeyrange = idbkeyrange.lowerbound(lower, open); parameters lower specifies the lower bound of the new key range. open optional indicates whether the lower bound excludes the endpoint value. the default is false. return value idbkeyrange: the newly created key range.
exceptions this method may raise a dom
exception of the following type:
exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use a lower bound key range. here we declare keyrangevalue = idbkeyrange.lowerbound("f", false); — a range that includes the value "f" and everthing a...
IDBKeyRange.only() - Web APIs
the only() method of the idbkeyrange interface creates a new key range containing a single value. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.only(value); parameters value is the value for the new key range. return value idbkeyrange: the newly created key range.
exceptions this method may raise a dom
exception of the following types:
exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use an only key range. here we declare a keyrangevalue = idbkeyrange.only("a"); — a range that only includes the value "a". we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.open...
IDBKeyRange.upperBound() - Web APIs
includes the upper endpoint value and is closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.upperbound(upper[, open=false]) parameters bound specifies the upper bound of the new key range. open indicates whether the upper bound excludes the endpoint value. the default is false. optional return value idbkeyrange: the newly created key range.
exceptions this method may raise a dom
exception of the following type:
exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use an upper bound key range. here we declare keyrangevalue = idbkeyrange.upperbound("f"); — a range that includes the value "f" and everything before it. we...
IDBLocaleAwareKeyRange - Web APIs
ale aware sorting enabled. methods this interface inherits all the methods of its parent interface, idbkeyrange. properties this interface inherits all the properties of its parent interface, idbkeyrange. bear in mind however that idblocaleawarekeyrange has its own implementation of idbkeyrange.bound. this is because when you use bound(), it checks if lower bound < upper bound, and throws an
exception if that’s not the case. with locale-aware indexes, the meaning of < depends on the locale, so for example in lithuanian y is sorted between i and k. the only difference between idbkeyrange and idblocaleawarekeyrange is that the latter doesn’t do the aforementioned check. developers should always use idblocaleawarekeyrange when dealing with locale-aware indexes. examples function displaydat...
IDBObjectStore.add() - Web APIs
tstore.put method instead. note: this feature is available in web workers. syntax var request = objectstore.add(value); var request = objectstore.add(value, key); parameters value the value to be stored. key optional the key to use to identify the record. if unspecified, it results to null. returns an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror any of the following conditions apply: the object store uses in-line keys...
IDBObjectStore.clear() - Web APIs
ving all records from the object store and removing all records in indexes that reference the object store. to remove only some of the records in a store, use idbobjectstore.delete passing a key or idbkeyrange. note: this feature is available in web workers. syntax var request = objectstore.clear(); returns an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. example in the following code snippet, we open a read/write transaction on our database and clear...
IDBObjectStore.count() - Web APIs
returns the total number of records in the store. note: this feature is available in web workers. syntax var request = objectstore.count(); var request = objectstore.count(query); parameters query optional a key or idbkeyrange object that specifies a range of records you want to count. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description invalidstateerror this idbobjectstore has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a transaction, retrieve...
IDBObjectStore.createIndex() - Web APIs
ue in one of three ways: string: a string containing a specific locale code, e.g. en-us, or pl. auto: the platform default locale will be used (may be changed by user agent settings.) null or undefined: if no locale is specified, normal javascript sorting will be used — not locale-aware. return value an idbindex object: the newly created index.
exceptions this method may raise a dom
exception of one of the following types:
exception description constrainterror occurs if an index with the same name already exists in the database. index names are case-sensitive. invalidaccesserror occurs if the provided key path is a sequence, and multientry is set to true in the objectparameters object. invalidstat...
IDBObjectStore.delete() - Web APIs
eature is available in web workers. syntax var request = objectstore.delete(key); var request = objectstore.delete(keyrange); parameters key the key of the record to be deleted, or an idbkeyrange to delete all records with keys in range. return value an idbrequest object on which subsequent events related to this operation are fired. the request.result attribute is set to undefined.
exceptions this method may raise a dom
exception of the following types:
exception description transactioninactiveerror this object store's transaction is inactive. readonlyerror the object store's transaction mode is read-only. invalidstateerror the object store has been deleted. dataerror the key is not a valid key or a key range. ...
IDBObjectStore.deleteIndex() - Web APIs
e, used during a version upgrade. note that this method must be called only from a versionchange transaction mode callback. note that this method synchronously modifies the idbobjectstore.indexnames property. note: this feature is available in web workers. syntax objectstore.deleteindex(indexname); parameters indexname the name of the existing index to remove. return value undefined
exceptions this method may raise a dom
exception of one of the following types:
exception description invalidstateerror occurs if the method was not called from a versionchange transaction mode callback. transactioninactiveerror occurs if the transaction this idbobjectstore belongs to is not active (e.g. has been deleted or removed.) in firefox previous to version 4...
IDBObjectStore.get() - Web APIs
encursor() method with the same key. that method provides a cursor if the record exists, and no cursor if it does not. note: this feature is available in web workers. syntax var request = objectstore.get(key); parameters key the key or key range that identifies the record to be retrieved. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbobjectstore has been deleted or removed. example in the following cod...
IDBObjectStore.getAllKeys() - Web APIs
sts, and no cursor if it does not. syntax var request = objectstore.getallkeys(); var request = objectstore.getallkeys(query); var request = objectstore.getallkeys(query, count); parameters query optional a value that is or resolves to an idbkeyrange. count optional specifies the number of values to return if more than one is found. if it is lower than 0 or greater than 232-1 a typeerror
exception will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid k...
IDBObjectStore.getKey() - Web APIs
a key is successfully found, then a structured clone of it is created and set as the result of the request object. note: this feature is available in web workers. syntax var request = objectstore.getkey(key); parameters key the key or key range that identifies the record to be retrieved. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbobjectstore has been deleted or removed. example let openrequest = in...
IDBObjectStore.index() - Web APIs
of the idbobjectstore interface opens a named index in the current object store, after which it can be used to, for example, return a series of records sorted by that index using a cursor. note: this feature is available in web workers. syntax var index = objectstore.index(name); parameters name the name of the index to open. return value an idbindex object for accessing the index.
exceptions this method may raise a dom
exception of one of the following types:
exception description invalidstateerror the source object store has been deleted, or the transaction for the object store has finished. notfounderror there is no index with the given name (case-sensitive) in the database. example in the following example we open a transacti...
IDBObjectStore.name - Web APIs
the name property of the idbobjectstore interface indicates the name of this object store. note: this feature is available in web workers. syntax idbobjectstore.name = mynewname; var myobjectstorename = idbobjectstore.name; value a domstring containing the object store's name.
exceptions there are a several
exceptions which can occur when you attempt to change an object store's name. invalidstateerror either the object store has been deleted or the current transaction is not an upgrade transaction; you can only rename indexes during upgrade transactions; that is, when the mode is "versionchange". transactioninactiveerror the current transaction is not active. constrainterror an object store is already using the specified name. example in the following code snippet, we open a r...
IDBObjectStore.openCursor() - Web APIs
only that key. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional an idbcursordirection telling the cursor what direction to travel. valid values are "next", "nextunique", "prev", and "prevunique". the default is "next". return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description invalidstateerror this idbobjectstore or idbindex has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a tra...
IDBObjectStore.openKeyCursor() - Web APIs
only that key. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional an idbcursordirection telling the cursor what direction to travel. valid values are "next", "nextunique", "prev", and "prevunique". the default is "next". return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description invalidstateerror this idbobjectstore or idbindex has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the specified key or key range is invalid. example in this simple fragment we create a tra...
IDBObjectStore.put() - Web APIs
m idbcursor.primarykey). this is only needed for object stores that have an autoincrement primary key, therefore the key is not in a field on the record object. 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. return value an idbrequest object on which subsequent events related to this operation are fired.
exceptions this method may raise a dom
exception of one of the following types:
exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror any of the following conditions apply: the object store uses in-line keys...
IDBRequest.result - Web APIs
note: this feature is available in web workers. syntax var myresult = request.result; value any example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store. ...
IDBTransaction.abort() - Web APIs
the abort() method of the idbtransaction interface rolls back all the changes to objects in the database associated with this transaction. all pending idbrequest objects created during this transaction have their idbrequest.error attribute set to aborterror. note: this feature is available in web workers. syntax transaction.abort();
exceptions this method may raise a dom
exception of the following type:
exception description invalidstateerror the transaction has already been committed or aborted. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success...
IDBTransaction: abort event - Web APIs
fired when an indexeddb transaction is aborted. 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. examples this example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the abort event, then aborts the transaction to trigger the event. // open the database const dbopen...
IDBTransaction.commit() - Web APIs
ction. note that commit() doesn't normally have to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. commit() can be used to start the commit process without waiting for events from outstanding requests to be dispatched. if it is called on a transaction that is not active, it throws an invalidstateerror dom
exception. note: this feature is available in web workers. syntax transaction.commit(); parameters none. return value void.
exceptions
exception description invalidstateerror the transaction state is not active. examples // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["mydb"], "readwrite"); // report on the succe...
IDBTransaction.objectStore() - Web APIs
t, 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. note: this feature is available in web workers. syntax idbtransaction.objectstore(name); parameters name the name of the requested object store. return value an idbobjectstore object for accessing an object store.
exceptions this method may raise a dom
exception of one of the following types:
exception description notfounderror the requested object store is not in this transaction's scope. invalidstateerror the request was made on a source object that has been deleted or removed, or if the transaction has finished. example in the following code snippet, we open a read...
IIRFilterNode.getFrequencyResponse() - Web APIs
containing an array of frequencies, specified in hertz, which you want to filter. magresponseoutput a float32array to receive the computed magnitudes of the freqency response for each frequency value in the frequencyarray. phaseresponseoutput a float32array to receive the computed phase response values in radians for each frequency value in the input frequencyarray. return value undefined
exceptions notsupportederror the three arrays provided are not all of the same length. examples in the following example we are using an iir filter on a media stream (for a complete full demo, see our stream-source-buffer demo live, or read its source.) as part of this demo, we get the frequency responses for this iir filter, for five sample frequencies. we first create the float32array objects we n...
Basic concepts - Web APIs
u do in indexeddb always happens in the context of a transaction. the indexeddb api provides lots of objects that represent indexes, tables, cursors, and so on, but each of these is tied to a particular transaction. thus, you cannot execute commands or open cursors outside of a transaction. transactions have a well-defined lifetime, so attempting to use a transaction after it has completed throws
exceptions. also, transactions auto-commit and cannot be committed manually. this transaction model is really useful when you consider what might happen if a user opened two instances of your web app in two different tabs simultaneously. without transactional operations, the two instances could interfere with each other's modifications. if you are not familiar with transactions in a database, read the w...
Using IndexedDB - Web APIs
ion, and outside the scope of this article.) if you need to look up a customer by name, however, you'll need to iterate over every ssn in the database until you find the right one. searching in this fashion would be very slow, so instead you can use an index. // first, make sure you created index in request.onupgradeneeded: // objectstore.createindex("name", "name"); // otherwize you will get dom
exception. var index = objectstore.index("name"); index.get("donna").onsuccess = function(event) { console.log("donna's ssn is " + event.target.result.ssn); }; the "name" index isn't unique, so there could be more than one entry with the name set to "donna". in that case you always get the one with the lowest key value. if you need to access all the entries with a given name you can use a cursor. yo...
IndexedDB API - Web APIs
cumented in case you need to update previously written code: idbversionchangerequest represents a request to change the version of a database. 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. idbdatabase
exception represents
exception conditions that can be encountered while performing database operations. idbtransactionsync sync version of idbtransaction. idbobjectstoresync sync version of idbobjectstore. idbindexsync sync version of idbindex. idbfactorysync sync version of idbfactory. idbenvironmentsync sync version of idbenvironment. idbdatabasesync sync version of idbdatabas...
InstallEvent - Web APIs
event. 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. the promise resolves when all resources have been fetched and cached, or when any
exception occurs. the code snippet also shows a best practice for versioning caches used by the service worker. although this example has only one cache, you can use this approach for multiple caches. the code maps a shorthand identifier for a cache to a specific, versioned cache name. note: logging statements are visible in google chrome via the "inspect" interface for the relevant service worker acces...
IntersectionObserver.IntersectionObserver() - Web APIs
observer api for a more in-depth description of how thresholds are used. the default is a threshold of 0.0. return value a new intersectionobserver which can be used to watch for the visibility of a target element within the specified root crossing through any of the specified visibility thresholds. call its observe() method to begin watching for the visibility changes on a given target.
exceptions syntaxerror the specified rootmargin is invalid. rangeerror one or more of the values in threshold is outside the range 0.0 to 1.0. example this example creates a new intersection observer which calls the function myobservercallback every time the visible area of the element being observed changes by at least 10%. let observer = new intersectionobserver(myobservercallback, ...
IntersectionObserverEntry.intersectionRect - Web APIs
ntly visible within the intersection root. syntax var intersectionrect = intersectionobserverentry.intersectionrect; value a domrectreadonly which describes the part of the target element that's currently visible within the root's intersection rectangle. this rectangle is computed by taking the intersection of boundingclientrect with each of the target's ancestors' clip rectangles, with the
exception of the intersection root itself. 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 intersectioncallback(entries) { entries.foreach(function(entry) { refreshzones.push({ element: entry.target, rect: entry.intersectionre...
Location: assign() - Web APIs
the location.assign() method causes the window to load and display the document at the url specified. after the navigation occurs, the user can navigate back to the page that called location.assign() by pressing the "back" button. if the assignment can't happen because of a security violation, a dom
exception of the security_error type is thrown. 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. if the provided url is not valid, a dom
exception of the syntax_error type is thrown. syntax location.assign(url); parameters url is a domstring containing the url of the page to navigate to. example // navigate to the location.reload article win...
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. see same-origin policy for more information. syntax location.reload(); specifications specification status comment html living standardthe definition of 'location.reload()' in that specification. ...
Location: replace() - Web APIs
the replace() method of the location interface replaces the current resource with the one at the provided url. the difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the back button to navigate to it. if the assignment can't happen because of a security violation, a dom
exception of the security_error type is thrown. 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. if the provided url is not valid, a dom
exception of the syntax_error type is thrown. syntax object.replace(url); parameters url is a domstring containing the url of the p...
MediaCapabilities.decodingInfo() - Web APIs
uration) parameters mediadecodingconfiguration a valid mediadecodingconfiguration dictionary containing a valid media decoding type of file or media-source and a valid media configuration: either an audioconfiguration or a videoconfiguration. ...
MediaCapabilities.encodingInfo() - Web APIs
arameters mediaencodingconfiguration a valid mediaencodingconfiguration dictionary containing a valid media encoding type of record or transmission and a valid media configuration: either an audioconfiguration or videoconfiguration dictionary. return value a promise fulfilling with a mediacapabilitiesinfo interface containing three boolean attributes: supported smooth powerefficient
exceptions a typeerror is raised if the mediaconfiguration passed to the encodinginfo() method is invalid, either because the type is not video or audio, the contenttype is not a valid codec mime type, or any other error in the media configuration passed to the method, including omitting any of the media encoding configuration elements. example //create media configuration to be tested const ...
MediaDevices.getDisplayMedia() - Web APIs
at resolves to a mediastream containing a video track whose contents come from a user-selected screen area, as well as an optional audio track. note: browser support for audio tracks varies, both in terms of whether or not they're supported at all by the media recorder and in terms of the which audio source or sourcoes are supported. check the compatibility table for details for each browser.
exceptions rejections of the returned promise are made by passing a dom
exception error object to the promise's failure handler. possible errors are: aborterror an error or failure that doesn't match any of the other
exceptions below occurred. 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...
MediaDevices.getUserMedia() - Web APIs
ameradeviceid } } the above will return the camera you requested, or a different camera if that specific camera is no longer available. again, to require the specific camera, you would use: { video: { deviceid: { exact: myexactcameraorbustdeviceid } } } return value a promise whose fulfillment handler receives a mediastream object when the requested media has successfully been obtained.
exceptions rejections of the returned promise are made by passing a dom
exception error object to the promise's failure handler. possible errors are: aborterror although the user and operating system both granted access to the hardware device, and no hardware issues occurred that would cause a notreadableerror, some problem occurred which prevented the device from being used. notallowederror one or m...
MediaRecorder() - Web APIs
s can be specified instead of the above two properties. if this is specified along with one or the other of the above properties, this will be used for the one that isn't specified. if bits per second values are not specified for video and/or audio, the default adopted for video is 2.5mbps, while the audio default is adaptive, depending upon the sample rate and the number of channels.
exceptions notsupportederror the specified mime type is not supported by the user agent. example this example shows how to create a media recorder for a specified stream, whose audio bit rate is set to 128 kbit/sec and whose video bit rate is set to 2.5 mbit/sec. the recorded media data will be stored in an mp4 wrapper (so if you gather the chunks of media data and save them to disk, they will be in...
MediaRecorder.pause() - Web APIs
ues a task that runs the below steps: if mediarecorder.state is "inactive", raise a dom invalidstate error and terminate these steps. if not, continue to the next step. set mediarecorder.state to "paused". stop gathering data into the current blob, but keep it available so that recording can be resumed later on. raise a pause event. syntax mediarecorder.pause() return value undefined.
exceptions invalidstateerror the mediarecorder is currently "inactive"; you can't pause recording if it's not active. if you call pause() while already paused, it silently does nothing. example ... pause.onclick = function() { mediarecorder.pause(); console.log("recording paused"); } ... specifications specification status comment mediastream recordingthe defi...
MediaRecorder - Web APIs
ded media in its data property. you can then collect and act upon that recorded media data using this event handler. mediarecorder.onerror an eventhandler called to handle the error event, including reporting errors that arise with media recording. these are fatal errors that stop recording. the received event is based on the mediarecordererrorevent interface, whose error property contains a dom
exception that describes the actual error that occurred. mediarecorder.onpause an eventhandler called to handle the pause event, which occurs when media recording is paused. mediarecorder.onresume an eventhandler called to handle the resume event, which occurs when media recording resumes after being paused. mediarecorder.onstart an eventhandler called to handle the start event, which occurs when med...
MediaRecorderErrorEvent() - Web APIs
by the mediastream recording api. in general, you won't create these yourself; they are delivered to your implementation of mediarecorder.onerror when errors occur while recording media. syntax var errorevent = new mediarecordererrorevent(errorinfo) parameters errorinfo an object describing the error object to be created. it must contain the error property at a minimum. error a dom
exception that describes the error that occurred. this object's name property should indicate the name of the error that occurred. the other fields may or may not be present. some user agents add to the error object other properties that provide information such as stack dumps, the name of the javascript file and the line number where the error occurred, and other debugging aids, but you should not ...
MediaSession.setPositionState() - Web APIs
avigator object's mediasession object. syntax navigator.mediasession.setpositionstate(statedict); parameters statedict optional an object conforming to the mediapositionstate dictionary, providing updated information about the playback position and speed of the document's ongoing media. if the object is empty, the existing playback state information is cleared. return value undefined.
exceptions typeerror this error can occur in an array of circumstances: the specified mediapositionstate object's duration is missing, negative, or null. position is missing or null, or is either negative or greater than duration. the playbackrate is zero. example in this example, a player for a non-standard media file format, written in javascript, uses setinterval() to establish a c...
MediaSource.addSourceBuffer() - Web APIs
ds it to the mediasource's sourcebuffers list. the new sourcebuffer is also returned. syntax var sourcebuffer = mediasource.addsourcebuffer(mimetype); parameters mimetype a domstring specifying the mime type of the sourcebuffer to create and add to the mediasource. return value a sourcebuffer object representing the new source buffer that has been created and added to the media source.
exceptions invalidaccesserror the value specified for mimetype is an empty string rather than a valid mime type. invalidstateerror the mediasource is not in the "open" readystate. notsupportederror the specified mimetype isn't supported by the user agent, or is not compatible with the mime types of other sourcebuffer objects that are already included in the media source's sourcebuffers list. quota...
MediaSource.duration - Web APIs
the duration property of the mediasource interface gets and sets the duration of the current media being presented. syntax mediasource.duration = 5.5; // 5.5 seconds var myduration = mediasource.duration; value a double. a value in seconds is expected.
exceptions the following
exceptions may be thrown when setting a new value for this property.
exception explanation invalidaccesserror an attempt was made to set a duration value that was negative, or nan. invalidstateerror mediasource.readystate is not equal to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is true.) example the following snippet is based on a simple example written by nick de...
MediaSource.endOfStream() - Web APIs
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. this can be used to indicate that a parsing error has occured while fetching media data; maybe the data is corrupt, or is encoded using a codec that the browser doesn't know how to decode. return value undefined
exceptions
exception explanation invalidstateerror mediasource.readystate is not equal to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is true.) example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source f...
MediaSource.removeSourceBuffer() - Web APIs
the removesourcebuffer() method of the mediasource interface removes the given sourcebuffer from the sourcebuffers list associated with this mediasource object. syntax mediasource.removesourcebuffer(sourcebuffer); parameters sourcebuffer the sourcebuffer object to be removed. return value undefined
exceptions
exception explanation notfounderror the supplied sourcebuffer doesn't exist in mediasource.sourcebuffers. examples for (i = 0; i < 10; i++) { var sourcebuffer = mediasource.addsourcebuffer(mimecodec); } mediasource.removesourcebuffer(mediasource.sourcebuffers[0]); specifications specification status comment media source extensionsthe definition of 'removesourcebuffer()' in that specification. recommenda...
MediaStreamAudioSourceNode() - Web APIs
be associated with. options a mediastreamaudiosourceoptions object defining the properties you want the mediastreamaudiosourcenode to have: mediastream a required property which specifies the mediastream from which to obtain audio for the node. return value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream.
exceptions invalidstateerror the specified mediastream doesn't have any audio tracks. examples this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from its mediastream. // define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // getusermedia block - grab stream // put it into a mediastreamaudiosou...
MediaStreamAudioSourceNode - Web APIs
iastreamaudiosourcenode() creates a new mediastreamaudiosourcenode object instance with the specified options. properties in addition to the following properties, mediastreamaudiosourcenode inherits the properties of its parent, audionode. mediastream read only the mediastream used when constructing this mediastreamaudiosourcenode. methods inherits methods from its parent, audionode.
exceptions invalidstateerror the stream specified by the mediastream parameter does not contain any audio tracks. usage notes typically, you should probably not use this type of node. it has been replaced with the more predictable mediastreamtrackaudiosourcenode, which has better-defined rules for how it chooses the track to output. if you do chooose to use mediastreamaudiosourcenode, you should ke...
MediaStreamTrackAudioSourceNode() - Web APIs
be associated with. options a mediastreamtrackaudiosourceoptions object defining the properties you want the mediastreamtrackaudiosourcenode to have: mediastreamtrack the mediastreamtrack from which to take audio data for this node's output. return value a new mediastreamtrackaudiosourcenode object representing the audio node whose media is obtained from the specified media track.
exceptions notsupportederror the specified context is not an audiocontext. invalidstateerror the specified mediastreamtrack isn't an audio track (that is, its kind property isn't audio. example this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from the first audio track provided by the device. let audioctx = new (window.audiocont...
MediaStream Image Capture API - Web APIs
ies = track.getcapabilities(); // check whether zoom is supported or not. if(!capabilities.zoom) { return; } track.applyconstraints({ advanced : [{ zoom: zoom.value }] }); finally, pass the mediastreamtrack object to the imagecapture() constructor. though a mediastream holds several types of tracks and provides multiple methods for retrieving them, the imagecapture constructor will throw a dom
exception of type notsupportederror if mediastreamtrack.kind is not "video". let imagecapture = new imagecapture(track); interfaces imagecapture an interface for capturing images from a photographic device referenced through a valid mediastreamtrack. photocapabilities provides available configuration options for an attached photographic device. retrieve a photocapabilities object by calling imagec...
MediaStream Recording API - Web APIs
o a local disk). reference blobevent each time a chunk of media data is finished being recorded, it's delivered to consumers in blob form using a blobevent of type dataavailable. mediarecorder the primary interface that implements the mediastream recording api. mediarecordererrorevent the interface that represents errors thrown by the mediastream recording api. its error property is a dom
exception that specifies that error occurred. specifications specification status comment mediastream recording working draft initial definition ...
MediaTrackConstraints.deviceId - Web APIs
f guid is recommended). 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(). an
exception to the rule that device ids are the same across browsing sessions: private browsing mode will use a different id, and will change it each browsing session. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'deviceid' in that spe...
MediaTrackSettings.deviceId - Web APIs
ugh the specification does recommend it be a guid. since there is a one-to-one pairing of id with each source, all tracks with the same source will share the same id for any given origin, so mediastreamtrack.getcapabilities() will always return exactly one value for deviceid. that makes the device id not useful for any changes to constraints when calling mediastreamtrack.applyconstraints(). an
exception to the rule that device ids are the same across browsing sessions: private browsing mode will use a different id, and will change it each browsing session. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'deviceid' in that spe...
MediaTrackSettings - Web APIs
op-and-scale" the track's resolution might be the result of the user agent using cropping or downscaling from a higher camera resolution. properties of shared screen tracks tracks containing video shared from a user's screen (regardless of whether the screen data comes from the entire screen or a portion of a screen, like a window or tab) are generally treated like video tracks, with the
exception that they also support the following added settings: cursor a domstring which indicates whether or not the mouse cursor is being included in the generated stream and under what conditions. possible values are: always the mouse is always visible in the video content of the {domxref("mediastream"), unless the mouse has moved outside the area of the content. motion the mouse cursor ...
MerchantValidationEvent() - Web APIs
his is an empty string by default. validationurl optional the url from which to retrieve payment handler specific verification information used to validate the merchant. this is an empty string by default. 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().
exceptions typeerror the string specified as validationurl could not be parsed as a url. rangeerror the specified methodname does not correspond to a known and supported merchant or is not a well-formed standard payment method identifier. specifications specification status comment payment request apithe definition of 'merchantvalidationevent()' in that specification. ca...
MerchantValidationEvent.complete() - Web APIs
ion event, passing in the data fetched from the validationurl. syntax merchantvalidationevent.complete(validationdata); merchantvalidationevent.complete(merchantsessionpromise); parameters validationdata or merchantsessionpromise an object containing the data needed to complete the merchant validation process, or a promise which resolves to the validation data. return value undefined.
exceptions this
exception may be passed into the rejection handler for the promise: invalidstateerror the event did not come directly from the user agent, but was instead dispatched by other code. another payment request is currently being processed, the current payment request is not currently being displayed to the user, or payment information is currently being updated. example in this example, ...
Microdata DOM API - Web APIs
argument, the user agent may return the same object as the object returned by the earlier call. in other cases, a new nodelist object must be returned. properties element . itemvalue [ = value ] returns the element's value. can be set, to change the element's value. setting the value when the element has no itemprop attribute or when the element's value is an item throws an invalidaccesserror
exception. element . properties if the element has an itemscope attribute, returns an htmlpropertiescollection object with all the element's properties. otherwise, an empty htmlpropertiescollection object. code example this sample shows how the getitems() method can be used to obtain a list of all the top-level microdata items of a particular type given in the document: var cats = document.getitems("h...
MutationObserver.observe() - Web APIs
.disconnect(). syntax mutationobserver.observe(target, options) parameters target a dom node (which may be an element) within the dom tree to watch for changes, or to be the root of a subtree of nodes to be watched. options a mutationobserverinit object providing options that describe which dom mutations should be reported to mutationobserver’s callback. return value undefined.
exceptions typeerror thrown in any of the following circumstances: the options are configured such that nothing will actually be monitored. (for example, if mutationobserverinit.childlist, mutationobserverinit.attributes, and mutationobserverinit.characterdata are all false.) the value of options.attributes is false (indicating that attribute changes are not to be monitored), but attributeold...
NDEFReader.scan() - Web APIs
atch pattern for matching each ndefrecord.id. recordtype -- the match pattern for matching each ndefrecord.recordtype. mediatype -- the match pattern for matching each ndefrecord.mediatype. signal -- optional abortsignal that allows to cancell this scan() operation. return value a promise that resolves with undefined immediatelly after scheduling read operations for the nfc adapter.
exceptions this method doesn't throw true
exceptions; instead, it rejects the returned promise, passing into it a dom
exception whose name is one of the following: aborterror the scan operation was aborted with abortsignal passed in options. notallowederror the permission for this operation was rejected. notsupportederror there is no nfc adapter compatible with web nfc, or a connection can not be e...
NDEFRecord.toRecords() - Web APIs
the torecords() method of the ndefrecord interface of web nfc api parses record payload ndefrecord.data besed on ndefrecord.recordtype and returns the result. in practice, it's possible to implement the parsing mechanism manually, but this method simplifies the process. syntax ndefrecord.torecords() parameters none. return value a list of ndefrecords.
exceptions notsupported the user agent does not know how to parse this combination of ndefrecord.data and ndefrecord.recordtype. specifications specification status comment web nfc, ndefrecord.torecords() draft initial definition. ...
NDEFWriter.write() - Web APIs
r or not to skip reading for the activated reader objects. will be ignored if overwrite is false. overwrite -- boolean specifying whether or not existing record should be overwritten, if such exists. signal -- optional abortsignal that allows to cancell this write operation. return value a promise that resolves with undefined when and if the message transfer is successfully completed.
exceptions this method doesn't throw true
exceptions; instead, it rejects the returned promise, passing into it a dom
exception whose name is one of the following: aborterror the write operation was aborted with abortsignal passed in options. notallowederror the permission for this operation was rejected or overwrite is false and there are already records on the tag. notsupportederror there is no n...
Navigator.canShare() - Web APIs
the navigator.canshare() method of the web share api returns true if a call to navigator.share() would succeed. syntax var canshare = navigator.canshare(data); parameters data optional an object containing data to share that matches what you would pass to navigator.share(). return value a boolean. true if data can be shared with navigator.share().
exceptions none. examples if(navigator.canshare(data)) { // we can use share() to share the data! woop! } specifications specification status comment web share api - level 2the definition of 'canshare' in that specification. draft initial definition. ...
Navigator.getUserMedia() - Web APIs
shown in the following example: function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here. }; } errorcallback when the call fails, the function specified in the errorcallback is invokedwith a mediastreamerror object as its sole argument; this object is is modeled on dom
exception. see {anch("errors")}} below for a list of the errors which can occur. return value undefined. errors examples width and height here's an example of using getusermedia(), including code to cope with various browsers' prefixes. note that this is the deprecated way of doing it: see the examples section under the mediadevices.getusermedia() for modern examples. navigator.getusermedia = nav...
Navigator.mozIsLocallyAvailable() - Web APIs
syntax navigator.mozislocallyavailable(uri, ifoffline); parameters uri the uri of the resource whose availability is to be checked, as a string. ifoffline allows you to specify whether or not the offline resources cache should be checked; specify true to consider the offline resources cache. ...
Navigator.registerProtocolHandler() - Web APIs
allow this site to handle [scheme] links?” or listing registered handlers in the browser’s settings. note: the title has been removed from the spec due to spoofing concerns, but all current browsers still require it. it is recommended to always set the title, since browsers that support the updated spec most likely will be backwards-compatible and still accept the title (but not use it).
exceptions securityerror the user agent blocked the registration. 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. the browser requires that the handler's u...
Navigator.requestMediaKeySystemAccess() - Web APIs
st element with a satisfiable configuration will be used. return value a promise that, when resolved, delivers a mediakeysystemaccess object to your fulfillment handler function. the fulfillment handler receives as input just one parameter: mediakeysystemaccess a mediakeysystemaccess object representing the media key system configuration described by keysystem and supportedconfigurations
exceptions in case of an error, the returned promise is rejected with a dom
exception whose name indicates what kind of error occurred. notsupportederror either the specified keysystem isn't supported by the platform or the browser, or none of the configurations specified by supportedconfigurations can be satisfied (if, for example, none of the codecs specified in contenttype are available). typeerror...
Node.baseURIObject - Web APIs
t's similar to node.baseuri, except it returns an nsiuri instead of a string. this property exists on all nodes (html, xul, svg, mathml, etc.), but only if the script trying to use it has universalxpconnect privileges. see node.baseuri for details on what the base url is. syntax uriobj = node.baseuriobject value an nsiuri. this property is read-only; attempting to write to it will throw an
exception. in addition, this property may only be accessed from privileged code. specification not in any specification. ...
Node.nodePrincipal - Web APIs
iprincipal object representing current security context of the node. note: this property exists on all nodes (html, svg, mathml, xul, etc.), but only if the script trying to use it has chrome privileges. syntax principalobj = node.nodeprincipal value an nsiprincipal object representing the node's security context. notes this property is read-only; attempting to write to it will throw an
exception. in addition, this property may only be accessed from privileged code. specifications not in any specification. this is a firefox-specific property. ...
Node - Web APIs
d of dom node is represented by an interface based on node. these include attr, characterdata (which text, comment, and cdatasection are all based on), processinginstruction, documenttype, notation, entity, and entityreference. in some cases, a particular feature of the base node interface may not apply to one of its child interfaces; in that case, the inheriting node may return null or throw an
exception, depending on circumstances. for example, attempting to add children to a node type that cannot have children will throw an
exception. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 6...
NodeIterator.nextNode() - Web APIs
eiterator.nextnode() method returns the next node in the set represented by the nodeiterator and advances the position of the iterator within the set. the first call to nextnode() returns the first node in the set. this method returns null when there are no nodes left in the set. in old browsers, as specified in old versions of the specifications, the method may throws the invalid_state_err dom
exception if this method is called after the nodeiterator.detach()method. recent browsers never throw. syntax node = nodeiterator.nextnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterato...
NodeIterator.previousNode() - Web APIs
the nodeiterator.previousnode() method returns the previous node in the set represented by the nodeiterator and moves the position of the iterator backwards within the set. this method returns null when the current node is 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 dom
exception if this method is called after the nodeiterator.detach()method. recent browsers never throw. syntax node = nodeiterator.previousnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns th...
NodeIterator - Web APIs
ere are none. specifications specification status comment domthe definition of 'nodeiterator' in that specification. living standard added the referencenode and pointerbeforereferencenode properties. removed the expandentityreferences property. the method detach() has been changed to be a no-op. the methods previousnode() and nextnode() don't raise an
exception any more. document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator' in that specification. obsolete initial definition. ...
NodeList.item() - Web APIs
a value of null is returned if the index is out of range, and a typeerror is thrown if no argument is provided. syntax nodeitem = nodelist.item(index) nodelist is a nodelist. this is usually obtained from another dom property or method, such as childnodes. index is the index of the node to be fetched. the index is zero-based. nodeitem is the indexth node in the nodelist returned by the item method. ...
OVR_multiview2.framebufferTextureMultiviewOVR() - Web APIs
th and stencil buffer data storage. texture a webgltexture object whose image to attach. level a glint specifying the mipmap level of the texture image to be attached. must be 0. baseviewindex a glint specifying the base view index of the framebuffer object attachment. numviews a glsizei specifying the number of views of the framebuffer object attachment. return value none.
exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer. attachment is not one of the accepted attachment points. a gl.invalid_value error is thrown if level is not 0. if numviews is less than one or more than max_views_ovr. a gl.invalid_operation error is thrown if texture isn't 0 or the name of an existing texture object. examples ext.framebuffer...
OfflineAudioContext.resume() - Web APIs
time in an audio context that has been suspended. the promise resolves immediately because the offlineaudiocontext does not require the audio hardware. if the context is not currently suspended or the rendering has not started, the promise is rejected with invalidstateerror. syntax offlineaudiocontext.resume().then(function() { ... }); parameters none. returns a promise resolving to void.
exceptions the promise is rejected when the following
exception is encountered. invalidstateerror if the context is not currently suspended or the rendering has not started. specifications specification status comment web audio apithe definition of 'resume()' in that specification. working draft initial definition. ...
OfflineAudioContext.suspend() - Web APIs
um boundary. for this reason, it is not allowed to schedule multiple suspends at the same quantized frame. also scheduling should be done while the context is not running to ensure the precise suspension. syntax offlineaudiocontext.suspend(suspendtime).then(function() { ... }); parameters suspendtime a double specifying the suspend time, in seconds. returns a promise resolving to void.
exceptions the promise is rejected when any
exception is encountered. invalidstateerror if the quantized frame number is one of the following: a negative number is less than or equal to the current time is greater than or equal to the total render duration is scheduled by another suspend for the same time specifications specification status comment web audio apithe defini...
OscillatorNode.type - Web APIs
wave. this is the default value. square a square wave with a duty cycle of 0.5; that is, the signal is "high" for half of each period. sawtooth a sawtooth wave. triangle a triangle wave. custom a custom waveform. you never set type to custom manually; instead, use the setperiodicwave() method to provide the data representing the waveform. doing so automatically sets the type to custom.
exceptions invalidstateerror the value custom was specified. to set a custom waveform, just call setperiodicwave(). doing so automatically sets the type for you. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new...
PaintWorklet.registerPaint - Web APIs
the paintworklet.registerpaint() method of the paintworklet interface registers a class programmatically generate an image where a css property expects a file. syntax registerpaint(name, class); parameters name the name of the worklet class to register. class a reference to the class that implements the worklet. return value undefined
exceptions typeerror thrown when one of the arguments is invalid or missing. invalidmodificationerror thrown when the a worklet already exists with the specified name. examples the following shows registering an example worklet module. this should be in a separate js file. note that registerpaint() is called without a reference to paintworklet. the file itself is loaded through css.paintworklet.addmodule() (documented here on the paren...
PannerNode.PannerNode() - Web APIs
d. coneinnerangle: the pannernode.coneinnerangle you want the pannernode to have (the default is 360.) coneouterangle: the pannernode.coneouterangle you want the pannernode to have (the default is 360.) coneoutergain: the pannernode.coneoutergain you want the pannernode to have. the default is 0, and its value can be in the range 0–1. return value a new pannernode object instance.
exceptions rangeerror the refdistance, maxdistance, or rollofffactor properties have been given a value that is outside the accepted range. invalidstateerror the coneoutergain property has been given a value outside the accepted range (0–1). example var ctx = new audiocontext(); var options = { positionx : 1, maxdistance: 5000 } var mypanner = new pannernode(ctx, options); specifications ...
PannerNode.coneOuterGain - Web APIs
e value, describing the amount of volume reduction outside the cone, defined by the coneouterangle attribute. the coneoutergain property's default value is 0, meaning that no sound can be heard outside the cone. syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.coneoutergain = 0; value a double. the default is 0, and its value can be in the range 0–1.
exceptions invalidstateerror the property has been given a value outside the accepted range (0–1). example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume. to help us visualise how the orientation vector affects, we can use the right-hand rule: first, let's start by writing a utility ...
PannerNode.maxDistance - Web APIs
stance between the audio source and the listener, after which the volume is not reduced any further. this value is used only by the linear distance model. the maxdistance property's default value is 10000. syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.maxdistance = 10000; value a double. the default is 10000, and non-positive values are not allowed.
exceptions rangeerror the property has been given a value that is outside the accepted range. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the positi...
PannerNode.refDistance - Web APIs
rce moves further from the listener – i.e. the distance at which the volume reduction starts taking effect. this value is used by all distance models. the refdistance property's default value is 1. syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.refdistance = 1; value a non-negative number. if the value is set to less than 0, a rangeerror is thrown.
exceptions rangeerror the property has been given a value that is outside the accepted range. example this example demonstrates how different values of refdistance affect how the volume of a sound decays as it moves away from the listener. unlike rollofffactor, changing this value also delays the volume decay until the sound moves past the reference point. const context = new audiocontext(); // all...
PannerNode.rolloffFactor - Web APIs
offfactor property's default value is 1. syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.rollofffactor = 1; value a number whose range depends on the distancemodel of the panner as follows (negative values are not allowed): "linear" the range is 0 to 1. "inverse" the range is 0 to infinity. "exponential" the range is 0 to infinity.
exceptions rangeerror the property has been given a value that is outside the accepted range. example this example demonstrates how different rollofffactor values affect how the volume of the test tone decreases with increasing distance from the listener: const context = new audiocontext(); // all our test tones will last this many seconds const note_length = 4; // this is how far we'll move the so...
ParentNode.append() - Web APIs
epts node objects. parentnode.append() has no return value, whereas node.appendchild() returns the appended node object. parentnode.append() can append several nodes and strings, whereas node.appendchild() can only append one node. syntax // [throws, unscopable] parentnode.append(...nodesordomstrings) // returns undefined parameters nodes a set of node or domstring objects to insert.
exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. examples appending an element let parent = document.createelement("div") let p = document.createelement("p") parent.append(p) console.log(parent.childnodes) // nodelist [ <p> ] appending text let parent = document.createelement("div") parent.append("some text") console.log(parent.textcontent) // "...
ParentNode.prepend() - Web APIs
before the first child of the parentnode. domstring objects are inserted as equivalent text nodes. syntax parentnode.prepend(...nodestoprepend); parameters nodestoprepend one or more nodes to insert before the first child node currently in the parentnode. each node can be specified as either a node object or as a string; strings are inserted as new text nodes. return value undefined.
exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. examples prepending an element var parent = document.createelement("div"); var p = document.createelement("p"); var span = document.createelement("span"); parent.append(p); parent.prepend(span); console.log(parent.childnodes); // nodelist [ <span>, <p> ] prepending text var parent = document.create...
ParentNode.replaceChildren() - Web APIs
de with a specified new set of children. these can be domstring or node objects. syntax // [throws, unscopable] parentnode.replacechildren(...nodesordomstrings) // returns undefined parameters nodesordomstrings a set of node or domstring objects to replace the parentnode's existing children with. if no replacement objects are specified, then the parentnode is emptied of all child nodes.
exceptions hierarchyrequesterror: the constraints of the node tree are violated. examples emptying a node replacechildren() provides a very convenient mechanism for emptying a node of all its children. 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 par...
PaymentRequest.canMakePayment() - Web APIs
canpay = await paymentrequest.canmakepayment(); returns a promise to a boolean that resolves to true if the user agent supports any of the payment methods supplied when instantiating the request using the paymentrequest constructor. if the payment can't be processed, the promise receives a value of false. note: if you call this too often, the browser may reject the returned promise with a dom
exception. parameters none examples in the following example, is excerpted from a demo that asynchronously builds a paymentrequest object for both apple pay and credit cards. it wraps the call to canmakepayment() in feature detection, and calls an appropriate callback depending on the resolution of the promise. async function initpaymentrquest() { const details = { total: { label: "total...
PaymentResponse.complete() - Web APIs
. note: in older versions of the specification, an empty string, "", was used instead of unknown to indicate a completion without a known result state. see the browser compatibility section below for details. return value a promise which resolves with no input value once the payment interface has been fully closed. if an error occurs, the promise instead rejects, returning one of the
exceptions listed below.
exceptions aborterror the document in which the payment request is taking place became inactive while the user interface was shown. invalidstateerror the payment has already completed, or complete() was called while a request to retry the payment is pending. you can't treat a payment as complete after requesting that the payment be tried again. examples the following exam...
PerformanceServerTiming.toJSON - Web APIs
the tojson() method of the performanceservertiming interface returns a domstring that is the json representation of the performanceservertiming object. syntax var json = performanceservertiming.tojson() parameters none. return value a domstring containing json.
exceptions none. specifications specification status comment server timingthe definition of 'tojson' in that specification. working draft initial definition. ...
Permissions.query() - Web APIs
push have been merged. if permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push. note: the persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the storage api. returns a promise that resolves to a permissionstatus object.
exceptions
exception explanation typeerror retrieving the permissiondescriptor information failed in some way, or the permission doesn't exist or is currently unsupported (e.g. midi, or push with uservisibleonly). example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { showlocalnewswithgeolocation(); } else...
Permissions.revoke() - Web APIs
user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push. note: the persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the storage api. returns a promise that calls its fulfillment handler with a permissionstatus object indicating the result of the request.
exceptions typeerror retrieving the permissiondescriptor information failed in some way, or the permission doesn't exist or is currently unsupported (e.g. midi, or push with uservisibleonly). example this function can be used by an app to request that its own geolocation api permission be revoked. function revokepermission() { navigator.permissions.revoke({name:'geolocation'}).then(function(resul...
Using the Permissions API - Web APIs
, then we can't get back to the permission prompt without using the browser menu options: firefox: tools > page info > permissions > access your location. select always ask. chrome: hamburger menu > settings > show advanced settings. in the privacy section, click content settings. in the resulting dialog, find the location section and select ask when a site tries to... . finally, click manage
exceptions and remove the permissions you granted to the sites you are interested in. however, future additions to browser functionality should provide the request() method, which will allow us to programatically request permissions, any time we like. these should hopefully be available soon. ...
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
ticator 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 specifically bound to the client device (cannot be removed). if the authenticator already contains one of such a public key credential, the client will throw a dom
exception or asks the user if they want to create a new credential. examples var publickey = { excludecredentials: [ { type: "public-key", // the id for john.doe@example.com id : new uint8array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for john-doe@example.com id : new uint8array(26) /* another id */ } ], c...
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
ticator 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 specifically bound to the client device (cannot be removed). if the authenticator does not contain any of these public key credentials, the client will throw a dom
exception "notallowederror". examples var options = { allowcredentials: [ { transports: ["usb"], type: "public-key", id: new uint8array(26) // actually provided by the server }, { transports: ["internal"], type: "public-key", id: new uint8array(26) // actually provided by the server } ], challenge: new uint8array([/* bytes sent from the server */]...
RTCDTMFSender.insertDTMF() - Web APIs
time, in milliseconds, that each dtmf tone should last. this value must be between 40 ms and 6000 ms (6 seconds), inclusive. the default is 100 ms. intertonegap optional the length of time, in milliseconds, to wait between tones. the browser will enforce a minimum value of 30 ms (that is, if you specify a lower value, 30 ms will be used instead); the default is 70 ms. return value undefined
exceptions invalidstateerror the dtmf tones couldn't be sent because the track has been stopped, or is in a read-only or inactive state. invalidcharactererror one or more of the characters in tones is not valid dtmf. example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtmfsender.insertdtmf()' in...
RTCDTMFSender.toneBuffer - Web APIs
the pound/hash sign ("#") and the asterisk ("*") these correspond to the similarly-labeled keys which are typically on the bottom row of the telephone keypad. the comma (",") this character instructs the dialing process to pause for two seconds before sending the next character in the buffer. all other characters are unrecognized and will cause insertdtmf() to throw an invalidcharactererror
exception. using tone buffer strings for example, if you're writing code to control a voicemail system by sending dtmf codes, you might use a string such as "*,1,5555". in this example, we would send "*" to request access to the vm system, then, after a pause, send a "1" to start playback of voicemail messages, then after a pause, dial "5555" as a pin number to open the messages. settting the tone buff...
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
the pound/hash sign ("#") and the asterisk ("*") these correspond to the similarly-labeled keys which are typically on the bottom row of the telephone keypad. the comma (",") this character instructs the dialing process to pause for two seconds before sending the next character in the buffer. all other characters are unrecognized and will cause insertdtmf() to throw an invalidcharactererror
exception. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtmftonechangeevent()' in that specification. candidate recommendation initial definition. ...
RTCDataChannel: error event - Web APIs
the error's name is rtcerror and the message is an error string specified by the webrtc layer. error information is output to the console using console.error(). the message string is always output, as is information about the source file's name, line number, and column number at which the error occurred. in addition, however, depending on the value of errordetail, additional informat...
RTCDataChannel.send() - Web APIs
ose that do have various additional restrictions. this will get less complicated over time, but for now, if you have questions, see understanding message size limits in using webrtc data channels. syntax rtcdatachannel.send(data); parameters data the data to transmit across the connection. this may be a usvstring, a blob, an arraybuffer, or an arraybufferview. return value undefined.
exceptions invalidstateerror since the data channel uses a separate transport channel from the media content, it must establish its own connection; if it hasn't finished doing so (that is, its readystate is "connecting"), this error occurs without sending or buffering the data. networkerror the specified data would need to be buffered, and there isn't room for it in the buffer. in this scenario, the ...
RTCError - Web APIs
the rtcerror interface describes an error which has occurred while handling webrtc operations. it's based upon the standard dom
exception interface that describes general dom errors. constructor rtcerror() creates and returns a new rtcerror object initialized with the properties of the provided rtcerrorinit dictionary and, optionally, a string to use as the value of the error's message property. properties in addition to the properties defined by the parent interface, dom
exception, rtcerror includes the following properties: errordetail read only a domstring specifying the webrtc-specific error code identifying the type of error that occurred. receivedalert read only an unsigned long integer value indicating the fatal dtls error which was received from the network. only valid if th...
RTCErrorEvent.error - Web APIs
the read-only rtcerrorevent property error contains an rtcerror object describing the details of the error which the event is announcing. syntax let errorinfo = rtcerrorevent.error; value an rtcerror object whose properties provide details about the error which has occurred in the context of a webrtc operation. since rtcerror is based upon dom
exception, it includes those properties. additional properties defined by rtcerror are: errordetail read only a domstring specifying the webrtc-specific error code identifying the type of error that occurred. receivedalert read only an unsigned long integer value indicating the fatal dtls error which was received from the network. only valid if the errordetail string is dtls-failure. if null, no dtls error was received. sctpcausecode read only ...
RTCIceCandidate.address - Web APIs
in the options object, but the address is automatically extracted from the candidate a-line, if it's formatted properly. syntax var address = rtcicecandidate.address; value a domstring providing the ip address from which the candidate comes. note: if port is null — and port is supported by the user agent — passing the candidate to addicecandidate() will fail, throwing an operationerror
exception. security notes it's important to note here that although webrtc does not require the two peers on an rtcpeerconnection to know one another's true ip addresses, the address property on rtcicecandidate can expose more information about the source of the remote peer than the user expects. the ip address can be used to derive information about the remote device's location, network topology, and s...
RTCIceCandidate.foundation - Web APIs
d to correlate candidates that are present on multiple rtcicetransport objects syntax var foundation = rtcicecandidate.foundation; value a domstring which uniquely identifies the candidate across all rtcicetransports on which it is available. note: if port is null — and port is supported by the user agent — passing the candidate to addicecandidate() will fail, throwing an operationerror
exception. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the field "4234997325" is the foundation. example this code snippet uses the foundation of two candidates to determine if they're actually the same candidate. if (candidate1.foundation == candidate2.foundation) { /* the two candida...
RTCIceCandidate.port - Web APIs
ort = rtcicecandidate.port; value a 16-bit number indicating the port number on the device at the address indicated by ip at which the candidate's peer can be reached. port is initialized to null if it is not specified in the candidate, or if the candidate string can't be parsed propertly. note: if port is null, passing the candidate to addicecandidate() will fail, throwing an operationerror
exception. this applies only if the candidate implements port. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the port number is found in the sixth field, which is "44323". in this case, the value of port will be 44323. example this code snippet fetches the ip address and port number of the c...
RTCIceCandidate.priority - Web APIs
icating the priority of the candidate according to the remote peer. the larger this value is, the more preferable the remote peer considers this candidate to be. priority is initialized to null if it is not specified in the candidate, or if the candidate string can't be parsed propertly. note: if priority is null, passing the candidate to addicecandidate() will fail, throwing an operationerror
exception. this applies only if the candidate implements the priority property. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the priority is the number after the protocol, so it's the fourth field in the candidate string. in this example, the priority is 2043278322. example this candidate e...
RTCIceCandidate.sdpMLineIndex - Web APIs
dpmlineindex = rtcicecandidate.sdpmlineindex; value a number containing a 0-based index into the set of m-lines providing media descriptions, indicating which media source is associated with the candidate, or null if no such association is available. note: attempting to add a candidate (using addicecandidate()) that has a value of null for either sdpmid or sdpmlineindex will throw a typeerror
exception. example ... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.sdpmlineindex' in that specification. candidate recommendation initial definition. ...
RTCIceCandidate.sdpMid - Web APIs
the specified candidate m-line string. syntax var sdpmid = rtcicecandidate.sdpmid; value a domstring which uniquely identifies the source media component from which the candidate draws data, or null if no such association exists for the candidate. note: attempting to add a candidate (using addicecandidate()) that has a value of null for either sdpmid or sdpmlineindex will throw a typeerror
exception. example ... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.sdpmid' in that specification. candidate recommendation initial definition. ...
RTCIceCandidate.type - Web APIs
un server to represent the candidate's peer anonymously. relay the candidate is a relay candidate, obtained from a turn server. the relay candidate's ip address is an address the turn server uses to forward the media between the two peers. if type is null, that information was missing from the candidate's a-line, which will cause rtcpeerconnection.addicecandidate() to throw an operationerror
exception. example in this example, the candidate's type is used to present a modified user interface for host candidates (those where the ip refers directly to the remote peer, rather than an intermediary). if (candidate.type == "host") { showhostcontrols(); } else { hidehostcontrols(); } specifications specification status comment webrtc 1.0: real-time communication betw...
RTCIceCandidateInit.sdpMLineIndex - Web APIs
icecandidate object's sdpmlineindex property. value a number containing a 0-based index into the set of m-lines providing media descriptions, indicating which media source is associated with the candidate, or null if no such association is available. note: attempting to add a candidate (using addicecandidate()) that has a value of null for either sdpmid or sdpmlineindex will throw a typeerror
exception. example ... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidateinit.sdpmlineindex' in that specification. candidate recommendation initial specification. ...
RTCIceCandidateInit.sdpMid - Web APIs
einit dictionary specifies the value of the rtcicecandidate object's sdpmid property. value a domstring which uniquely identifies the source media component from which the candidate draws data, or null if no such association exists for the candidate. note: attempting to add a candidate (using addicecandidate()) that has a value of null for either sdpmid or sdpmlineindex will throw a typeerror
exception. example ... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidateinit.sdpmid' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.addStream() - Web APIs
ld update your code to instead use the addtrack() method: navigator.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); stream.gettracks().foreach(function(track) { pc.addtrack(track, stream); }); }); the newer addtrack() api avoids confusion over whether later changes to the track-makeup of a stream affects a peer connection (they do not). the
exception is in chrome, where addstream() does make the peer connection sensitive to later stream changes (though such changes do not fire the negotiationneeded event). if you are relying on the chrome behavior, note that other browsers do not have it. you can write web compatible code using feature detection instead: // add a track to a stream and the peer connection said stream was added to: stream.add...
RTCPeerConnection.addTrack() - Web APIs
tion will be on the same stream on the remote end. return value the rtcrtpsender object which will be used to transmit the media data. note: every rtcrtpsender is paired with an rtcrtpreceiver to make up an rtcrtptransceiver. the associated receiver is muted (indicating that it is not able to deliver packets) until and unless one or more streams are added to the receiver by the remote peer.
exceptions invalidaccesserror the specified track (or all of its underlying streams) is already part of the rtcpeerconnection. invalidstateerror the rtcpeerconnection is closed. usage notes adding tracks to multiple streams after the track parameter, you can optionally specify one or more mediastream objects to add the track to. only tracks are sent from one peer to another, not streams. since st...
RTCPeerConnection.addTransceiver() - Web APIs
transceiver.direction property. sendencodings optional a list of encodings to allow when sending rtp media from the rtcrtpsender. each entry is of type rtcrtpencodingparameters. streams optional a list of mediastream objects to add to the transceiver'srtcrtpreceiver; when the remote peer's rtcpeerconnection's track event occurs, these are the streams that will be specified by that event.
exceptions typeerror a string was specified as trackorkind which is not valid. the string must be either "audio" or "video". specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.addtransceiver()' in that specification. candidate recommendation ...
RTCPeerConnection.createAnswer() - Web APIs
o use the promise-based version of createanswer() instead. the parameters for this form of createanswer() are described below, to aid in updating existing code. successcallback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription object describing the newly-created answer. failurecallback an rtcpeerconnectionerrorcallback which will be passed a single dom
exception object explaining why the request to create an answer failed. options optional an optional rtcofferoptions object providing options requested for the answer.
exceptions notreadableerror the identity provider wasn't able to provide an identity assertion. operationerror generation of the sdp failed for some reason; this is a general failure catch-all
exception. return value a promise w...
RTCPeerConnection.createDataChannel() - Web APIs
will select an id for you. the options which can be configured using the rtcdatachannelinit dictionary represent the script-settable subset of the properties on the rtcdatachannel interface. return value a new rtcdatachannel object with the specified label, configured using the options specified by options if that parameter is included; otherwise, the defaults listed above are established.
exceptions invalidstateerror the rtcpeerconnection is closed. typeerror this can happen in a couple of situations: the label and/or protocol string is too long; these cannot be longer than 65,535 bytes (bytes, rather than characters). the id is 65535. while this is a valid unsigned 16-bit value, it's not a permitted value for id. syntaxerror values were specified for both the maxpacketlif...
RTCPeerConnection.removeTrack() - Web APIs
le"), it is marked as needing to be negotiated again; the remote peer won't experience the change until this negotiation occurs. a negotiationneeded event is sent to the rtcpeerconnection to let the local end know this negotiation must occur. syntax pc.removetrack(sender); parameters mediatrack a rtcrtpsender specifying the sender to remove from the connection. return value undefined.
exceptions invalidstateerror the connection is not open. example this example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button. var pc, sender; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerconnection(); var track = stream.getvideotracks()[0]; sender = pc.addtrack(track, stream); }); ...
RTCPeerConnection.setConfiguration() - Web APIs
to new regional ice servers, then initiate an ice restart. you cannot change the identity information for a connection once it's already been set. syntax rtcpeerconnection.setconfiguration(configuration); parameters configuration an rtcconfiguration object which provides the options to be set. the changes are not additive; instead, the new values completely replace the existing ones.
exceptions invalidaccesserror one or more of the urls specified in configuration.iceservers is a turn server, but complete login information is not provided (that is, either the rtciceserver.username or rtciceserver.credentials is missing). this prevents successful login to the server. invalidmodificationerror the configuration includes changed identity information, but the connection already has ide...
RTCRtpEncodingParameters.scaleResolutionDownBy - Web APIs
video will be encoded at its original size. a value of 2.0 would reduce the size of the video by a factor of 2 both horizontally and vertically, resulting in a video 25% the original size. a value less than 1.0 would cause the video to get larger rather than smaller, which is not the intent of this property. therefore, specifying a value less than 1.0 is not permitted and will cause a rangeerror
exception to be thrown by rtcpeerconnection.addtransceiver() or rtcrtpsender.setparameters(). specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpencodingparameters.scaleresolutiondownby' in that specification. candidate recommendation initial definition. ...
RTCRtpSender.replaceTrack() - Web APIs
jected if the track cannot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see things that require negotiation). if newtrack was omitted or was null, replacetrack() simply stops the sender. no negotiation is required in this case. when the promise is fulfilled, the fulfillment handler receives a value of undefined.
exceptions if the returned promise is rejected, one of the following
exceptions is provided to the rejection handler: invalidmodificationerror replacing the rtcrtpsender's current track with the new one would require negotiation. invalidstateerror the track on which this method was called is stopped rather than running. typeerror the new track's kind doesn't match the original track. usage notes...
RTCRtpSender.setParameters() - Web APIs
es the encoding's priority. the default value is low. 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(). return value a promise that resolves when the rtcrtpsender.track property is updated with the given parameters.
exceptions if an error occurs, the returned promise is rejected with the appropriate
exception from the list below. invalidmodificationerror one of the following problems was detected: the number of encodings specified in the parameters object's encodings property does not match the number of encodings currently listed for the rtcrtpsender. you cannot change the number of encoding options once the...
RTCRtpSender.setStreams() - Web APIs
jects. syntax rtcrtpsender.setstreams(mediastream); rtcrtpsender.setstreams([mediastream...]); parameters mediastream or [mediastream...] optional an mediastream object—or an array of multiple mediastream objects—identifying the streams to which the rtcrtpsender's track belongs. if this parameter isn't specified, no new streams will be associated with the track. return value none.
exceptions invalidstateerror the sender's connection is closed. description setstreams() is purely additive. it doesn't remove the track from any streams; it simply adds it to new ones. if you specify streams to which the track already belongs, that stream is unaffected. once the track has been added to all of the streams, renegotiation of the connection will be triggered by the negotiationneeded e...
RTCRtpTransceiver.direction - Web APIs
ot offer to send rtp data, and will not do so. does not offer to receive rtp data and will not do so. [1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding.
exceptions when setting the value of direction, the following
exceptions can occur: invalidstateerror either the receiver's rtcpeerconnection is closed or the rtcrtpreceiver is stopped. usage notes setting the direction when you change the value of direction, an invalidstateerror
exception will occur if the connection is closed or the receiver is stopped. if the new value of direction is in fact ...
RTCRtpTransceiver.stop() - Web APIs
recently, the stopped property was provided to return true if the connection is stopped. that property has been deprecated and will be removed at some point. instead, check the value of currentdirection. if it's stopped, the transceiver has been stopped. this method does nothing if the transceiver is already stopped. syntax rtcrtptransceiver.stop() paramters none. return value undefined
exceptions invalidstateerror the rtcpeerconnection of which the transceiver is a member is closed. 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. the receiver then stops receiving media; the receiver's track is stopped, and the transceiver's direction is changed to stopped, and renegot...
Range.compareBoundaryPoints() - Web APIs
d boundary-point of range. range.end_to_start compares the end boundary-point of sourcerange to the start boundary-point of range. range.start_to_end compares the start boundary-point of sourcerange to the end boundary-point of range. range.start_to_start compares the start boundary-point of sourcerange to the start boundary-point of range. if the value of the parameter is invalid, a dom
exception with a notsupportederror code is thrown. sourcerange a range to compare boundary points with the range. example var range, sourcerange, compare; range = document.createrange(); range.selectnode(document.getelementsbytagname("div")[0]); sourcerange = document.createrange(); sourcerange.selectnode(document.getelementsbytagname("div")[1]); compare = range.compareboundarypoints(range.start_to...
Range.setEnd() - Web APIs
ument) than the start point will result in a collapsed range with the start and end points both set to the specified end position. syntax range.setend(endnode, endoffset); parameters endnode the node inside which the range should end. endoffset an integer greater than or equal to zero representing the offset for the end of the range from the start of endnode. return value undefined.
exceptions
exceptions are thrown as dom
exception objects of the following types: invalidnodetypeerror the node specified by endnode is a doctype node; range endpoints cannot be located inside a doctype node. indexsizeerror the value specified by endoffset is either greater than or equal to the length of the node or is less than zero. usage notes if the endnode is a node of type text, comment, or ...
Range.surroundContents() - Web APIs
the range.surroundcontents() method moves content of the range into a new node, placing the new node at the start of the specified range. this method is nearly equivalent to newnode.appendchild(range.extractcontents()); range.insertnode(newnode). after surrounding, the boundary points of the range include newnode. an
exception will be thrown, however, if the range splits a non-text node with only one of its boundary points. that is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail. syntax range.surroundcontents(newparent); parameters newparent a node with which to surround the contents. example html <span class="header-text">put this in a headline</span> javascript const range = document.createrange(); ...
Range - Web APIs
) for all the elements in the range. range.intersectsnode() returns a boolean indicating whether the given node intersects the range. range.ispointinrange() returns a boolean indicating whether the given point is in the range. specifications specification status comment domthe definition of 'range' in that specification. living standard do not use range
exception anymore, use dom
exception instead. made the second parameter of collapse() optional. added the methods ispointinrange(), comparepoint(), and intersectsnode(). added the constructor range(). dom parsing and serializationthe definition of 'extensions to range' in that specification. working draft added the method createcontextualfragment(). css object model (csso...
ReadableByteStreamController.close() - Web APIs
the close() method of the readablebytestreamcontroller interface closes the associated stream. note: readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. syntax readablebytestreamcontroller.close(); parameters none. return value undefined.
exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream is not readable for some other reason. examples tbd. specifications specification status comment streamsthe definition of 'close()' in that specification. living standard initial definition. ...
ReadableByteStreamController.enqueue() - Web APIs
the enqueue() method of the readablebytestreamcontroller interface enqueues a given chunk in the associated stream. syntax readablebytestreamcontroller.enqueue(chunk); parameters chunk the chunk to enqueue. return value undefined.
exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existant or detached. examples tbd. specifications specification status comment streamsthe definition of 'enqueue()' in that specification. living standard initial definition. ...
ReadableByteStreamController.error() - Web APIs
the error() method of the readablebytestreamcontroller interface causes any future interactions with the associated stream to error. syntax readablebytestreamcontroller.error(e); parameters e the error you want future interactions to fail with. return value undefined.
exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream is not readable for some other reason. examples tbd. specifications specification status comment streamsthe definition of 'error()' in that specification. living standard initial definition. ...
ReadableStream.ReadableStream() - Web APIs
— this indicates the size to use for each chunk, in bytes. note: you could define your own custom queuingstrategy, or use an instance of bytelengthqueuingstrategy or countqueuingstrategy for this object value. if no queuingstrategy is supplied, the default used is the same as a countqueuingstrategy with a high water mark of 1. return value an instance of the readablestream object.
exceptions rangeerror the supplied type value is neither "bytes" nor undefined. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() fuction is also provided to stop the generation if read...
ReadableStream.cancel() - Web APIs
led, and the stream is not readable any more. to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close(). syntax var promise = readablestream.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter.
exceptions typeerror the stream you are trying to cancel is not a readablestream, or it is locked. examples in jake archibald's cancelling a fetch example, a stream is used to fetch the whatwg html spec chunk by chunk; each chunk is searched for the string "service workers". when the search terms is found, cancel() is used to cancel the stream — the job is finished so it is no longer needed. var ...
ReadableStream.getReader() - Web APIs
er being created that can read readable byte streams (i.e. can handle "bring your own buffer" reading). undefined (or not specified at all — this is the default), which results in a readablestreamdefaultreader being created that can read individual chunks from a stream. return value a readablestreamdefaultreader or readablestreambyobreader object instance, depending on the mode value.
exceptions rangeerror the provided mode value is not "byob" or undefined. typeerror the stream you are trying to create a reader for is not a readablestream. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentia...
ReadableStream.pipeThrough() - Web APIs
le stream will no longer be canceled. in this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. return value the readable side of the transformstream.
exceptions typeerror the writable and/or readable property of transformstream are undefined. examples in the following example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream. next, we log the contents of the readable stream, use pipethrough() to send it to a new function that cr...
ReadableStream.pipeTo() - Web APIs
ger be canceled. in this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. return value a promise that resolves when the piping process has completed.
exceptions typeerror the writablestream and/or readablestream objects are not a writable stream/readable stream, or one or both of the streams are locked. examples // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(body => body.pipethrough(new pngtransformstream())) .then(rs => rs.pipeto(new finaldestinationstream())) spec...
ReadableStream.tee() - Web APIs
e. since a response body cannot be consumed more than once, you’d need two copies to do this. to cancel the stream you then need to cancel both resulting branches. teeing a stream will generally lock it for the duration, preventing other readers from locking it. syntax var teedstreams = readablestream.tee(); parameters none. return value an array containing two readablestream instances.
exceptions typeerror the source stream is not a readablestream. examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui. see simple tee example for the full cod...
ReadableStreamBYOBReader.ReadableStreamBYOBReader() - Web APIs
) constructor creates and returns a readablestreambyobreader object instance. note: you generally wouldn't use this constructor manually; instead, you'd use the readablestream.getreader() method. syntax var readablestreambyobreader = new readablestreambyobreader(stream); parameters stream the readablestream to be read. return value an instance of the readablestreambyobreader object.
exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader, or its stream controller is not a readablebytestreamcontroller. examples tbd specifications specification status comment streamsthe definition of 'readablestreambyobreader()' in that specification. living standard initial definition. ...
ReadableStreamBYOBReader.cancel() - Web APIs
may or may not use it. note: if the reader is active, the cancel() method behaves the same as that for the associated stream (readablestream.cancel()). syntax var promise = readablestreambyobreader.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter.
exceptions typeerror the source object is not a readablestreambyobreader, or the stream has no owner. examples tbd. specifications specification status comment streamsthe definition of 'cancel()' in that specification. living standard initial definition. ...
ReadableStreamBYOBReader.read() - Web APIs
n the state of the stream. the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes errored, the promise will be rejected with the relevant error.
exceptions typeerror the source object is not a readablestreambyobreader, the stream has no owner, the view is not an object or has become detached, or the view's length is 0. examples tbd. specifications specification status comment streamsthe definition of 'read()' in that specification. living standard initial definition. ...
ReadableStreamBYOBReader.releaseLock() - Web APIs
d in that same way subsequently; otherwise, the reader will appear closed. a reader’s lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader’s readablestreambyobreader.read() method has not finished. this will result in a typeerror being thrown. syntax readablestreambyobreader.releaselock(); parameters none. return value undefined.
exceptions typeerror the source object is not a readablestreambyobreader, or a read request is pending. examples tbd. specifications specification status comment streamsthe definition of 'releaselock()' in that specification. living standard initial definition. ...
ReadableStreamBYOBRequest.respond() - Web APIs
the error() method of the readablestreambyobrequest interface xxx syntax readablestreambyobrequestinstance.respond(byteswritten); parameters byteswritten xxx return value void.
exceptions typeerror the source object is not a readablestreambyobrequest, or there is no associated controller, or the associated internal array buffer is detached. examples tbd. specifications specification status comment streamsthe definition of 'respond()' in that specification. living standard initial definition. ...
ReadableStreamBYOBRequest.respondWithNewView() - Web APIs
the respondwithnewview() method of the readablestreambyobrequest interface xxx syntax readablestreambyobrequestinstance.respondwithnewview(view); parameters view xxx return value void.
exceptions typeerror the source object is not a readablestreambyobrequest, or there is no associated controller, or the associated internal array buffer is non-existant or detached. examples tbd. specifications specification status comment streamsthe definition of 'respondwithnewview()' in that specification. living standard initial definition. ...
ReadableStreamDefaultController.close() - Web APIs
ream. readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. if you want to completely get rid of the stream and discard any enqueued chunks, you'd use readablestream.cancel() or readablestreamdefaultreader.cancel(). syntax readablestreamdefaultcontroller.close(); parameters none. return value undefined.
exceptions typeerror the source object is not a readablestreamdefaultcontroller. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() function is also provided to stop the generation if re...
ReadableStreamDefaultController.error() - Web APIs
the error() method of the readablestreamdefaultcontroller interface causes any future interactions with the associated stream to error. note: the error() method can be called more than once, and can be called when the stream is not readable. syntax readablestreamdefaultcontroller.error(e); parameters e the error you want future interactions to fail with. return value undefined.
exceptions typeerror the source object is not a readablestreamdefaultcontroller, or the stream is not readable for some other reason. examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using readablestreamdefaultcontroller.desiredsize to manually detect when the stream is full and apply backpressure, and also of using err...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
r creates and returns a readablestreamdefaultreader object instance. note: you generally wouldn't use this constructor manually; instead, you'd use the readablestream.getreader() method. syntax var readablestreamdefaultreader = new readablestreamdefaultreader(stream); parameters stream the readablestream to be read. return value an instance of the readablestreamdefaultreader object.
exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, unt...
ReadableStreamDefaultReader.cancel() - Web APIs
ller.close(). note: if the reader is active, the cancel() method behaves the same as that for the associated stream (readablestream.cancel()). syntax var promise = readablestreamdefaultreader.cancel(reason); parameters reason optional a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter.
exceptions typeerror the source object is not a readablestreamdefaultreader, or the stream has no owner. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (this code is based on our simple random stream example). each chunk is read sequentially and output to the ui, until the stream has finished...
ReadableStreamDefaultReader.read() - Web APIs
n the state of the stream. the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes errored, the promise will be rejected with the relevant error.
exceptions typeerror the source object is not a readablestreamdefaultreader, or the stream has no owner. examples example 1 - simple example this example shows the basic api usage, but doesn't try to deal with complications like stream chunks not ending on line boundaries for example. in this example stream is a previously-created custom readablestream. it is read using a readablestreamdefaultread...
ReadableStreamDefaultReader.releaseLock() - Web APIs
hat same way subsequently; otherwise, the reader will appear closed. a reader’s lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader’s readablestreamdefaultreader.read() method has not finished. this will result in a typeerror being thrown. syntax readablestreamdefaultreader.releaselock(); parameters none. return value undefined.
exceptions typeerror the source object is not a readablestreamdefaultreader, or a read request is pending. examples function fetchstream() { const reader = stream.getreader(); ... reader.releaselock() ... } specifications specification status comment streamsthe definition of 'releaselock()' in that specification. living standard initial definition. ...
Request() - Web APIs
tes a new request object. syntax var myrequest = new request(input[, init]); parameters input defines the resource that you wish to fetch. this can either be: a usvstring containing the direct url of the resource you want to fetch. a request object, effectively creating a copy. 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. if this object has a request.mode of navigate, the mode value is converted to same-origin. init optional an options object containing any custom settings that you want to apply to the request. the possible options are: method: the request method, e.g., get, post. t...
ResizeObserver.disconnect() - Web APIs
the disconnect() method of the resizeobserver interface unobserves all observed element or svgelement targets. syntax resizeobserver.disconnect(); parameters none. return value void.
exceptions none. examples btn.addeventlistener('click', () => { resizeobserver.disconnect(); }) specifications specification status comment resize observerthe definition of 'disconnect()' in that specification. editor's draft initial definition. ...
ResizeObserver.observe() - Web APIs
get, options); parameters target a reference to an element or svgelement to be observed. options optional an options object allowing you to set options for the observation. currently this only has one possible option that can be set: box sets which box model the observer will observe changes to. possible values are content-box (the default), and border-box. return value void.
exceptions none. examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem...
ResizeObserver.unobserve() - Web APIs
the unobserve() method of the resizeobserver interface ends the observing of a specified element or svgelement. syntax void unobserve(target); parameters target a reference to an element or svgelement to be unobserved. return value void.
exceptions none. examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.conte...
Response.redirect() - Web APIs
ling service worker could intercept a page's request and redirect it as desired. this will actually lead to a real redirect if a service worker sends it upstream. syntax var response = response.redirect(url, status); parameters url the url that the new response is to originate from. status optional an optional status code for the response (e.g., 302.) return value a response object.
exceptions
exception explanation rangeerror the specified status is not a redirect status. typeerror the specified url is invalid. example responseobj.redirect('https://www.example.com', 302); specifications specification status comment fetchthe definition of 'redirect()' in that specification. living standard ...
SVGAnimatedString.baseVal - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition) recommendation scalable vector graphics (svg) 2 candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. ...
SVGAnimatedString - Web APIs
value. if the given attribute or property is being animated it contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, it contains the same value as baseval. svganimatedstring.baseval this is a domstring representing the base value. the base value of the given attribute before applying any animations. setter throws dom
exception. methods the svganimatedstring interface do not provide any specific methods. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition) recommendation scalable vector graphics (svg) 2 candidate recommendation browser compatibility the compatibility table on this page is generated from structured data...
SVGImageElement.decode - Web APIs
the decode() method of the svgimageelement interface initiates asynchronous decoding of an image, returning a promise that resolves once the image data is ready for use. syntax var promise = svgimageelement.decode(); parameters none. return value a promise which resolves once the image data is ready to be used, such as by appending it to the dom, replacing an existing image, and so forth.
exceptions none. specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation initial definition. html living standardthe definition of 'decode()' in that specification. living standard ...
SVGRect - Web APIs
the svgrect represents a rectangle. rectangles consist of an x and y coordinate pair identifying a minimum x value, a minimum y value, and a width and height, which are constrained to be non-negative. an svgrect object can be designated as read only, which means that attempts to modify the object will result in an
exception being thrown. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/svgrect" target="_top"><rect x="1" y="1" width="75" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="38.
SVGScriptElement - Web APIs
th="2px" /><text x="401" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgscriptelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties svgscriptelement.type read only a domstring corresponding to the type attribute of the given <script> element. a dom
exception is raised with the code no_modification_allowed_err on an attempt to change the value of a read only attribut. svgscriptelement.crossorigin read only a domstring corresponding to the crossorigin attribute of the given <script> element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specific...
Selection.setBaseAndExtent() - Web APIs
and so on. note: if the focus position appears before the anchor position in the document, the direction of the selection is reversed — the caret is placed at the beginning of the text rather the end, which matters for any keyboard command that might follow. for example, shift + ➡︎ would cause the selection to narrow from the beginning rather than grow at the end. return value void.
exceptions if anchoroffset is larger than the number of child nodes inside anchornode, or if focusoffset is larger than the number of child nodes inside focusnode, an indexsizeerror
exception is thrown. examples in this example, we have two paragraphs containing spans, each one containing a single word. the first one is set as the anchornode and the second is set as the focusnode. we also have an additi...
SensorErrorEvent.SensorErrorEvent() - Web APIs
the sensorerrorevent constructor creates a new sensorerrorevent object which provides information about errors thrown by any of the interfaces based on sensor. syntax sensorerrorevent = new sensorerrorevent(type, {error: dom
exception}); parameters type will always be 'sensorerrorevent'. options optional currently only one option is supported: error: an instance of dom
exception. specifications specification status comment generic sensor apithe definition of 'sensorerrorevent' in that specification. candidate recommendation initial definition. ...
SensorErrorEvent.error - Web APIs
the error read-only property of the sensorerrorevent interface returns the dom
exception object passed in the event's contructor. syntax var dom
exception = sensorerrorevent.error; value a dom
exception. specifications specification status comment generic sensor apithe definition of 'error' in that specification. candidate recommendation initial definition. ...
SensorErrorEvent - Web APIs
the sensorerrorevent interface of the sensor apis provides information about errors thrown by a sensor or related interface. constructor sensorerrorevent.sensorerrorevent() creates a new sensorerrorevent object. properties sensorerrorevent.error read only returns the dom
exception object passed in the event's contructor. specifications specification status comment generic sensor apithe definition of 'sensorerrorevent' in that specification. candidate recommendation initial definition. ...
ServiceWorker - Web APIs
rker. it returns one of the following values: installing, installed, activating, activated, or redundant. event handlers serviceworker.onstatechange read only an eventlistener property called whenever an event of type statechange is fired; it is basically fired anytime the serviceworker.state changes. methods the serviceworker interface inherits methods from its parent, worker, with the
exception of worker.terminate — this should not be accessible from service workers. examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. if ('serviceworker' in navigator) { navigator.serviceworker.register('service-worker.js', { scope: './' }).then(function (regist...
ServiceWorkerGlobalScope.onfetch - Web APIs
ion(fetchevent) { ... }; example this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, the code returns a promise that resolves to the first matching request in the cache object. if no match is found, the code fetches a response from the network. the code also handles
exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an
exception. it will return a normal response object that has the appropriate error code set. self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (resp...
ServiceWorkerGlobalScope - Web APIs
ervice worker context. examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, the code returns a promise that resolves to the first matching request in the cache object. if no match is found, the code fetches a response from the network. the code also handles
exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an
exception. it will return a normal response object that has the appropriate error code set. self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (resp...
ServiceWorkerRegistration.showNotification() - Web APIs
rge screens, a notification should remain active until the user clicks or dismisses it. if this value is absent or false, the desktop version of chrome will auto-minimize notifications after approximately twenty seconds. the default value is false. silent: when set indicates that no sounds or vibrations should be made. if options’s silent is true and options’s vibrate is present a typeerror
exception will be thrown. the default value is false. tag: an id for a given notification that allows you to find, replace, or remove the notification using a script if necessary. timestamp: a domtimestamp representing the time when the notification was created. it can be used to indicate the time at which a notification is actual. for example, this could be in the past when a notification is used for...
SharedWorker() - Web APIs
ng the type of credentials to use for the worker. the value can be omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring specifying an identifying name for the sharedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. return value the created worker.
exceptions a securityerror is raised if the document is not allowed to start workers, for example if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. examples the following code snippet shows creation of a sharedwo...
SourceBuffer.appendBuffer() - Web APIs
the appendbuffer() method of the sourcebuffer interface appends media segment data from an arraybuffer or arraybufferview object to the sourcebuffer. syntax sourcebuffer.appendbuffer(source); parameters source a buffersource (that is, either an arraybufferview or arraybuffer) which contains the media segment data you want to add to the sourcebuffer. return value undefined.
exceptions none. example tbd. specifications specification status comment media source extensionsthe definition of 'appendbuffer()' in that specification. recommendation initial definition. ...
SourceBuffer.appendBufferAsync() - Web APIs
fer, or null if the request could not be initiated. example this simplified example async function, fillsourcebuffer(), takes as input parameters buffersource, buffer, and a sourcebuffer to which to append the source media from the buffer. async function fillsourcebuffer(buffer, msbuffer) { try { while(true) { await msbuffer.appendbufferasync(buffer); } } catch(e) { handle
exception(e); } } specifications not currently part of any specification. this is being experimented with under the auspices of the web platform incubator community group (wicg). specification status comment media source extensions recommendation initial definition; does not include this method. ...
SourceBuffer.appendWindowEnd - Web APIs
ta is appended to the sourcebuffer. coded media frames with timestamps wthin this range will be appended, whereas those outside the range will be filtered out. the default value of appendwindowend is positive infinity. syntax var myappendwindowend = sourcebuffer.appendwindowend; sourcebuffer.appendwindowend = 120.0; value a double, indicating the end time of the append window, in seconds.
exceptions the following
exceptions may be thrown when setting a new value for this property.
exception explanation invalidaccesserror an attempt was made to set the value to less than or equal to sourcebuffer.appendwindowstart, or nan. invalidstateerror this sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), or this s...
SourceBuffer.appendWindowStart - Web APIs
s wthin this range will be appended, whereas those outside the range will be filtered out. the default value of appendwindowstart is the presentation start time, which is the beginning time of the playable media. syntax var myappendwindowstart = sourcebuffer.appendwindowstart; sourcebuffer.appendwindowstart = 2.0; value a double, indicating the start time of the append window, in seconds.
exceptions the following
exceptions may be thrown when setting a new value for this property.
exception explanation invalidaccesserror an attempt was made to set the value to less than 0, or a value greater than or equal to sourcebuffer.appendwindowend. invalidstateerror this sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently...
SourceBuffer.changeType() - Web APIs
to change codecs or container type mid-stream. one scenario in which this is helpful is to support adapting the media source to changing bandwidth availability, by transitioning from one codec to another as resource constraints change. syntax sourcebuffer.changetype(type); parameters type a domstring specifying the mime type that future buffers will conform to. return value undefined.
exceptions typeerror the specified string is empty, rather than indicating a valid mime type. invalidstateerror the sourcebuffer is not a member of the parent media source's sourcebuffers list, or the buffer's updating property indicates that a previously queued appendbuffer() or remove() is still being processed. notsupportederror the specified mime type is not supported, or is not supported with ...
SourceBuffer.remove() - Web APIs
range from the sourcebuffer. this method can only be called when sourcebuffer.updating equals false. if sourcebuffer.updating is not equal to false, call sourcebuffer.abort(). syntax sourcebuffer.remove(start, end); parameters start a double representing the start of the time range, in seconds. end a double representing the end of the time range, in seconds. return value undefined.
exceptions
exception explanation invalidaccesserror the mediasource.duration property is equal to nan, the start parameter is negative or greater than mediasource.duration, or the end parameter is less than or equal to start or equal to nan. invalidstateerror the sourcebuffer.updating property is equal to true, or this sourcebuffer has been removed from the mediasou...
SourceBuffer.removeAsync() - Web APIs
a promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the sourcebuffer. example this example establishes an asynchronous function, emptysourcebuffer(), which simply clears the contents of the specified sourcebuffer. async function emptysourcebuffer(msbuffer) { await msbuffer.removeasync(0, infinity).catch(function(e) { handle
exception(e); } } specifications not currently part of the mse specification. specification status comment media source extensions recommendation initial definition. ...
SourceBuffer.timestampOffset - Web APIs
the timestampoffset property of the sourcebuffer interface controls the offset applied to timestamps inside media segments that are appended to the sourcebuffer. the initial value of timestampoffset is 0. syntax var myoffset = sourcebuffer.timestampoffset; sourcebuffer.timestampoffset = 2.5; value a double, with the offset amount expressed in seconds.
exceptions the following
exceptions may be thrown when setting a new value for this property.
exception explanation invalidstateerror one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is currently true), a media segment inside the sourcebuffer is currently being parsed, or this sourcebuffer has been removed from the mediaso...
SourceBuffer.trackDefaults - Web APIs
the trackdefaults property of the sourcebuffer interface specifies the default values to use if kind, label, and/or language information is not available in the initialization segment of the media to be appended to the sourcebuffer. syntax var mytrackdefaults = sourcebuffer.trackdefaults; sourcebuffer.trackdefaults = mytrackdefaultlist; value a trackdefaultlist object.
exceptions the following
exceptions may be thrown when setting a new value for this property.
exception explanation invalidstateerror one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is currently true), or this sourcebuffer has been removed from the mediasource. example tbd ...
SourceBufferList: indexed property getter - Web APIs
the indexed property getter of the sourcebufferlist interface allows the sourcebuffer objects in the list to be accessed with an array operator (i.e. [].) syntax var mysourcebuffer = sourcebufferlist[index]; parameters index the index position of the sourcebuffer object you want to return. return value a sourcebuffer object.
exceptions no specific
exceptions are thrown, but if the supplied index is great than or equal to sourcebufferlist.length, the operation will return undefined. example tbd. specifications specification status comment media source extensionsthe definition of 'sourcebuffer() getter' in that specification. recommendation initial definition. ...
StaticRange.StaticRange() - Web APIs
ed. startoffset the offset into the starting node at which the first character of the range is found. endcontainer the node in which the end point of the range is located. endoffset the offset into the node indicated by endoffset at which the last character in the range is located. return value a new staticrange object initialized with the values given in the rangespec object.
exceptions invalidnodetypeerror a dom
exception fired if either or both of the startcontainer and/or endcontainer are a type of node which you can't include in a range. those node types are node.document_type_node (representing the documenttype node derived from the dtd identified using the doctype preamble in the html, for example) and the attr node describing an attribute of an element on the dom.. ...
Storage.setItem() - Web APIs
rface, when passed a key name and value, will add that key to the given storage object, or update that key's value if it already exists. syntax storage.setitem(keyname, keyvalue); parameters keyname a domstring containing the name of the key you want to create/update. keyvalue a domstring containing the value you want to give the key you are creating/updating. return value undefined.
exceptions setitem() may throw an
exception if the storage is full. particularly, in mobile safari (since ios 5) it always throws when the user enters private mode. (safari sets the quota to 0 bytes in private mode, unlike other browsers, which allow storage in private mode using separate data containers.) hence developers should make sure to always catch possible
exceptions from setitem(). example the ...
SubtleCrypto.decrypt() - Web APIs
rams object. to use aes-gcm, pass an aesgcmparams object. key is a cryptokey containing the key to be used for decryption. if using rsa-oaep, this is the privatekey property of the cryptokeypair object. data is a buffersource containing the data to be decrypted (also known as ciphertext). return value result is a promise that fulfills with an arraybuffer containing the plaintext.
exceptions the promise is rejected when the following
exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or there was ...
SubtleCrypto.deriveBits() - Web APIs
algorithm is ecdh, this will be the ecdh private key. otherwise it will be the initial key material for the derivation function: for example, for pbkdf2 it might be a password, imported as a cryptokey using subtlecrypto.importkey(). length is a number representing the number of bits to derive. return value result is a promise that fulfills with an arraybuffer containing the derived bits.
exceptions the promise is rejected when one of the following
exceptions are encountered: invalidaccesserror raised when the base key is not a key for the requested derivation algorithm or if the cryptokey.usages value of that key doesn't contain derivekey. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for derivation, or if the algorithm requested for th...
SubtleCrypto.deriveKey() - Web APIs
essages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a new key. "derivebits": the key may be used in deriving bits. "wrapkey": the key may be used to wrap a key. "unwrapkey": the key may be used to unwrap a key. return value result is a promise that fulfills with a cryptokey.
exceptions the promise is rejected when one of the following
exceptions are encountered: invalidaccesserror raised when the master key is not a key for the requested derivation algorithm or if the cryptokey.usages value of that key doesn't contain derivekey. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for derivation, or if the algorithm requested for ...
SubtleCrypto.encrypt() - Web APIs
aes-ctr, pass an aesctrparams object. to use aes-cbc, pass an aescbcparams object. to use aes-gcm, pass an aesgcmparams object. key is a cryptokey containing the key to be used for encryption. data is a buffersource containing the data to be encrypted (also known as the plaintext). return value result is a promise that fulfills with an arraybuffer containing the "ciphertext".
exceptions the promise is rejected when the following
exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or aes-gcm...
SubtleCrypto.exportKey() - Web APIs
it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. key is the cryptokey to export. return value result is a promise. if format was jwk, then the promise fulfills with a json object containing the key. otherwise the promise fulfills with an arraybuffer containing the key.
exceptions the promise is rejected when one of the following
exceptions is encountered: invalidaccesserror raised when trying to export a non-extractable key. notsupported raised when trying to export in an unknown format. typeerror raised when trying to use an invalid format. examples note: you can try the working examples out on github. raw export this example exports an aes key as an arr...
SubtleCrypto.generateKey() - Web APIs
he key may be used to verify signatures. derivekey: the key may be used in deriving a new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key. return value result is a promise that fulfills with a cryptokey (for symmetric algorithms) or a cryptokeypair (for public-key algorithms).
exceptions the promise is rejected when the following
exception is encountered: syntaxerror raised when the result is a cryptokey of type secret or private but keyusages is empty. syntaxerror raised when the result is a cryptokeypair and its privatekey.usages attribute is empty. examples note: you can try the working examples on github. rsa key pair generation this code generates an rsa-oaep ...
SubtleCrypto.importKey() - Web APIs
key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key. return value result is a promise that fulfills with the imported key as a cryptokey object.
exceptions the promise is rejected when one of the following
exceptions is encountered: syntaxerror raised when keyusages is empty but the unwrapped key is of type secret or private. typeerror raised when trying to use an invalid format or if the keydata is not suited for that format. supported formats this api supports four different key import/export formats: raw, pkcs #8, subjectpublickeyinfo,...
SubtleCrypto.sign() - Web APIs
e string "hmac" or an object of the form { "name": "hmac" }. key is a cryptokey object containing the key to be used for signing. if algorithm identifies a public-key cryptosystem, this is the private key. data is an arraybuffer or arraybufferview object containing the data to be signed. return value signature is a promise that fulfills with an arraybuffer containing the signature.
exceptions the promise is rejected when the following
exception is encountered: invalidaccesserror raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. supported algorithms the web crypto api provides four algorithms that can be used for signing and signature verification. three of these ...
SubtleCrypto.unwrapKey() - Web APIs
key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key return value result is a promise that fulfills with the unwrapped key as a cryptokey object.
exceptions the promise is rejected when one of the following
exceptions is encountered: invalidaccesserror raised when the unwrapping key is not a key for the requested unwrap algorithm or if the cryptokey.usages value of that key doesn't contain unwrap. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for encryption or wrapping. syntaxerror raised when ...
SubtleCrypto.verify() - Web APIs
key that will be used to verify the signature. it is the secret key for a symmetric algorithm and the public key for a public-key system. signature is a arraybuffer containing the signature to verify. data is a arraybuffer containing the data whose signature is to be verified. return value result is a promise that fulfills with a boolean: true if the signature is valid, false otherwise.
exceptions the promise is rejected when the following
exception is encountered: invalidaccesserror raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. supported algorithms the verify() method supports the same algorithms as the sign() method. examples note: you can tr...
SubtleCrypto.wrapKey() - Web APIs
to use rsa-oaep, pass an rsaoaepparams object. to use aes-ctr, pass an aesctrparams object. to use aes-cbc, pass an aescbcparams object. to use aes-gcm, pass an aesgcmparams object. to use aes-kw, pass the string "aes-kw", or an object of the form { "name": "aes-kw }. return value result is a promise that fulfills with an arraybuffer containing the encrypted exported key.
exceptions the promise is rejected when one of the following
exceptions is encountered: invalidaccesserror raised when the wrapping key is not a key for the requested wrap algorithm. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for encryption or wrapping. typeerror raised when trying to use an invalid format. supported algorithms all algorithms th...
Text.splitText() - Web APIs
fset is equal to the length of the original node, the newly created node has no data. separated text nodes can be concatenated using the node.normalize() method. syntax newnode = textnode.splittext(offset) parameters offset the index immediately before which to break the text node. return value returns a newly created text node that contains the text after the specified offset point.
exceptions thrown a dom
exception with a value of index_size_err is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text; a dom
exception with a value of no_modification_allowed_err is thrown if the node is read-only. example in this example, the text of a <p> is split into two text nodes, and a <u> is inserted between them. html <p>foobar</p> java...
TextEncoder() - Web APIs
coder() takes no parameters since firefox 48 and chrome 53 note: prior to firefox 48 and chrome 53, an encoding type label was accepted as a paramer to the textencoder object, since then both browers have removed support for any encoder type other than utf-8, to match the spec. any type label passed into the textencoder constructor will now be ignored and a utf-8 textencoder will be created.
exceptions textencoder() throws no
exceptions since firefox 48 and chrome 53 note: prior to firefox 48 and chrome 53 an
exception would be thrown for an unknown encoding type. specifications specification status comment encodingthe definition of 'textencoder()' in that specification. living standard initial definition ...
TimeRanges.end() - Web APIs
returns the time offset at which a specified time range ends. syntax endtime = timeranges.end(index) parameters index is the range number to return the ending time for.
exceptions index_size_err a dom
exception thrown if the specified index doesn't correspond to an existing range. example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded. specifications specification stat...
TimeRanges.start() - Web APIs
returns the time offset at which a specified time range begins. syntax starttime = timeranges.start(index) parameters index is the range number to return the starting time for.
exceptions index_size_err a dom
exception thrown if the specified index doesn't correspond to an existing range. example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded. specifications specification...
TouchEvent - Web APIs
an be supported, in which case the earliest touch in the touchlist gets canceled. using with addeventlistener() and preventdefault() it's important to note that in many cases, both touch and mouse events get sent (in order to let non-touch-specific code still interact with the user). if you use touch events, you should call preventdefault() to keep the mouse event from being sent as well. the
exception to this is chrome, starting with version 56 (desktop, chrome for android, and android webview), where the default value for the passive option for touchstart and touchmove is true and calls to preventdefault() will have no effect. to override this behavior, you need to set the passive option to false, after which calling preventdefault() will work as specified. the change to treat listeners as pa...
UserDataHandler - Web APIs
1.2)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. 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. per the specification,
exceptions should not be thrown in a userdatahandler. in both document.importnode() and node.clonenode(), although user data is not copied over, the handler will be called. properties none. 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. operation (unsign...
Using the User Timing API - Web APIs
("... cleared '" + obj + "' measure(s)", 1); performance.clearmeasures(obj); } else { // no argument specified so clear all measures log("... cleared all measures", 1); performance.clearmeasures(); } } interoperability as shown in the performance interface's browser compatibility table, the user timing methods are broadly implemented by desktop and mobile browsers (the only
exceptions are no support for desktop safari and mobile safari). see also user timing standard; w3c editor's draft a primer for web performance timing apis; xiaoqian wu; w3c editor's draft ...
User Timing API - Web APIs
timeline, call performance.clearmeasures(name) where name is the name of the measure(s) you want removed. if this method is called with no arguments, all measure type entries will be removed from the performance timeline. interoperability as shown in the performance interface's browser compatibility table, the user timing methods are broadly implemented by desktop and mobile browsers (the only
exceptions are desktop safari and mobile safari, however the safari technology preview 24 has support). to test your browser's support for this api, run the perf-api-support application. see also user timing standard; w3c editor's draft caniuse data a primer for web performance timing apis; xiaoqian wu; w3c editor's draft ...
ValidityState - Web APIs
the validitystate interface represents the validity states that an element can be in, with respect to constraint validation. together, they help explain why an element's value fails to validate, if it's not valid. properties for each of these boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the
exception of the valid property, which is true if the element's value obeys all constraints. badinput read only a boolean that is true if the user has provided input that the browser is unable to convert. customerror read only a boolean indicating whether the element's custom validity message has been set to a non-empty string by calling the element's setcustomvalidity() method. patternmismatch read only a boolean that is true if t...
WakeLock.request() - Web APIs
rface returns a promise that resolves with a wakelocksentinel object, which allows control over screen dimming and locking. syntax var wakelock = navigator.wakelock.request(type); parameters type options are as follows: 'screen': requests a screen wake lock. prevents devices from dimming or locking the screen. return value a promise that resolves with a wakelocksentinel object.
exceptions notallowederror thrown when wake lock is not available, which can happen because: document is not allowed to use screen wake lock due to screen-wake-lock policy. document is not fully active. document is hidden. user agent could not acquire platform's wake lock. examples the following asynchronous function requests a wakelocksentinel object. the request() method is wrapped i...
WebGL2RenderingContext.drawBuffers() - Web APIs
an array of glenum specifying the buffers into which fragment colors will be written. possible values are: gl.none: fragment shader output is not written into any color buffer. gl.back: fragment shader output is written into the back color buffer. gl.color_attachment{0-15}: fragment shader output is written in the nth color attachment of the current framebuffer. return value none.
exceptions if buffers contains not one of the accepted values, a gl.invalid_enum error is thrown. examples gl.drawbuffers([gl.none, gl.color_attachment1]); specifications specification status comment webgl 2.0the definition of 'drawbuffers' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gldrawbuffers' in th...
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
uffer. possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying an offset in the element array buffer. must be a valid multiple of the size of the given type. instancecount a glsizei specifying the number of instances of the set of elements to execute. return value none.
exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if offset is a valid multiple of the size of the given type, a gl.invalid_operation error is thrown. if count or instancecount are negative, a gl.invalid_value error is thrown. examples gl.drawelementsinstanced(gl.points, 2, gl.unsigned_short, 0, 4); specifications specification status comment...
WebGL2RenderingContext.drawRangeElements() - Web APIs
ontained in offset. count a glsizei specifying the number of elements to be rendered. type a glenum specifying the type of the values in the element array buffer. possible values are: gl.unsigned_byte gl.unsigned_short gl.unsigned_int offset a glintptr specifying an offset in the element array buffer. must be a valid multiple of the size of the given type. return value none.
exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if offset is a valid multiple of the size of the given type, a gl.invalid_operation error is thrown. if count is negative, a gl.invalid_value error is thrown. examples gl.drawrangeelements(gl.points, 0, 7, 8, gl.unsigned_byte, 0); specifications specification status comment webgl 2.0t...
WebGL2RenderingContext.getBufferSubData() - Web APIs
fer: buffer used for pixel transfer operations. srcbyteoffset a glintptr specifying the byte offset from which to start reading from the buffer. dstdata an arraybuffer or sharedarraybuffer to which to write the buffer data. srcoffset optional a gluint specifying the element index offset where to start reading the buffer. length optional a gluint defaulting to 0. return value none.
exceptions an invalid_value error is generated if: offset + returneddata.bytelength would extend beyond the end of the buffer returneddata is null offset is less than zero. an invalid_operation error is generated if: zero is bound to target target is transform_feedback_buffer, and any transform feedback object is currently active. examples var buffer = gl.createbuffer(); gl.bindbuffer(gl.arr...
WebGLRenderingContext.activeTexture() - Web APIs
the webglrenderingcontext.activetexture() method of the webgl api specifies which texture unit to make active. syntax void gl.activetexture(texture); parameters texture the texture unit to make active. the value is a gl.texturei where i is within the range from 0 to gl.max_combined_texture_image_units - 1. return value none.
exceptions if texture is not one of gl.texturei, where i is within the range from 0 to gl.max_combined_texture_image_units - 1, a gl.invalid_enum error is thrown. examples the following call selects gl.texture1 as the current texture. subsequent calls that modify the texture state will affect this texture. gl.activetexture(gl.texture1); the number of texture units is implementation dependent, you can get this number with the help of the max_combined_texture_i...
WebGLRenderingContext.bindBuffer() - Web APIs
buffer for copying from one buffer object to another. gl.transform_feedback_buffer: buffer for transform feedback operations. gl.uniform_buffer: buffer used for storing uniform blocks. gl.pixel_pack_buffer: buffer used for pixel transfer operations. gl.pixel_unpack_buffer: buffer used for pixel transfer operations. buffer a webglbuffer to bind. return value none.
exceptions only one target can be bound to a given webglbuffer. an attempt to bind the buffer to another target will throw an invalid_operation error and the current buffer binding will remain the same. a webglbuffer which has been marked for deletion with deletebuffer cannot be (re-)bound. an attempt to do so will generate an invalid_operation error, and the current binding will remain untouched. examp...
WebGLRenderingContext.bindFramebuffer() - Web APIs
ffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. framebuffer a webglframebuffer object to bind. return value none.
exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer, gl.draw_framebuffer, or gl.read_framebuffer. examples binding a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, framebuffer); getting current bindings to check the current frame buffer binding, qu...
WebGLRenderingContext.bindRenderbuffer() - Web APIs
bgl api binds a given webglrenderbuffer to a target, which must be gl.renderbuffer. syntax void gl.bindrenderbuffer(target, renderbuffer); parameters target a glenum specifying the binding point (target). possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. renderbuffer a webglrenderbuffer object to bind. return value none.
exceptions a gl.invalid_enum error is thrown if target is not gl.renderbuffer. examples binding a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); gl.bindrenderbuffer(gl.renderbuffer, renderbuffer); getting current bindings to check the current renderbuffer binding, query the renderbuffer_binding constant. ...
WebGLRenderingContext.bindTexture() - Web APIs
binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. texture a webgltexture object to bind. return value none.
exceptions a gl.invalid_enum error is thrown if target is not gl.texture_2d, gl.texture_cube_map, gl.texture_3d, or gl.texture_2d_array. examples binding a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); getting current bindings to check the current texture binding, query the gl.te...
WebGLRenderingContext.blendEquation() - Web APIs
stination - source when using the ext_blend_minmax extension: ext.min_ext: minimum of source and destination, ext.max_ext: maximum of source and destination. when using a webgl 2 context, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination. default value: gl.func_add
exception if mode is not one of the three possible values, a gl.invalid_enum error is thrown. return value none. examples to set the blend equation, use: gl.blendequation(gl.func_add); gl.blendequation(gl.func_subtract); gl.blendequation(gl.func_reverse_subtract); to get the blend equations, query the blend_equation, blend_equation_rgb and blend_equation_alpha constants which return gl.func_add, gl...
WebGLRenderingContext.blendEquationSeparate() - Web APIs
act: destination - source, when using the ext_blend_minmax extension: ext.min_ext: minimum of source and destination, ext.max_ext: maximum of source and destination. when using a webgl 2 context, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination. return value none.
exceptions if mode is not one of the three possible values, a gl.invalid_enum error is thrown. examples to set the blend equations, use: gl.blendequationseparate(gl.func_add, gl.func_subtract); to get the current blend equations, query the blend_equation, blend_equation_rgb and blend_equation_alpha constants which return gl.func_add, gl.func_subtract, gl.func_reverse_subtract, or if the ext_blend_min...
WebGLRenderingContext.blendFunc() - Web APIs
used for blending pixel arithmetic. syntax void gl.blendfunc(sfactor, dfactor); parameters sfactor a glenum specifying a multiplier for the source blending factors. the default value is gl.one. for possible values, see below. dfactor a glenum specifying a multiplier for the destination blending factors. the default value is gl.zero. for possible values, see below. return value none.
exceptions if sfactor or dfactor is not one of the listed possible values, a gl.invalid_enum error is thrown. if a constant color and a constant alpha value are used together as source and destination factors, a gl.invalid_enum error is thrown. constants the following constants can be used for sfactor and dfactor. the formula for the blending color can be described like this: color(rgba) = (sourcec...
WebGLRenderingContext.blendFuncSeparate() - Web APIs
tion blending factors. the default value is gl.zero. for possible values, see below. srcalpha a glenum specifying a multiplier for the alpha source blending factor. the default value is gl.one. for possible values, see below. dstalpha a glenum specifying a multiplier for the alpha destination blending factor. the default value is gl.zero. for possible values, see below. return value none.
exceptions if srcrgb, dstrgb, srcalpha, or dstalpha is not one of the listed possible values, a gl.invalid_enum error is thrown. if a constant color and a constant alpha value are used together as source (srcrgb) and destination (dstrgb) factors, a gl.invalid_enum error is thrown. constants the following constants can be used for srcrgb, dstrgb, srcalpha, and dstalpha the formulas for the blending ...
WebGLRenderingContext.bufferData() - Web APIs
drawing and image specification commands. gl.stream_copy: the contents are intended to be specified once by reading data from webgl, and used at most a few times as the source for webgl drawing and image specification commands. srcoffset a gluint specifying the element index offset where to start reading the buffer. length optional a gluint defaulting to 0. return value none.
exceptions a gl.out_of_memory error is thrown if the context is unable to create a data store with the given size. a gl.invalid_value error is thrown if size is negative. a gl.invalid_enum error is thrown if target or usage are not one of the allowed enums. examples using bufferdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer();...
WebGLRenderingContext.bufferSubData() - Web APIs
dstbyteoffset a glintptr specifying an offset in bytes where the data replacement will start. srcdata optional an arraybuffer, sharedarraybuffer or one of the arraybufferview typed array types that will be copied into the data store. srcoffset a gluint specifying the element index offset where to start reading the buffer. length optional a gluint defaulting to 0. return value none.
exceptions a gl.invalid_value error is thrown if the data would be written past the end of the buffer or if data is null. a gl.invalid_enum error is thrown if target is not one of the allowed enums. examples using buffersubdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl...
WebGLRenderingContext.clear() - Web APIs
he preset values can be set by clearcolor(), cleardepth() or clearstencil(). the scissor box, dithering, and buffer writemasks can affect the clear() method. syntax void gl.clear(mask); parameters mask a glbitfield bitwise or mask that indicates the buffers to be cleared. possible values are: gl.color_buffer_bit gl.depth_buffer_bit gl.stencil_buffer_bit return value none.
exceptions if mask is not one of the listed possible values, a gl.invalid_enum error is thrown. examples the clear() method accepts multiple values. gl.clear(gl.depth_buffer_bit); gl.clear(gl.depth_buffer_bit | gl.color_buffer_bit); to get the current clear values, query the color_clear_value, depth_clear_value, and stencil_clear_value constants. gl.getparameter(gl.color_clear_value); gl.getparamete...
WebGLRenderingContext.drawArrays() - Web APIs
line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. return value none.
exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if first or count are negative, a gl.invalid_value error is thrown. if gl.current_program is null, a gl.invalid_operation error is thrown. examples gl.drawarrays(gl.points, 0, 8); specifications specification status comment webgl 1.0the definition of 'drawarrays' in that specification...
WebGLRenderingContext.drawElements() - Web APIs
nts to be rendered. type a glenum specifying the type of the values in the element array buffer. possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying a byte offset in the element array buffer. must be a valid multiple of the size of the given type. return value none.
exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if offset is not a valid multiple of the size of the given type, a gl.invalid_operation error is thrown. if count is negative, a gl.invalid_value error is thrown. examples gl.drawelements(gl.points, 8, gl.unsigned_byte, 0); specifications specification status comment webgl 1.0the defi...
WebGLRenderingContext.framebufferRenderbuffer() - Web APIs
_webgl ext.color_attachment13_webgl ext.color_attachment14_webgl ext.color_attachment15_webgl renderbuffertarget a glenum specifying the binding point (target) for the render buffer. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. renderbuffer a webglrenderbuffer object to attach. return value none.
exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer, gl.draw_framebuffer, or gl.read_framebuffer. a gl.invalid_enum error is thrown if renderbuffertarget is not gl.renderbuffer. a gl.invalid_enum error is thrown if attachment is not one of the allowed enums. examples gl.framebufferrenderbuffer(gl.framebuffer, gl.color_attachment0, gl.renderbuffer, renderbuffer); specifica...
WebGLRenderingContext.framebufferTexture2D() - Web APIs
texture_cube_map_negative_y: image for the negative y face of the cube. gl.texture_cube_map_positive_z: image for the positive z face of the cube. gl.texture_cube_map_negative_z: image for the negative z face of the cube. texture a webgltexture object whose image to attach. level a glint specifying the mipmap level of the texture image to be attached. must be 0. return value none.
exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer. attachment is not one of the accepted attachment points. textarget is not one of the accepted texture targets. a gl.invalid_value error is thrown if level is not 0. a gl.invalid_operation error is thrown if texture isn't 0 or the name of an existing texture object. examples gl.framebuffertexture2d(gl.fra...
WebGLRenderingContext.getActiveUniform() - Web APIs
entry for each member. if the uniform block has an instance name, the block name is prefixed. e.g. uniform block { float foo; }; will result in foo, and uniform block { float bar; } e; will result in block.bar. the size attribute of the return value corresponds to the length of the array for uniforms declared as arrays. otherwise, it is 1 (this includes interface blocks instanced with arrays).
exceptions gl.invalid_value is generated if the program webglprogram is invalid (not linked, deleted, etc.). gl.invalid_value is generated if index is not in the range [0, gl.getprogramparameter(program, gl.active_uniforms) - 1]. examples const numuniforms = gl.getprogramparameter(program, gl.active_uniforms); for (let i = 0; i < numuniforms; ++i) { const info = gl.getactiveuniform(program, i); ...
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
_color_encoding_ext a glenum indicating the framebuffer color encoding. either gl.linear or ext.srgb_ext. ext.framebuffer_attachment_texture_num_views_ovr a glsizei indicating the number of views of the framebuffer object attachment. ext.framebuffer_attachment_texture_base_view_index_ovr a glint indicating the base view index of the framebuffer object attachment.
exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer, gl.draw_framebuffer, gl.read_framebuffer or if attachment is not one of the accepted attachment points. examples gl.getframebufferattachmentparameter(gl.framebuffer, gl.color_attachment0, gl.framebuffer_attachment_object_type); specifications specification status commen...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
ic format. syntax webglshaderprecisionformat gl.getshaderprecisionformat(shadertype, precisiontype); parameters shadertype either a gl.fragment_shader or a gl.vertex_shader. precisiontype a precision type value. either gl.low_float, gl.medium_float, gl.high_float, gl.low_int, gl.medium_int, or gl.high_int. return value a webglshaderprecisionformat object or null, if an error occurs.
exceptions gl.invalid_enum if the shader or precision types aren't recognized. gl.invalid_operation if the shader compiler isn't supported. examples the following code gets the precision format of a gl.vertex_shader with a gl.medium_float precision type. var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_floa...
WebGLRenderingContext.makeXRCompatible() - Web APIs
n it originally was. this is useful if you have an application which can start out being presented on a standard 2d display but can then be transitioned to a 3d immersion system. syntax let makecompatpromise = webglrenderingcontext.makexrcompatible(); parameters none. return value a promise which successfully resolves once the webgl context is ready to be used for rendering webxr content.
exceptions this method doesn't throw traditional
exceptions; instead, the promise rejects with one of the following errors as the value passed into the rejection handler: aborterror switching the context over to the webxr-compatible context failed. invalidstateerror the webgl context has been lost or there is no available webxr device. usage notes because makexrcompatible() may involve replacing ...
WebGLRenderingContext.readPixels() - Web APIs
_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev pixels an arraybufferview object to read data into. the array type must match the type of the type parameter. uint8array for gl.unsigned_byte. uint16array for gl.unsigned_short_5_6_5, gl.unsigned_short_4_4_4_4, or gl.unsigned_short_5_5_5_1. float32array for gl.float. dstoffset optional offset. defaults to 0. return value none.
exceptions a gl.invalid_enum error is thrown if format or type is not an accepted value. a gl.invalid_operation error is thrown if type is gl.unsigned_short_5_6_5 and format is not gl.rgb. type is gl.unsigned_short_4_4_4_4 and format is not gl.rgba. type does not match the typed array type of pixels. a gl.invalid_framebuffer_operation error is thrown if the currently bound framebuffer...
WebGLRenderingContext.scissor() - Web APIs
or the lower left corner of the box. default value: 0. y a glint specifying the vertical coordinate for the lower left corner of the box. default value: 0. width a non-negative glsizei specifying the width of the scissor box. default value: width of the canvas. height a non-negative glsizei specifying the height of the scissor box. default value: height of the canvas. return value none.
exceptions if either width or height is a negative value, a gl.invalid_value error is thrown. examples when the scissor test is enabled, only pixels within the scissor box can be modified by drawing commands. // turn on scissor test gl.enable(gl.scissor_test); // set the scissor rectangle gl.scissor(x, y, width, height); // execute drawing commands in the scissor box (e.g. clear) // turn off scissor...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
f stride is 0, the attribute is assumed to be tightly packed, that is, the attributes are not interleaved but each attribute is in a separate block, and the next vertex' attribute follows immediately after the current vertex. offset a glintptr specifying an offset in bytes of the first component in the vertex attribute array. must be a multiple of the byte length of type. return value none.
exceptions a gl.invalid_value error is thrown if offset is negative. a gl.invalid_operation error is thrown if stride and offset are not multiples of the size of the data type. a gl.invalid_operation error is thrown if no webglbuffer is bound to the array_buffer target. when using a webgl 2 context, a gl.invalid_operation error is thrown if this vertex attribute is defined as a integer in the vertex ...
A basic 2D WebGL animation example - Web APIs
or. the values of z and w are fixed at 0.0 and 1.0, respectively, since we're drawing in 2d. the standard webgl global gl_position is then set to the transformed and rotated vertex's position. fragment shader next comes the fragment shader. its role is to return the color of each pixel in the shape being rendered. since we're drawing a solid, untextured object with no lighting applied, this is
exceptionally simple: <script id="fragment-shader" type="x-shader/x-fragment"> #ifdef gl_es precision highp float; #endif uniform vec4 uglobalcolor; void main() { gl_fragcolor = uglobalcolor; } </script> this starts by specifying the precision of the float type, as required. then we set the global gl_fragcolor to the value of the uniform uglobalcolor, which is set by the javascript co...
Lifetime of a WebRTC session - Web APIs
es, during the lifetime of a webrtc session, network conditions change. one of the users might transition from a cellular to a wifi network, or the network might become congested, for example. when this happens, the ice agent may choose to perform ice restart. this is a process by which the network connection is renegotiated, exactly the same way the initial ice negotiation is performed, with one
exception: media continues to flow across the original network connection until the new one is up and running. then media shifts to the new network connection and the old one is closed. note: different browsers support ice restart under different sets of conditions. not all browsers will perform ice restart due to network congestion, for example. if you need to change the configuration of the connectio...
WebSocket() - Web APIs
ls optional either a single protocol string or an array of protocol strings. these strings are used to indicate sub-protocols, so that a single server can implement multiple websocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). if you don't specify a protocol string, an empty string is assumed.
exceptions thrown security_err the port to which the connection is being attempted is being blocked. syntaxerror the url is invalid. specifications specification status comment html living standardthe definition of 'the websocket constructor' in that specification. living standard ...
WebSocket.close() - Web APIs
optional a numeric value indicating the status code explaining why the connection is being closed. if this parameter is not specified, a default value of 1005 is assumed. see the list of status codes of closeevent for permitted values. reason optional a human-readable string explaining why the connection is closing. this string must be no longer than 123 bytes of utf-8 text (not characters).
exceptions thrown invalid_access_err an invalid code was specified. syntax_err the reason string is too long or contains unpaired surrogates. note: in gecko, this method didn't support any parameters prior to gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). specifications specification status comment html living standard the definition of 'websocket.close()...
WebSocket.send() - Web APIs
mber of bytes. blob specifying a blob enqueues the blob's raw data to be transmitted in a binary frame. the value of bufferedamount is increased by the byte size of that raw data. arraybufferview you can send any javascript typed array object as a binary frame; its binary data contents are queued in the buffer, increasing the value of bufferedamount by the requisite number of bytes.
exceptions thrown invalid_state_err the connection is not currently open. syntax_err the data is a string that has unpaired surrogates. note: gecko's implementation of the send() method differs somewhat from the specification in gecko 6.0; gecko returns a boolean indicating whether or not the connection is still open (and, by extension, that the data was successfully queued or transmitted); this i...
Writing WebSocket servers - Web APIs
for example, let's assume that your server is listening on example.com, port 8000, and your socket server responds to get requests at example.com/chat. warning: the server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. browsers generally require a secure connection for websockets, although they may offer an
exception for local devices. the handshake is the "web" in websockets. it's the bridge from http to websockets. in the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. the server must be careful to understand everything the client asks for, otherwise security issues can occur. tip: the request-uri (/chat here) has no defi...
Geometry and reference spaces in WebXR - Web APIs
viable if the rooms have uneven floors or floors whose height above ground level vary, since they don't support the avatar's vertical position changing. the primary reference space types the viewer reference space corresponds to the viewer's position in space; it's used by the xrviewerpose returned by the xrframe method getviewerpose(). it's not typically used directly otherwise. the only real
exception is that you are likely to use the viewer reference space when performing the xr scene inline within web content. the local reference space is typically used to describe a relatively small area, such as a single room. it is not only always available when using an immersive session mode (immersive-vr or immersive-ar), but is always included among the optional features when requesting a new session...
WebXR permissions and security - Web APIs
application. the document is considered trustworthy, in that it is responsible and is both currently active and has focus. the user's intent to enter immersive vr mode is well understood; see user intent below for details. if all of that is true, the promise returned by requestsession() is resolved, and the new xrsession object is passed into the fulfillment handler. otherwise, an appropriate
exception is thrown, such as securityerror if the document doesn't have permission to enter immersive mode. 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. specifically: if the...
Starting up and shutting down a WebXR session - Web APIs
ser declining to grant permission to use the headset—the promise gets rejected. so a more complete function that starts up and returns a webxr session could look like this: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr"); return session; } catch(error) { throw error; } } this function returns the new xrsession or throws an
exception if an error occurs while creating the session. customizing the session in addition to the display mode, the requestsession() method can take an optional object with initialization parameters to customize the session. currently, the only configurable aspect of the session is which of the reference spaces should be used to represent the world's coordinate system. you can specify either required o...
Keyframe Formats - Web APIs
only specified the end state of the animation, and the beginning state is implied. attributes keyframes may specify property-value pairs for any of the animatable css properties. the property names are specified using camel-case so for example background-color becomes backgroundcolor and background-position-x becomes backgroundpositionx. shorthand values such as margin are also permitted. two
exceptional css properties are: float, which must be written as cssfloat since "float" is a reserved word in javascript. it's just for reference here, this will have no effect on animation since "float" is not an animatable css property. offset, which must be written as cssoffset since "offset" represents the keyframe offset as described below. the following special attributes may also be specified: ...
Using the Web Animations API - Web APIs
parated from the declaration with a comma. in the above example, to make sure that alice’s color changes at 30% (not 50%) for the color change, we are giving it offset: 0.3. currently, there should be at least two keyframes specified (representing the starting and ending states of the animation sequence). if your keyframe list has only one entry, element.animate() may throw a notsupportederror
exception in some browsers until they are updated. so to recap, the keys are equally spaced by default unless you specify an offset on a key. handy, no? representing timing properties we’ll also need to create an object of timing properties (an animationeffecttimingproperties object) corresponding to the values in alice’s animation: var alicetiming = { duration: 3000, iterations: infinity } yo...
The structured clone algorithm - Web APIs
workers via postmessage(), storing objects with indexeddb, or copying objects for other apis. it clones by recursing through the input object while maintaining a map of previously visited references, to avoid infinitely traversing cycles. things that don't work with structured clone function objects cannot be duplicated by the structured clone algorithm; attempting to throws a data_clone_err
exception. cloning dom nodes likewise throws a data_clone_err
exception. certain object properties are not preserved: the lastindex property of regexp objects is not preserved. property descriptors, setters, getters, and similar metadata-like features are not duplicated. for example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that's ...
Window.fullScreen - Web APIs
the fullscreen property of the window interface indicates whether the window is displayed in full screen mode or not. syntax isinfullscreen = windowref.fullscreen; with chrome privileges, the property is read-write, otherwise it is read-only. bear in mind that if you try to set this property without chrome privileges, it will not throw an
exception and instead just silently fail. this is to prevent scripts designed to set this property in internet explorer from breaking. return value isinfullscreen a boolean. possible values: true: the window is in full screen mode. false: the window is not in full screen mode. notes switching between regular window and full screen will fire the "resize" event on the corresponding window. example if (window.fullscreen) { // it's f...
Window.localStorage - Web APIs
localstorage object from the same site accessed with https (e.g., https://example.com). the keys and the values are always in the utf-16 domstring format, which uses two bytes per character. as with objects, integer keys are automatically converted to strings. syntax mystorage = window.localstorage; value a storage object which can be used to access the current origin's local storage space.
exceptions securityerror the request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). for example, the user may have their browser configured to deny permission to persist data for the specified origin. example the following snippet accesses the current domain's local storage object and adds a...
Window.open() - Web APIs
e is no reliable way. what is the javascript relationship between the main window and the secondary window? the window.open() method gives a main window a reference to a secondary window; the opener property gives a secondary window a reference to its main window. i cannot access the properties of the new secondary window. i always get an error in the javascript console saying "error: uncaught
exception: permission denied to get property <property_name or method_name>. why is that? it is because of the cross-domain script security restriction (also referred as the "same origin policy"). a script loaded in a window (or frame) from a distinct origin (domain name) cannot get nor set properties of another window (or frame) or the properties of any of its html objects coming from another distinct or...
window.postMessage() - Web APIs
the message, using the origin and possibly source properties. this cannot be overstated: failure to check the origin and possibly source properties enables cross-site scripting attacks. as with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postmessage to detect when an event handler listening for events sent by postmessage throws an
exception. postmessage() schedules the messageevent to be dispatched only after all pending execution contexts have finished. for example, if postmessage() is invoked in an event handler, that event handler will run to completion, as will any remaining handlers for that same event, before the messageevent is dispatched. the value of the origin property of the dispatched event is not affected by the curre...
Window.sessionStorage - Web APIs
storage object from the same site accessed with https (e.g., https://example.com). the keys and the values are always in the utf-16 domstring format, which uses two bytes per character. as with objects, integer keys are automatically converted to strings. syntax mystorage = window.sessionstorage; value a storage object which can be used to access the current origin's session storage space.
exceptions securityerror the request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). for example, the user may have their browser configured to deny permission to persist data for the specified origin. example the following snippet accesses the current origin's session storage object and adds...
WindowOrWorkerGlobalScope.atob() - Web APIs
ample, you can encode, transmit, and decode control characters such as ascii values 0 through 31. for use with unicode or utf-8 strings, see the note on "unicode strings" in the page for btoa(). syntax var decodeddata = scope.atob(encodeddata); parameters encodeddata a binary string contains an base64 encoded data. return value an ascii string containing decoded data from encodeddata.
exceptions dom
exception (name: invalidcharactererror) throws if encodeddata is not valid base64. example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it. specifications ...
WindowOrWorkerGlobalScope.btoa() - Web APIs
ich may otherwise cause communication problems, transmit it, then use the atob() method to decode the data again. for example, you can encode control characters such as ascii values 0 through 31. syntax var encodeddata = scope.btoa(stringtoencode); parameters stringtoencode the binary string to encode. return value an ascii string containing the base64 representation of stringtoencode.
exceptions invalidcharactererror the string contained a character that did not fit in a single byte. see "unicode strings" below for more detail. example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string unicode strings the btoa() function takes a javascript string as a parameter. in javascript strings are repres...
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.cleartimeout()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html living standardthe definition of 'cleartimeout()' in that specification. living standard ...
WindowOrWorkerGlobalScope.fetch() - Web APIs
2tjllusrsz273h2nfse=). keepalive the keepalive option can be used to allow the request to outlive the page. fetch with the keepalive flag is a replacement for the navigator.sendbeacon() api. signal an abortsignal object instance; allows you to communicate with a fetch request and abort it if desired via an abortcontroller. return value a promise that resolves to a response object.
exceptions aborterror the request was aborted due to a call to the abortcontroller method abort() method. typeerror the specified url string includes user credentials. this information should instead be provided using an authorization header. 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() c...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
; when queuemicrotask() isn't available the code below is basically a monkey-patch for queuemicrotask() for modern engines. it creates a microtask by using a promise that resolves immediately. 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. living standard initial definition ...
Worker() - Web APIs
redentials: a domstring specifying the type of credentials to use for the worker. the value can be omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring specifying an identifying name for the dedicatedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes.
exceptions a securityerror is raised if the document is not allowed to start workers, e.g. if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. examples the following code snippet shows creation of a worker object u...
WorkerGlobalScope.importScripts() - Web APIs
the importscripts() method of the workerglobalscope interface synchronously imports one or more scripts into the worker's scope. syntax self.importscripts('foo.js'); self.importscripts('foo.js', 'bar.js', ...); parameters a comma-separated list of domstring objects representing the scripts to be imported. these paths are relative to html document base url. return value none.
exceptions networkerror imported scripts were not served with a valid javascript mime type (i.e. text/javascript). 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() bei...
WorkerGlobalScope - Web APIs
ecated methods workerglobalscope.close() discards any tasks queued in the workerglobalscope's event loop, effectively closing this particular scope. in newer browser versions, close() is available on dedicatedworkerglobalscope and sharedworkerglobalscope instead. 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). example you won't access workerglobalscope directly in your code; however, its properties and methods are inherited by more specific global scopes such as dedicatedworkerglobalscope and sharedworkerglobalscope. for example, you could import another script into the worker and print out the contents of the worker scope's navigator object using the following two lin...
Worklet.addModule() - Web APIs
ons: credentials: a requestcredentials value that indicates whether to send credentials (e.g. cookies and http authentification) when loading the module. can be one of "omit", "same-origin", or "include". defaults to "same-origin". see also request.credentials. return value a promise that resolves once the module from the given url has been added. the promise doesn't return any value.
exceptions if addmodule() fails, it rejects the promise, delivering one of the following errors to the rejection handler. aborterror the specified script is invalid or could not be loaded. syntaxerror the specified moduleurl is invalid. examples audioworklet example const audioctx = new audiocontext(); const audioworklet = audioctx.audioworklet; await audioworklet.addmodule('modules/bypassfilter...
WritableStream.abort() - Web APIs
the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. syntax var promise = writablestream.abort(reason); parameters reason a domstring providing a human-readable reason for the abort. return value a promise, which fulfills with the value given in the reason parameter.
exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... // abort the stream later on, when required writablestream.abort(); specifications specification status comment st...
WritableStream.getWriter() - Web APIs
the getwriter() method of the writablestream interface returns a new instance of writablestreamdefaultwriter and locks the stream to that instance. while the stream is locked, no other writer can be acquired until this one is released. syntax var writer = writablestream.getwriter(); parameters none. return value a writablestreamdefaultwriter object instance.
exceptions typeerror the stream you are trying to create a writer for is not a writablestream. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() meth...
WritableStreamDefaultController.error() - Web APIs
urn a rejected promise from one of the underlying sink’s methods. however, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. syntax writablestreamdefaultcontroller.error(e); parameters e a domstring representing the error you want future interactions to fail with. return value undefined.
exceptions typeerror the stream you are trying to error is not a writablestream. examples const writablestream = new writablestream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('my error is broken'); }, write(chunk, controller) { ... }, close(controller) { ... }, abort(err) { ... } }); specifications ...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
tor creates a new writablestreamdefaultwriter object instance. note: you generally wouldn't use this constructor manually; instead, you'd use the writablestream.getwriter() method. syntax var writablestreamdefaultwriter = new writablestreamdefaultwriter(stream); parameters stream the writablestream to be written to. return value an instance of the writablestreamdefaultwriter object.
exceptions typeerror the provided stream value is not a writablestream, or it is locked to another writer already. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. 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, whi...
WritableStreamDefaultWriter.abort() - Web APIs
er is active, the abort() method behaves the same as that for the associated stream (writablestream.abort()). if not, it returns a rejected promise. syntax var promise = writablestreamdefaultwriter.abort(reason); parameters reason optional a domstring representing a human-readable reason for the abort. return value a promise, which fulfills with the value given in the reason parameter.
exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... // abort the stream when desired writer.abort.then((reason) => { console.log(reason); }) s...
WritableStreamDefaultWriter.close() - Web APIs
invoking the close behavior. during this time any further attempts to write will fail (without erroring the stream). syntax var promise = writablestreamdefaultwriter.close(); parameters none. return value a promise, which fulfills with the undefined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process.
exceptions typeerror the stream you are trying to close is not a writablestream. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. 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 writable...
WritableStreamDefaultWriter.desiredSize - Web APIs
iter interface returns the desired size required to fill the stream's internal queue. syntax var desiredsize = writablestreamdefaultwriter.desiredsize; value an integer. note that this can be negative if the queue is over-full. the value will be null if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed.
exceptions typeerror the writer’s lock is released. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... // return stream's desired size let size = writer.desiredsize; specifications specification status comment stre...
WritableStreamDefaultWriter.write() - Web APIs
, and not necessarily that it is safely saved to its ultimate destination. syntax var promise = writablestreamdefaultwriter.write(chunk); parameters chunk a block of binary data to pass to the writablestream. return value a promise, which fulfills with the undefined upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated.
exceptions typeerror the target stream is not a writable stream, or it does not have an owner. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. 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 instan...
Using XMLHttpRequest - Web APIs
}); if you want to know if the current page has changed, please read the article about document.lastmodified. cross-site xmlhttprequest modern browsers support cross-site requests by implementing the cross-origin resource sharing (cors) standard. as long as the server is configured to allow requests from your web application's origin, xmlhttprequest will work. otherwise, an invalid_access_err
exception is thrown. bypassing the cache a cross-browser compatible approach to bypassing the cache is appending a timestamp to the url, being sure to include a "?" or "&" as appropriate. for example: http://foo.com/bar.html -> http://foo.com/bar.html?12345 http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345 as the local cache is indexed by url, this causes every request to ...
XMLHttpRequest.open() - Web APIs
he url to send the request to. async optional an optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. if this value is false, the send() method does not return until the response is received. if true, notification of a completed transaction is provided using event listeners. this must be true if the multipart attribute is true, or an
exception will be thrown. note: synchronous requests on the main thread can be easily disruptive to the user experience and should be avoided; in fact, many browsers have deprecated synchronous xhr support on the main thread entirely. synchronous requests are permitted in workers. user optional the optional user name to use for authentication purposes; by default, this is the null value. password opt...
XMLHttpRequest.response - Web APIs
ar body = xmlhttprequest.response; value an appropriate object based on the value of responsetype. 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. the value is null if the request is not yet complete or was unsuccessful, with the
exception that when reading text data using a responsetype of "text" or the empty string (""), the response can contain the response so far while the request is still in the loading readystate (3). the response types are described below. "" an empty responsetype string is treated the same as "text", the default type. arraybuffer the response is a javascript arraybuffer containing binary data. blob ...
XMLHttpRequest.responseText - Web APIs
if the request has not yet been sent by calling send(). while handling an asynchronous request, the value of responsetext always has the current content received from the server, even if it's incomplete because the data has not been completely received yet. you know the entire content has been received when the value of readystate becomes xmlhttprequest.done (4), and status becomes 200 ("ok").
exceptions invalidstateerror the xmlhttprequest.responsetype is not set to either the empty string or "text". since the responsetext property is only valid for text content, any other value is an error condition. example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); // if specified, responsetype must be empty string or "text" xhr.responsetype = 'text'; xhr.onload = function () ...
XMLHttpRequest.responseType - Web APIs
. see html in xmlhttprequest to learn more about using xhr to fetch html content. json the response is a javascript object created by parsing the contents of received data as json. text the response is a text in a domstring object. ms-stream the response is part of a streaming download; this response type is only allowed for download requests, and is only supported by internet explorer.
exceptions invalidaccesserror an attempt was made to change the value of responsetype on anxmlhttprequest which is in synchronous mode but not in a worker. for additional details, see synchronous xhr restrictions below. usage notes synchronous xhr restrictions you cannot change the value of responsetype in a synchronous xmlhttprequest except when the request belongs to a worker. this restriction is...
XMLHttpRequest.responseXML - Web APIs
urls. if the server doesn't specify the content-type as "text/xml" or "application/xml", you can use xmlhttprequest.overridemimetype() to parse it as xml anyway. this property isn't available to workers. syntax var data = xmlhttprequest.responsexml; value a document from parsing the xml or html received using xmlhttprequest, or null if no data was received or if the data is not xml/html.
exceptions invalidstateerror the responsetype isn't either "document" or an empty string. example var xhr = new xmlhttprequest; xhr.open('get', '/server'); // if specified, responsetype must be empty string or "document" xhr.responsetype = 'document'; // force the response to be parsed as xml xhr.overridemimetype('text/xml'); xhr.onload = function () { if (xhr.readystate === xhr.done && xhr.sta...
XMLHttpRequest.send() - Web APIs
d before being sent. an xmlhttprequestbodyinit, which per the fetch spec can be a blob, buffersource, formdata, urlsearchparams, or usvstring object. null if no value is specified for the body, a default value of null is used. the best way to send binary content (e.g. in file uploads) is by using an arraybufferview or blob in conjunction with the send() method. return value undefined.
exceptions
exception description invalidstateerror send() has already been invoked for the request, and/or the request is complete. networkerror the resource type to be fetched is a blob, and the method is not get. example: get var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.onload = function () { // request finished. do processing h...
XMLHttpRequest.setRequestHeader() - Web APIs
ader has been set using this, an accept header with the type "*/*" is sent with the request when send() is called. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. note: for your custom fields, you may encounter a "not allowed by access-control-allow-headers in preflight response"
exception when you send requests across domains. in this situation, you need to set up the access-control-allow-headers in your response header at server side. syntax xmlhttprequest.setrequestheader(header, value) parameters header the name of the header whose value is to be set. value the value to set as the body of the header. return value undefined. specifications specification ...
XPathEvaluator.createExpression() - Web APIs
athevaluator.createexpression(expression, resolver); parameters expression a domstring representing representing the xpath expression to be created. resolver optional permits translation of all prefixes, including the xml namespace prefix, within the xpath expression into appropriate namespace uris. return value a xpathexpression representing the compiled form of the xpath expression.
exceptions invalid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpath
exception of type invalid_expression_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a dom
exception of type namespace_error is raised. example the following example shows the use of the evaluate() m...
XPathResult.booleanValue - Web APIs
the read-only booleanvalue property of the xpathresult interface returns the boolean value of a result with xpathresult.resulttype being boolean_type. note: this feature is available in web workers. syntax var value = result.booleanvalue; return value the return value is the boolean value of the xpathresult returned by document.evaluate().
exceptions type_err in case xpathresult.resulttype is not boolean_type, an xpath
exception of type type_err is thrown. example the following example shows the use of the booleanvalue property. html <div>xpath example</div> <p>text is 'xpath example': <output></output></p> javascript var xpath = "//div/text() = 'xpath example'"; var result = document.evaluate(xpath, document, null, xpathresult.boolean_type, null); document.queryselector("output").t...
XPathResult.iterateNext() - Web APIs
the iteratenext() method of the xpathresult interface iterates over a node set result and returns the next node from it or null if there are no more nodes. syntax var node = result.iteratenext(); return value the next node within the node set of the xpathresult.
exceptions type_err in case xpathresult.resulttype is not unordered_node_iterator_type or ordered_node_iterator_type, an xpath
exception of type type_err is thrown. invalid_state_err if the document is mutated since the result was returned, an xpath
exception of type invalid_state_err is thrown. example the following example shows the use of the iteratenext() method. html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath,...
XPathResult.numberValue - Web APIs
the read-only numbervalue property of the xpathresult interface returns the numeric value of a result with xpathresult.resulttype being number_type. note: this feature is available in web workers. syntax var value = result.numbervalue; return value the return value is the numeric value of the xpathresult returned by document.evaluate().
exceptions type_err in case xpathresult.resulttype is not number_type, an xpath
exception of type type_err is thrown. example the following example shows the use of the numbervalue property. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var xpath = "count(//div)"; var result = document.evaluate(xpath, document, null, xpathresult.number_type, null); document.queryselector("output").textcontent = result.n...
XPathResult.singleNodeValue - Web APIs
odevalue property of the xpathresult interface returns a node value or null in case no node was matched of a result with xpathresult.resulttype being any_unordered_node_type or first_ordered_node_type. note: this feature is available in web workers. syntax var value = result.singlenodevalue; return value the return value is the node value of the xpathresult returned by document.evaluate().
exceptions type_err in case xpathresult.resulttype is not any_unordered_node_type or first_ordered_node_type, an xpath
exception of type type_err is thrown. example the following example shows the use of the singlenodevalue property. html <div>xpath example</div> <div>tag name of the element having the text content 'xpath example': <output></output></div> javascript var xpath = "//*[text()='xpath e...
XPathResult.snapshotItem() - Web APIs
method of the xpathresult interface returns an item of the snapshot collection or null in case the index is not within the range of nodes. unlike the iterator result, the snapshot does not become invalid, but may not correspond to the current document if it is mutated. syntax var node = result.snapshotitem(i); return value the node at the given index within the node set of the xpathresult.
exceptions type_err in case xpathresult.resulttype is not unordered_node_snapshot_type or ordered_node_snapshot_type, an xpath
exception of type type_err is thrown. example the following example shows the use of the snapshotitem() method. html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, d...
XPathResult.snapshotLength - Web APIs
the read-only snapshotlength property of the xpathresult interface represents the number of nodes in the result snapshot. note: this feature is available in web workers. syntax var snapshotlength = result.snapshotlength; return value an integer value representing the number of nodes in the result snapshot.
exceptions type_err in case xpathresult.resulttype is not unordered_node_snapshot_type or ordered_node_snapshot_type, an xpath
exception of type type_err is thrown. example the following example shows the use of the snapshotlength property. html <div>xpath example</div> <div>number of matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); document.queryselector("out...
XPathResult.stringValue - Web APIs
the read-only stringvalue property of the xpathresult interface returns the string value of a result with xpathresult.resulttype being string_type. note: this feature is available in web workers. syntax var value = result.stringvalue; return value the return value is the string value of the xpathresult returned by document.evaluate().
exceptions type_err in case xpathresult.resulttype is not string_type, an xpath
exception of type type_err is thrown. example the following example shows the use of the stringvalue property. html <div>xpath example</div> <div>text content of the <div> above: <output></output></div> javascript var xpath = "//div/text()"; var result = document.evaluate(xpath, document, null, xpathresult.string_type, null); document.queryselector("output").textconte...
XRFrame.getViewerPose() - Web APIs
esents the difference between two spaces. syntax var xrviewerpose = xrframe.getviewerpose(referencespace); parameters referencespace an xrreferencespace object specifying the space to use as the reference point or base for the computation of the viewer's current pose. return value a xrviewerpose describing the viewer's position and orientation relative to the specified reference space.
exceptions invalidstateerror a dom
exception 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. viewerpose = xrfram...
XRReferenceSpace - Web APIs
tual world using a specified tracking behavior. the tracking behavior is defined by the selected reference space type. it expands upon the base class, xrspace, by adding support for several different tracking behaviors as well as to request a new reference space which describes the offset transform between the tracked object and another location in the world. all reference spaces—with the sole
exception being bounded reference spaces—are described using the xrreferencespace type. bounded spaces are implemented as xrboundedreferencespace objects. these are special spaces which let you establish a perimeter within which it's "safe" for the viewer to move. for xr systems that allow the user to physically move around, such as those that track movement with a real-world camera, this boundary establ...
XRRigidTransform() - Web APIs
is facing. the default value for orientation is {x: 0, y: 0, z: 0, w: 1}. the specified orientation gets normalized if it's not already. return value a new xrrigidtransform object which has been initialized to represent a transform matrix that would adjust the position and orientation of an object from the origin to the specified position and facing in the direction indicated by orientation.
exceptions typeerror the value of the w coordinate in the specified position is not 1.0. examples in this example, the beginning of the animation of a scene is shown, starting with a request for a reference space of a given type, then shifting the coordinate system based on a transform before requesting the first animation frame. let animationframerequestid = 0; xrsession.requestreferencespace("lo...
XRSession.requestReferenceSpace() - Web APIs
ces of xrsession, both immersive and inline, though it's most useful for inline sessions. it's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace return value a promise that resolves with an xrreferencespace object.
exceptions rather than throwing true
exceptions, requestreferencespace() rejects the returned promise with a dom
exception whose name is found in the list below: notsupportederror the requested reference space is not supported. specifications specification status comment webxr device apithe definition of 'requestreferencespace()' in that specification. working draft ini...
XRSession.updateRenderState() - Web APIs
t field of view, in radians, to be used when computing the projection matrix for an inline xrsession. the projection matrix calculation also takes into account the output canvas's aspect ratio. this property must not be specified for immersive sessions, so the value is null by default for immersive sessions. the default value is otherwise π * 0.5 (half of the value of pi). return value none.
exceptions this method may throw any of the following
exceptions. these are true
exceptions, since this method does not return a promise. invalidstateerror this may occur for one of the following reasons: the xrsession has already ended, so you cannot change its render state. the baselayer specified in newstate was created by an xrsession other than the one on which updaterenderstate() was ca...
XRSpace - Web APIs
ble region of the space. the origin of an xrboundedreferencespace is always at floor level, with its x and z coordinates typically defaulting to a location near the room's center. xrreferencespace represents a reference space which is typically expected to remain static for the duration of the xrsession. while objects may move within the space, the space itself remains fixed in place. there are
exceptions to this static nature; most commonly, an xrreferencespace may move in order to adjust based on reconfiguration of the user's headset or other motion-sensitive device. properties the xrspace interface defines no properties of its own; however, it does inherit the properties of its parent interface, eventtarget. methods the xrspace interface provides no methods of its own. however, it inherit...
XRSystem: requestSession() - Web APIs
special hardware and should be avalable on any user agent offering webxr api support. sessioninit optional a xrsessioninit object providing options to configure the new xrsession. see specifying session options for details on how to configure a webxr session. return value a promise that resolves with an xrsession object if the device and user agent support the requested mode and features.
exceptions this method doesn't throw true
exceptions; instead, it rejects the returned promise, passing into it a dom
exception whose name is one of the following: invalidstateerror the requested session mode is immersive-vr but there is already an immersive vr session either currently active or in the process of being set up. there can only be one immersive vr session at a time. notsupportederror th...
XRWebGLLayer() - Web APIs
hich, if true, requests that the new layer include a stencil buffer. otherwise, no stencil buffer is allocated. the default is false. return value a newly-created xrwebgllayer which links the specified xrsession to the webgl context given by context, which will be used as the renderer for the session. any options specified in layerinit are used to tailor the rendering system's configuration.
exceptions invalidstateerror the new xrwebgllayer could not be created due to one of a number of possible state errors: the xrsession specified by session has already been stopped. the specified webgl context, context, has been lost for any reason, such as a gpu switch or reset. the specified session is immersive but the context is not webxr compatible. operationerror the resources (in...
XRWebGLLayer.getViewport() - Web APIs
ramebuffer into which the scene should be rendered for the eye represented by the view. syntax let viewport = xrwebgllayer.getviewport(view); parameters view an xrview object indicating the view for which the viewport is to be returned. return value a xrviewport object representing the viewport which will restrict drawing to the portion of the layer corresponding to the specified view.
exceptions invalidstateerror either the specified view is not in an active xrframe or that xrframe and the xrwebgllayer are not part of the same webxr session. 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...
msGetRegionContent - Web APIs
is positioned in the region. this proprietary method is specific to internet explorer browser. syntax var retval = element.msgetregioncontent(); parameters retval [out, reval] type: msrangecollection the name of the property to enable. return value type: boolean returned ranges are sorted by document position and do not overlap. if an element is not a region, this method throws a dom
exception with the invalidaccesserror error code. this is only available to regions that are document elements and not to regions that are pseudo-elements. see also microsoft api extensions ...
ARIA: timer role - Accessibility
lement that contains additional instructions for navigating or operating this element. aria-roledescription used to give the timer a more descriptive role text for screen readers to speak. this should be localized. keyboard interactions keyboard interaction is xxx. focus is being managed via xxx. the tab , space and enter keys, as well as escape , must be handled by the application. the one
exception is if focus xxx. required javascript features keypress used to handle keyboard input and control the focus click, touch handle as appropriate for your widget as well changing attribute values aria-activedescendant is used to manage the focus inside the application container. set in response to keyboard or other application events that change focus or point of interaction. the timer ro...
ARIA: application role - Accessibility
implemented. in a slides application, for example, a widget could be created that uses the arrow keys to position elements on the slide, and uses audio feedback via an aria live region to communicate the position and overlap status with other objects. focus is being managed via aria-activedescendant. the tab , space and enter keys, as well as escape , must be handled by the application. the one
exception is if focus is set to a standard widget inside the application that supports keyboard navigation from the browser, for example an input element. required javascript features keypress used to handle keyboard input and control the focus click, touch handle as appropriate for your widget as well changing attribute values aria-activedescendant is used to manage the focus inside the applicati...
Keyboard-navigable JavaScript widgets - Accessibility
links, form controls) get focused. with the tabindex global attribute, authors can make other elements focusable, too. when set to 0, the element becomes focusable by keyboard and script. when set to -1, the element becomes focusable by script, but it does not become part of the keyboard focus order. the order in which elements gain focus when using a keyboard, is the source order by default. in
exceptional circumstances, authors may want to redefine the order. to do this, authors can set tabindex to any positive number. warning: avoid using positive values for tabindex. elements with a positive tabindex are put before the default interactive elements on the page, which means page authors will have to set (and maintain) tabindex values for all focusable elements on the page whenever they use on...
Keyboard - Accessibility
is not working at the moment, or who simply prefer to use a keyboard for input whenever possible. focusable elements should have interactive semantics if an element can be focused using the keyboard, then it should be interactive; that is, the user should be able to do something to it and produce a change of some kind (for example, activating a link or changing an option). note: one important
exception to this rule is if the element has role="document" applied to it, inside an interactive context (such as role="application"). 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"). most interactive elements are focusable by default; you can make an element focusable by adding a tabindex=0 attribute ...
Perceivable - Accessibility
readability. text should not be fully justified (e.g., text-align: justify;). line height should be at least 1.5 times the text size within paragraphs (e.g., line-height: 1.5;), and at least 2.25 times the text size between paragraphs (e.g., padding: 2.25rem;). when the text size is doubled, the content should not need to be scrolled. 1.4.9 images of text (no
exception) (aaa) text should not be presented as part of an image unless it is purely decoration (i.e., it does not convey any content) or cannot be presented in any other way. 1.4.10 reflow (aa) added in 2.1 no horizontal scrolling for left-to-right languages (like english) or right-to-left languages (like arabic) no vertical scrolling for top-to-bottom languages (lik...
::cue-region - CSS: Cascading Style Sheets
the ::cue-region css pseudo-element matches webvtt cues within a selected element. this can be used to style captions and other cues in media with vtt tracks. ::cue-region { color: yellow; font-weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only
exception is that background and its shorthand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. syntax ::cue-region | ::cue-region( <selector> ) permitted properties rules whose selectors include this element may only use the following css properties: background background-attachment background-clip background-color background-image background-origin background-position background-repeat background-size c...
::cue - CSS: Cascading Style Sheets
the ::cue css pseudo-element matches webvtt cues within a selected element. this can be used to style captions and other cues in media with vtt tracks. ::cue { color: yellow; font-weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only
exception is that background and its longhand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. syntax ::cue | ::cue( <selector> ) permitted properties rules whose selectors include this element may only use the following css properties: background background-attachment background-clip background-color background-image background-origin background-position background-repeat background-size color font font-family font-si...
light-level - CSS: Cascading Style Sheets
dim the device is used in a dim environment, where excessive contrast and brightness would be distracting or uncomfortable to the reader. for example: night time, or a dimly illuminated indoor environment. normal the device is used in a environment with a light level in the ideal range for the screen, and which does not necessitate any particular adjustment. washed the device is used in an
exceptionally bright environment, causing the screen to be washed out and difficult to read. for example: bright daylight. examples this code will likely not work on any devices (device compatibility is low). @media (light-level: normal) { p { background: url("texture.jpg"); color: #333; } } @media (light-level: dim) { p { background: #222; color: #ccc; } } @media (light-lev...
Box alignment in grid layout - CSS: Cascading Style Sheets
the align-self and justify-self properties as a group. this means that you can set alignment for all of your grid items at once, then override any items that need a different alignment by applying the align-self or justify-self property to the rules for the individual grid items. the initial value for align-self and justify-self is stretch so the item will stretch over the entire grid area. the
exception to this rule is where the item has an intrinsic aspect ratio, for example an image. in this case the item will be aligned to start in both dimensions in order that the image is not distorted. content alignment justify-content align-content place-content these properties deal with aligning the tracks of the grid when there is extra space to distribute. this scenario will occur if the track...
<basic-shape> - CSS: Cascading Style Sheets
this is the closest side in the radius dimension. farthest-side uses the length from the center of the shape to the farthest side of the reference box. for circles, this is the farthest side in any dimension. for ellipses, this is the farthest side in the radius dimension. description computed values of basic shapes the values in a <basic-shape> function are computed as specified, with these
exceptions: omitted values are included and compute to their defaults. a <position> value in circle() or ellipse() is computed as a pair of offsets (horizontal then vertical) from the top left origin, each given as a combination of an absolute length and a percentage. a <border-radius> value in inset() is computed as an expanded list of all eight <length> or percentage values. interpolation of basic...
drop-shadow() - CSS: Cascading Style Sheets
e box-shadow property. the box-shadow property creates a rectangular shadow behind an element's entire box, while the drop-shadow() filter function creates a shadow that conforms to the shape (alpha channel) of the image itself. syntax drop-shadow(offset-x offset-y blur-radius color) the drop-shadow() function accepts a parameter of type <shadow> (defined in the box-shadow property), with the
exception that the inset keyword and spread parameters are not allowed. parameters offset-x offset-y (required) two <length> values that determine the shadow offset. offset-x specifies the horizontal distance, where negative values place the shadow to the left of the element. offset-y specifies the vertical distance, where negative values place the shadow above the element. if both values are 0, the s...
filter - CSS: Cascading Style Sheets
al-align: top; width:25%; height:auto; } #img3 { height:100%; } drop-shadow() the drop-shadow() function applies a drop shadow effect to the input image. a drop shadow is effectively a blurred, offset version of the input image's alpha mask drawn in a particular color, composited below the image. the function accepts a parameter of type <shadow> (defined in css3 backgrounds), with the
exception that the inset keyword is not allowed. this function is similar to the more established box-shadow property; the difference is that with filters, some browsers provide hardware acceleration for better performance. the parameters of the <shadow> parameter are as follows: <offset-x> <offset-y> (required) these are two <length> values to set the shadow offset. <offset-x> specifies the horizontal...
float - CSS: Cascading Style Sheets
lock table-footer-group block inline-flex flex inline-grid grid other unchanged note: if you're referring to this property from javascript as a member of the htmlelement.style object, modern browsers support float, but in older browsers you have to spell it as cssfloat, with internet explorer versions 8 and older using stylefloat. this was an
exception to the rule, that the name of the dom member is the camel-case name of the dash-separated css name (due to the fact that "float" is a reserved word in javascript, as seen in the need to escape "class" as "classname" and escape <label>'s "for" as "htmlfor"). syntax /* keyword values */ float: left; float: right; float: none; float: inline-start; float: inline-end; /* global values */ float: inh...
font-size - CSS: Cascading Style Sheets
often called compounding. rems rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. in other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent, thereby eliminating compounding. the css below is nearly identical to the previous example. the only
exception is that the unit has been changed to rem. html { font-size: 62.5%; /* font-size 1em = 10px on default browser settings */ } span { font-size: 1.6rem; } then we apply this css to the same html, which looks like this: <span>outer <span>inner</span> outer</span> in this example, the words “outer inner outer” are all displayed at 16px (assuming that the browser's font-size has been lef...
image-orientation - CSS: Cascading Style Sheets
css property specifies a layout-independent correction to the orientation of an image. it should not be used for any other orientation adjustments; instead, the transform property should be used with the rotate <transform-function>. warning: this property is deprecated in the specification. its functionality may be moved into properties on the <img> and/or <picture> elements, with the possible
exception of from-image. the flip and <angle> values were made obsolete in firefox 63. /* keyword values */ image-orientation: none; image-orientation: from-image; /* use exif data from the image */ /* global values */ image-orientation: inherit; image-orientation: initial; image-orientation: unset; /* obsolete values. obsolete since gecko 63 */ image-orientation: 90deg; /* rotate 90deg */ image-orient...
outline - CSS: Cascading Style Sheets
/* color | style | width */ outline: green solid 3px; /* global values */ outline: inherit; outline: initial; outline: unset; the outline property may be specified using one, two, or three of the values listed below. the order of the values does not matter. note: the outline will be invisible for many elements if its style is not defined. this is because the style defaults to none. a notable
exception is input elements, which are given default styling by browsers. values <'outline-color'> sets the color of the outline. defaults to currentcolor if absent. see outline-color. <'outline-style'> sets the style of the outline. defaults to none if absent. see outline-style. <'outline-width'> sets the thickness of the outline. defaults to medium if absent. see outline-width. description b...
Creating a cross-browser video player - Developer guides
ted and vice versa. support for the different prefixed versions of the relevant action are checked in order to call the correct one. interestingly document must be used for exiting/cancelling fullscreen mode, whereas any html element can request fullscreen mode, here the videocontainer is used as it also contains the custom controls which should also appear with the video in fullscreen mode. the
exception to this is safari 5.1, which will only allow webkitrequestfullscreen to be called on the <video> element. the custom controls will only appear on this browser in fullscreen mode with some webkit specific css: the default browser controls have to be hidden with video::-webkit-media-controls { display:none !important; } the custom controls container needs to have a special z-index value: .contr...
Creating and triggering events - Developer guides
events can be created with the event constructor as follows: const event = new event('build'); // listen for the event. elem.addeventlistener('build', function (e) { /* ... */ }, false); // dispatch the event. elem.dispatchevent(event); the above code example uses the eventtarget.dispatchevent() method. this constructor is supported in most modern browsers (with internet explorer being the
exception). for a more verbose approach (which works with internet explorer), see the old-fashioned way below. adding custom data – customevent() to add more data to the event object, the customevent interface exists and the detail property can be used to pass custom data. for example, the event could be created as follows: const event = new customevent('build', { detail: elem.dataset.time }); this ...
Localizations and character encodings - Developer guides
n doubt, use windows-1252 as the fallback encoding. specifying the heuristic detection mode the heuristic detection mode is specified by the preference intl.charset.detector in intl.properties. the setting must be left blank for all locales other than russian, ukrainian and japanese. do not under any circumstances specify the "universal" detector. it is not actually universal despite its name!
exception for minority languages if the localization is for minority language and the users are typically literate in the majority language of the region and read web content written in the majority language very often, it is appropriate to specify the fallback encoding and the heuristic detection mode to be the same as for the localization for the majority language of the region. for example, for a local...
disabled - HTML: Hypertext Markup Language
fieldset; if there is no containing element with the disabled attribute set, and the control itself does not have the attribute, then the control is enabled. if declared on an <optgroup>, the select is still interactive (unless otherwise disabled), but none of the items in the option group are selectable. note: if a <fieldset> is disabled, the descendant form controls are all disabled, with the
exception of form controls within the <legend>. when a supporting element has the disabled attribute applied, the :disabled pseudo-class also applies to it. conversely, elements that support the disabled attribute but don't have the attribute set match the :enabled pseudo-class. this boolean attribute prevents the user from interacting with the button. if this attribute isn't set, the button can still b...
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
from a variety of sources, including images or videos retrieved from other hosts, it's inevitable that security problems may arise. as soon as you draw into a canvas any data that was loaded from another origin without cors approval, the canvas becomes tainted. a tainted canvas is one which is no longer considered secure, and any attempts to retrieve image data back from the canvas will cause an
exception to be thrown. if the source of the foreign content is an html <img> or svg <svg> element, attempting to retrieve the contents of the canvas isn't allowed. if the foreign content comes from an image obtained from either as htmlcanvaselement or imagebitmap, and the image source doesn't meet the same origin rules, attempts to read the canvas's contents are blocked. calling any of the following on...
<noframes>: The Frame Fallback element - HTML: Hypertext Markup Language
the obsolete html no frames or frame fallback element, <noframes>, provides content to be presented in browsers that don't support (or have disabled support for) the <frame> element. although most commonly-used browsers support frames, there are
exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers. a <noframes> element can contain any html elements that are allowed within the body of an html document, with the
exception of the <frameset> and <frame> elements, since using frames when they aren't supported doesn't make sense. <noframes> can be used to present a message explaining that the user's browser doesn't support frames, but ideally should be used to present an alternate form of the site that doesn't use frames but still offers th...
Cross-Origin Resource Sharing (CORS) - HTTP
value of the access-control-allow-origin header was "*". but it does not fail: because the value of the access-control-allow-origin header is "http://foo.example" (an actual origin) rather than the "*" wildcard, the credential-cognizant content is returned to the invoking web content. note that the set-cookie response header in the example above also sets a further cookie. in case of failure, an
exception—depending on the api used—is raised. third-party cookies note that cookies set in cors responses are subject to normal third-party cookie policies. in the example above, the page is loaded from foo.example, but the cookie on line 20 is sent by bar.other, and would thus not be saved if the user has configured their browser to reject all third-party cookies. the http response headers this s...
Content Security Policy (CSP) - HTTP
to include images from any origin in their own content, but to restrict audio or video media to trusted providers, and all scripts only to a specific server that hosts trusted code. content-security-policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com here, by default, content is only permitted from the document's origin, with the following
exceptions: images may load from anywhere (note the "*" wildcard). media is only allowed from media1.com and media2.com (and not from subdomains of those sites). executable script is only allowed from userscripts.example.com. example 4 a web site administrator for an online banking site wants to ensure that all its content is loaded using tls, in order to prevent attackers from eavesdropping on req...
Using HTTP cookies - HTTP
he samesite attribute lets servers require that a cookie shouldn't be sent with cross-origin requests (where site is defined by the registrable domain), which provides some protection against cross-site request forgery attacks (csrf). it takes three possible values: strict, lax, and none. with strict, the cookie is sent only to the same site as the one that originated it; lax is similar, with an
exception for when the user navigates to a url from an external site, such as by following a link; none has no restrictions on cross-site requests. here is an example: set-cookie: mykey=myvalue; samesite=strict the values of samesite attribute are case-insensitive. browsers are migrating to have cookies default to samesite=lax. if a cookie is needed to be sent cross-origin, opt out of the samesite res...
Feature-Policy: document-domain - HTTP
syntax feature-policy: document-domain <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
Feature-Policy: encrypted-media - HTTP
the http feature-policy header encrypted-media directive controls whether the current document is allowed to use the encrypted media extensions api (eme). when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a dom
exception. syntax feature-policy: encrypted-media <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe allow attribute only) the feature will be allowed in this iframe, as long as the docu...
Feature-Policy: midi - HTTP
syntax feature-policy: midi <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
Transfer-Encoding - HTTP
ted, separated by a comma transfer-encoding: gzip, chunked directives chunked data is sent in a series of chunks. the content-length header is omitted in this case and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format, followed by '\r\n' and then the chunk itself, followed by another '\r\n'. the terminating chunk is a regular chunk, with the
exception that its length is zero. it is followed by the trailer, which consists of a (possibly empty) sequence of entity header fields. compress a format using the lempel-ziv-welch (lzw) algorithm. the value name was taken from the unix compress program, which implemented this algorithm. like the compress program, which has disappeared from most unix distributions, this content-encoding is used by almo...
HTTP
odes indicate whether a specific http request has been successfully completed. responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors. csp directives the content-security-policy response header fields allows web site administrators to control resources the user agent is allowed to load for a given page. with a few
exceptions, policies mostly involve specifying server origins and script endpoints. tools & resources helpful tools and resources for understanding and debugging http. firefox developer tools network monitor mozilla observatory a project designed to help developers, system administrators, and security professionals configure their sites safely and securely. redbot tools to check your cache-r...
Concurrency model and the event loop - JavaScript
time if the latter listens to message events. never blocking a very interesting property of the event loop model is that javascript, unlike a lot of other languages, never blocks. handling i/o is typically performed via events and callbacks, so when the application is waiting for an indexeddb query to return or an xhr request to return, it can still process other things like user input. legacy
exceptions exist like alert or synchronous xhr, but it is considered a good practice to avoid them. beware:
exceptions to the
exception do exist (but are usually implementation bugs, rather than anything else). specifications specification html living standardthe definition of 'event loops' in that specification. node.js event loop ...
ReferenceError: assignment to undeclared variable "x" - JavaScript
message referenceerror: assignment to undeclared variable "x" (firefox) referenceerror: "x" is not defined (chrome) referenceerror: variable undefined in strict mode (edge) error type referenceerror warning in strict mode only. what went wrong? a value has been assigned to an undeclared variable. in other words, there was an assignment without the var keyword. there are some differences between declared and undeclared variables, which might lead to unexpected results and that's why javascript presents an error in strict mode. ...
SyntaxError: Unexpected token - JavaScript
this might be a simple typo. message syntaxerror: expected expression, got "x" syntaxerror: expected property name, got "x" syntaxerror: expected target, got "x" syntaxerror: expected rest argument name, got "x" syntaxerror: expected closing parenthesis, got "x" syntaxerror: expected '=>' after argument list, got "x" error type syntaxerror what went wrong? a specific language construct was expected, but something else was provided. this might be a simple typo. examples expression expected for example, when chaining expressions, trailing commas are not allowed. ...
TypeError: "x" is (not) "y" - JavaScript
oftentimes, unexpected undefined or null values. message typeerror: unable to get property {x} of undefined or null reference (edge) typeerror: "x" is (not) "y" (firefox) examples: typeerror: "x" is undefined typeerror: "x" is null typeerror: "undefined" is not an object typeerror: "x" is not an object or null typeerror: "x" is not a symbol error type typeerror. what went wrong? there was an unexpected type. this occurs oftentimes with undefined or null values. also, certain methods, such as object.create() or symbol.keyfor(), require a specific type, that must be provided. ...
SyntaxError: function statement requires a name - JavaScript
message syntax error: expected identifier (edge) syntaxerror: function statement requires a name [firefox] syntaxerror: unexpected token ( [chrome] error type syntaxerror what went wrong? there is a function statement in the code that requires a name. you'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an iife, or if the function code is placed correctly in this context at all. ...
TypeError: variable "x" redeclares argument - JavaScript
message typeerror: variable "x" redeclares argument (firefox) error type typeerror warning in strict mode only. what went wrong? the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again. this might be a naming conflict and thus javascript warns about it. this error occurs as a warning in strict mode code only. in non-strict code, the redeclaration is silently ignored. examples invalid cases in this case, the variable "arg" redeclares the argument. ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
it can only be used to check if a property is in an object. message typeerror: invalid operand to 'in' (edge) typeerror: right-hand side of 'in' should be an object, got 'x' (firefox) typeerror: cannot use 'in' operator to search for 'x' in 'y' (firefox, chrome) error type typeerror what went wrong? the in operator can only be used to check if a property is in an object. you can't search in strings, or in numbers, or other primitive types. examples searching in strings unlike in other programming languages (e.g. python), you can't search in strings using the in operator. ...
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? the instanceof operator expects the right hand side operands to be a constructor object, i.e. an object which has a prototype property and is callable. ...
TypeError: 'x' is not iterable - JavaScript
message typeerror: 'x' is not iterable (firefox, chrome) typeerror: 'x' is not a function or its return value is not iterable (chrome) error type typeerror what went wrong? the value which is given as the right hand-side of for…of or as argument of a function such as promise.all or typedarray.from, is not an iterable object. an iterable can be a built-in iterable type such as array, string or map, a generator result, or an object implementing the iterable protocol. ...
Array() constructor - JavaScript
ctor, not array literals created with the bracket syntax. arraylength if the only argument passed to the array constructor is an integer between 0 and 232-1 (inclusive), this returns a new javascript array with its length property set to that number (note: this implies an array of arraylength empty slots, not slots with actual undefined values). if the argument is any other number, a rangeerror
exception is thrown. examples array literal notation arrays can be created using the literal notation: let fruits = ['apple', 'banana']; console.log(fruits.length); // 2 console.log(fruits[0]); // "apple" array constructor with a single parameter arrays can be created using a constructor with a single number parameter. an array with its length property set to that number and the array elements...
Array.prototype.reduce() - JavaScript
ect(this); // 2. let len be ? tolength(? get(o, "length")). var len = o.length >>> 0; // steps 3, 4, 5, 6, 7 var k = 0; var value; if (arguments.length >= 2) { value = arguments[1]; } else { while (k < len && !(k in o)) { k++; } // 3. if len is 0 and initialvalue is not present, // throw a typeerror
exception. if (k >= len) { throw new typeerror( 'reduce of empty array ' + 'with no initial value' ); } value = o[k++]; } // 8. repeat, while k < len while (k < len) { // a. let pk be ! tostring(k). // b. let kpresent be ? hasproperty(o, pk). // c. if kpresent is true, then // i. let kvalue be ? get(o, pk).
Array.prototype.every() - JavaScript
not defined'); } // 1. let o be the result of calling toobject passing the this // value as the argument. var o = object(this); // 2. let lenvalue be the result of calling the get internal method // of o with the argument "length". // 3. let len be touint32(lenvalue). var len = o.length >>> 0; // 4. if iscallable(callbackfn) is false, throw a typeerror
exception. if (typeof callbackfn !== 'function' && object.prototype.tostring.call(callbackfn) !== '[object function]') { throw new typeerror(); } // 5. if thisarg was supplied, let t be thisarg; else let t be undefined. if (arguments.length > 1) { t = thisarg; } // 6. let k be 0. k = 0; // 7. repeat, while k < len while (k < len) { var kvalue; ...
Array.prototype.find() - JavaScript
ject.defineproperty(array.prototype, 'find', { value: function(predicate) { // 1. let o be ? toobject(this value). if (this == null) { throw typeerror('"this" is null or not defined'); } var o = object(this); // 2. let len be ? tolength(? get(o, "length")). var len = o.length >>> 0; // 3. if iscallable(predicate) is false, throw a typeerror
exception. if (typeof predicate !== 'function') { throw typeerror('predicate must be a function'); } // 4. if thisarg was supplied, let t be thisarg; else let t be undefined. var thisarg = arguments[1]; // 5. let k be 0. var k = 0; // 6. repeat, while k < len while (k < len) { // a. let pk be ! tostring(k). // b. let kvalue be ? get...
Array.prototype.findIndex() - JavaScript
ineproperty(array.prototype, 'findindex', { value: function(predicate) { // 1. let o be ? toobject(this value). if (this == null) { throw new typeerror('"this" is null or not defined'); } var o = object(this); // 2. let len be ? tolength(? get(o, "length")). var len = o.length >>> 0; // 3. if iscallable(predicate) is false, throw a typeerror
exception. if (typeof predicate !== 'function') { throw new typeerror('predicate must be a function'); } // 4. if thisarg was supplied, let t be thisarg; else let t be undefined. var thisarg = arguments[1]; // 5. let k be 0. var k = 0; // 6. repeat, while k < len while (k < len) { // a. let pk be ! tostring(k). // b. let kvalue be ?
Array.prototype.forEach() - JavaScript
ow.) foreach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. the typical use case is to execute side effects at the end of a chain. foreach() does not mutate the array on which it is called. (however, callback may do so) there is no way to stop or break a foreach() loop other than by throwing an
exception. if you need such behavior, the foreach() method is the wrong tool. early termination may be accomplished with: a simple for loop a for...of / for...in loops array.prototype.every() array.prototype.some() array.prototype.find() array.prototype.findindex() array methods: every(), some(), find(), and findindex() test the array elements with a predicate returning a truthy value to determi...
Array.from() - JavaScript
ray-like object or iterator - not null or undefined' ); } // 4. if mapfn is undefined, then let mapping be false. var mapfn = arguments.length > 1 ? arguments[1] : void undefined; var t; if (typeof mapfn !== 'undefined') { // 5. else // 5. a if iscallable(mapfn) is false, throw a typeerror
exception. if (!iscallable(mapfn)) { throw new typeerror( 'array.from: when provided, the second argument must be a function' ); } // 5. b. if thisarg was supplied, let t be thisarg; else let t be undefined. if (arguments.length > 2) { t = arguments[2]; ...
Array.prototype.map() - JavaScript
not defined'); } // 1. let o be the result of calling toobject passing the |this| // value as the argument. var o = object(this); // 2. let lenvalue be the result of calling the get internal // method of o with the argument "length". // 3. let len be touint32(lenvalue). var len = o.length >>> 0; // 4. if iscallable(callback) is false, throw a typeerror
exception. // see: http://es5.github.com/#x9.11 if (typeof callback !== 'function') { throw new typeerror(callback + ' is not a function'); } // 5. if thisarg was supplied, let t be thisarg; else let t be undefined. if (arguments.length > 1) { t = arguments[1]; } // 6. let a be a new array created as if by the expression new array(len) // where array is the ...
ArrayBuffer() constructor - JavaScript
example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new arraybuffer(length) parameters length the size, in bytes, of the array buffer to create. return value a new arraybuffer object of the specified size. its contents are initialized to 0.
exceptions a rangeerror is thrown if the length is larger than number.max_safe_integer (>= 2 ** 53) or negative. compatibility notes starting with ecmascript 2015, arraybuffer constructors require to be constructed with a new operator. 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 c...
Atomics.add() - JavaScript
and send us a pull request. syntax atomics.add(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to add a value to. value the number to add. return value the old value at the given position (typedarray[index]).
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using add() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)t...
Atomics.and() - JavaScript
x atomics.and(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise and. value the number to compute the bitwise and with. return value the old value at the given position (typedarray[index]).
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise and operation only yields 1, if both a and b are 1. the truth table for the and operation is: a b a & b 0 0 0 0 1 0 1 0 0 1 1 1 for example...
Atomics.compareExchange() - JavaScript
tvalue) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to exchange a value. expectedvalue the value to check for equality. replacementvalue the number to exchange. return value the old value at the given position (typedarray[index]).
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using compareexchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 7; atomics.compareexchange(ta, 0, 7, 12); // returns 7, the old value atomics.load(ta, 0); // 12 specifications specificati...
Atomics.exchange() - JavaScript
a pull request. syntax atomics.exchange(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to exchange a value. value the number to exchange. return value the old value at the given position (typedarray[index]).
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using exchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.exchange(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (...
Atomics.load() - JavaScript
tps://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.load(typedarray, index) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to load from. return value the value at the given position (typedarray[index]).
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using load const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.load' i...
Atomics.notify() - JavaScript
will return 0 on non-shared arraybuffer objects. syntax atomics.notify(typedarray, index, count) parameters typedarray a shared int32array. index the position in the typedarray to wake up on. count optional the number of sleeping agents to notify. defaults to +infinity. return value returns the number of woken up agents. returns 0, if a non-shared arraybuffer object is used.
exceptions throws a typeerror, if typedarray is not a int32array. throws a rangeerror, if index is out of bounds in the typedarray. examples using notify given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however, once t...
Atomics.or() - JavaScript
ntax atomics.or(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise or. value the number to compute the bitwise or with. return value the old value at the given position (typedarray[index]).
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise or operation yields 1, if either a or b are 1. the truth table for the or operation is: a b a | b 0 0 0 0 1 1 1 0 1 1 1 1 for example, a bi...
Atomics.store() - JavaScript
teractive-examples and send us a pull request. syntax atomics.store(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to store a value in. value the number to store. return value the value that has been stored.
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using store() var sab = new sharedarraybuffer(1024); var ta = new uint8array(sab); atomics.store(ta, 0, 12); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.store' in that specific...
Atomics.sub() - JavaScript
a pull request. syntax atomics.sub(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to subtract a value from. value the number to subtract. return value the old value at the given position (typedarray[index]).
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using sub const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 48; atomics.sub(ta, 0, 12); // returns 48, the old value atomics.load(ta, 0); // 36 specifications specification ecmascript (ec...
Atomics.wait() - JavaScript
and may not be allowed on the main thread. syntax atomics.wait(typedarray, index, value[, timeout]) parameters typedarray a shared int32array. index the position in the typedarray to wait on. value the expected value to test. timeout optional time to wait in milliseconds. infinity, if no time is provided. return value a string which is either "ok", "not-equal", or "timed-out".
exceptions throws a typeerror, if typedarray is not a shared int32array. throws a rangeerror, if index is out of bounds in the typedarray. examples using wait() given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however,...
Atomics.xor() - JavaScript
x atomics.xor(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise xor. value the number to compute the bitwise xor with. return value the old value at the given position (typedarray[index]).
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise xor operation yields 1, if a and b are different. the truth table for the xor operation is: a b a ^ b 0 0 0 0 1 1 1 0 1 1 1 0 for example, ...
Atomics - JavaScript
specified index of the array. returns the value. atomics.sub() subtracts a value at the specified index of the array. returns the old value at that index. atomics.wait() verifies that the specified index of the array still contains a value and sleeps awaiting or times out. returns either "ok", "not-equal", or "timed-out". if waiting is not allowed in the calling agent then it throws an error
exception. (most browsers will not allow wait() on the browser's main thread.) atomics.xor() computes a bitwise xor on the value at the specified index of the array with the provided value. returns the old value at that index. examples using atomics const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.and(ta, ...
BigInt.prototype.toString() - JavaScript
sitory. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax bigintobj.tostring([radix]) parameters radixoptional optional. an integer in the range 2 through 36 specifying the base to use for representing numeric values. return value a string representing the specified bigint object.
exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown. description the bigint object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for bigint objects, the tostring() method returns a string representation of the object in the specified radix. the tostring() method parses its first argument...
DataView() constructor - JavaScript
ting the specified data buffer. (that probably wasn't a very helpful description.) you can think of the returned object as an "interpreter" of the array buffer of bytes — it knows how to convert numbers to fit within the buffer correctly, both when reading and writing to it. this means handling integer and float conversion, endianness, and other details of representing numbers in binary form.
exceptions rangeerror thrown if the byteoffset or bytelength parameter values result in the view extending past the end of the buffer. for example, if the buffer is 16 bytes long, the byteoffset is 8, and the bytelength is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. examples using dataview var buffer = new arraybuffer(16); v...
Date.prototype.toLocaleDateString() - JavaScript
e zone console.log(date.tolocaledatestring()); // → "12/11/2012" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror
exception: function tolocaledatestringsupportslocales() { try { new date().tolocaledatestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized date formats. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly so...
Date.prototype.toLocaleString() - JavaScript
onsole.log(date.tolocalestring()); // → "12/11/2012, 7:00:00 pm" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror
exception: function tolocalestringsupportslocales() { try { new date().tolocalestring('i'); } catch (e) { return e instanceof rangeerror; } return false; } using locales this example shows some of the variations in localized date and time formats. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly s...
Date.prototype.toLocaleTimeString() - JavaScript
e zone console.log(date.tolocaletimestring()); // → "7:00:00 pm" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror
exception: function tolocaletimestringsupportslocales() { try { new date().tolocaletimestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized time formats. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly...
Error.prototype.message - JavaScript
the message property combined with the name property is used by the error.prototype.tostring() method to create a string representation of the error. ...
EvalError - JavaScript
constructor evalerror() creates a new evalerror object. instance properties evalerror.prototype.message error message. although ecma-262 specifies that evalerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. evalerror.prototype.name error name. inherited from error. evalerror.prototype.filename path to file that raised this error. inherited from error. evalerror.prototype.linenumber line number in file that raised this error. inherited from error. ...
Function.prototype.toString() - JavaScript
t; it does not inherit object.prototype.tostring. for user-defined function objects, the tostring method returns a string containing the source text segment which was used to define the function. javascript calls the tostring method automatically when a function is to be represented as a text value, e.g. when a function is concatenated with a string. 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 tostr...
Generator.prototype.throw() - JavaScript
for debugging purposes, it is useful to make it an instanceof error. return value an object with two properties: done (boolean) has the value true if the iterator is past the end of the iterated sequence. in this case value optionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. ...
InternalError() constructor - JavaScript
the internalerror() constructor creates an error that indicates an error that occurred internally in the javascript engine. for example: "internalerror: too much recursion". syntax new internalerror([message[, filename[, linenumber]]]) parameters message optional. human-readable description of the error filename optional. the name of the file containing the code that caused the
exception linenumber optional. the line number of the code that caused the
exception examples creating a new internalerror new internalerror("engine failure"); specifications not part of any standard. ...
Intl.Locale.prototype.script - JavaScript
s one of the core attributes of a locale. it indicates the set of symbols, or glyphs, that are used to write a particular language. for instance, the script associated with english is latin, whereas the script typically associated with korean is hangul. in many cases, denoting a script is not strictly necessary, since the language (which is necessary) is only written in a single script. there are
exceptions to this rule, however, and it is important to indicate the script whenever possible, in order to have a complete unicode language identifier. examples setting the script in the locale identifer string argument the script is the second part of a valid unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the locale constructor. note...
JSON.parse() - JavaScript
ll request. syntax json.parse(text[, reviver]) parameters text the string to parse as json. see the json object for a description of json syntax. reviver optional if a function, this prescribes how the value originally produced by parsing is transformed, before being returned. return value the object, array, string, number, boolean, or null value corresponding to the given json text.
exceptions throws a syntaxerror
exception if the string to parse is not valid json. polyfill // from https://github.com/douglascrockford/json-js/blob/master/json2.js if (typeof json.parse !== "function") { var rx_one = /^[\],:{}\s]*$/; var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fa-f]{4})/g; var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[ee][+\-]?\d+)?/g; var rx_four = /(?:^...
JSON.stringify() - JavaScript
te space; this number is capped at 10 (if it is greater, the value is just 10). values less than 1 indicate that no space should be used. if this is a string, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. if this parameter is not provided (or is null), no white space is used. return value a json string representing the given value.
exceptions throws a typeerror ("cyclic object value")
exception when a circular reference is found. throws a typeerror ("bigint value can't be serialized in json") when trying to stringify a bigint value. description json.stringify() converts a value to json notation representing it: if the value has a tojson() method, it's responsible to define what data will be serialized. boolean, number, and...
Number.prototype.toExponential() - JavaScript
x numobj.toexponential([fractiondigits]) parameters fractiondigits optional. an integer specifying the number of digits after the decimal point. defaults to as many digits as necessary to specify the number. return value a string representing the given number object in exponential notation with one digit before the decimal point, rounded to fractiondigits digits after the decimal point.
exceptions rangeerror if fractiondigits is too small or too large. values between 0 and 20, inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as well. typeerror if this method is invoked on an object that is not a number. description if the fractiondigits argument is omitted, the number of digits after the decimal point defaults to the number ...
Number.prototype.toFixed() - JavaScript
nd send us a pull request. syntax numobj.tofixed([digits]) parameters digits optional the number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. if this argument is omitted, it is treated as 0. return value a string representing the given number using fixed-point notation.
exceptions rangeerror if digits is too small or too large. values between 0 and 100, inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as chosen. typeerror if this method is invoked on an object that is not a number. description tofixed() returns a string representation of numobj that does not use exponential notation and has exactly digits di...
Number.prototype.toLocaleString() - JavaScript
ith default options is returned. var number = 3500; console.log(number.tolocalestring()); // displays "3,500" if in u.s. english locale checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check for support in es5.1 and later implementations, the requirement that illegal language tags are rejected with a rangeerror
exception can be used: function tolocalestringsupportslocales() { var number = 0; try { number.tolocalestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } prior to es5.1, implementations were not required to throw a range error
exception if tolocalestring is called with arguments. a check that works in all hosts, including those supporting ecma-262 prior to ed...
Number.prototype.toPrecision() - JavaScript
enting a number object in fixed-point or exponential notation rounded to precision significant digits. see the discussion of rounding in the description of the number.prototype.tofixed() method, which also applies to toprecision(). if the precision argument is omitted, behaves as number.prototype.tostring(). if the precision argument is a non-integer value, it is rounded to the nearest integer.
exceptions rangeerror if precision is not between 1 and 100 (inclusive), a rangeerror is thrown. implementations are allowed to support larger and smaller values as well. ecma-262 only requires a precision of up to 21 significant digits. examples using toprecision let numobj = 5.123456 console.log(numobj.toprecision()) // logs '5.123456' console.log(numobj.toprecision(5)) // logs '5.1235' con...
Number.prototype.toString() - JavaScript
github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax numobj.tostring([radix]) parameters radix optional. an integer in the range 2 through 36 specifying the base to use for representing numeric values. return value a string representing the specified number object.
exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown. description the number object overrides the tostring() method of the object object. (it does not inherit object.prototype.tostring()). for number objects, the tostring() method returns a string representation of the object in the specified radix. the tostring() method parses its first argume...
Object.create() - JavaScript
umerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names. these properties correspond to the second argument of object.defineproperties(). return value a new object with the specified prototype object and properties.
exceptions the proto parameter has to be either null or an object excluding primitive wrapper objects. if proto is neither of these a typeerror is thrown. custom and null objects a new object created from a completely custom object (especially one created from the null object, which is basically a custom object with no members) can behave in unexpected ways. this is especially true when debugging,...
Object.defineProperties() - JavaScript
undefined. set a function which serves as a setter for the property, or undefined if there is no setter. the function will receive as its only argument the new value being assigned to the property. defaults to undefined. if a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if a descriptor has both value or writable and get or set keys, an
exception is thrown. return value the object that was passed to the function. 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 iscallable) to the following reimplementation in javascript: function defineproperties(obj, properties) { function converttodes...
Object.defineProperty() - JavaScript
re is no setter. 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. defaults to undefined. if a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if a descriptor has both value or writable and get or set keys, an
exception is thrown. bear in mind that these attributes are not necessarily the descriptor's own properties. inherited properties will be considered as well. in order to ensure these defaults are preserved, you might freeze the object.prototype upfront, specify all options explicitly, or point to null with object.create(null). // using __proto__ var obj = {}; var descriptor = object.create(null); // no i...
Object.freeze() - JavaScript
xamples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.freeze(obj) parameters obj the object to freeze. return value the object that was passed to the function. description nothing can be added to or removed from the properties set of a frozen object. any attempt to do so will fail, either silently or by throwing a typeerror
exception (most commonly, but not exclusively, when in strict mode). for data properties of a frozen object, values cannot be changed, the writable and configurable attributes are set to false. accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). note that values that are objects can still be modified, unless they are also frozen. as an obj...
Object.getPrototypeOf() - JavaScript
quest. syntax object.getprototypeof(obj) parameters obj the object whose prototype is to be returned. return value the prototype of the given object. if there are no inherited properties, null is returned. examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; // true non-object coercion in es5, it will throw a typeerror
exception if the obj parameter isn't an object. in es2015, the parameter will be coerced to an object. object.getprototypeof('foo'); // typeerror: "foo" is not an object (es5 code) object.getprototypeof('foo'); // string.prototype (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.getprototypeof' in that specification. ...
Object.prototype.propertyIsEnumerable() - JavaScript
request. syntax obj.propertyisenumerable(prop) parameters prop the name of the property to test. return value a boolean indicating whether the specified property is enumerable and is the object's own property. description every object has a propertyisenumerable method. this method can determine whether the specified property in an object can be enumerated by a for...in loop, with the
exception of properties inherited through the prototype chain. if the object does not have the specified property, this method returns false. examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // returns true a.property...
Object.setPrototypeOf() - JavaScript
performance, you should avoid setting the [[prototype]] of an object. instead, create a new object with the desired [[prototype]] using object.create(). syntax object.setprototypeof(obj, prototype) parameters obj the object which is to have its prototype set. prototype the object's new prototype (an object or null). return value the specified object. description throws a typeerror
exception if the object whose [[prototype]] is to be modified is non-extensible according to object.isextensible(). does nothing if the prototype parameter isn't an object or null (i.e., number, string, boolean, or undefined). otherwise, this method changes the [[prototype]] of obj to the new value. object.setprototypeof() is in the ecmascript 2015 specification. it is generally considered the proper way ...
Promise.prototype.catch() - JavaScript
g errors // throwing an error will call the catch method most of the time var p1 = new promise(function(resolve, reject) { throw new error('uh-oh!'); }); p1.catch(function(e) { console.error(e); // "uh-oh!" }); // errors thrown inside asynchronous functions will act like uncaught errors var p2 = new promise(function(resolve, reject) { settimeout(function() { throw new error('uncaught
exception!'); }, 1000); }); p2.catch(function(e) { console.error(e); // this is never called }); // errors thrown after resolve is called will be silenced var p3 = new promise(function(resolve, reject) { resolve(); throw new error('silenced
exception!'); }); p3.catch(function(e) { console.error(e); // this is never called }); if it is resolved //create a promise which would not call onrejec...
handler.defineProperty() - JavaScript
t extensible. a property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. a property may not be non-configurable, if a corresponding configurable property of the target object exists. if a property has a corresponding target object property then object.defineproperty(target, prop, descriptor) will not throw an
exception. in strict mode, a false return value from the defineproperty() handler will throw a typeerror
exception. examples trapping of defineproperty the following code traps object.defineproperty(). const p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('called: ' + prop); return true; } }); const desc = { configurable: true, enumerable: true, value...
handler.getOwnPropertyDescriptor() - JavaScript
wn property of the target object and the target object is not extensible. a property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. the result of object.getownpropertydescriptor(target) can be applied to the target object using object.defineproperty() and will not throw an
exception. examples trapping of getownpropertydescriptor the following code traps object.getownpropertydescriptor(). const p = new proxy({ a: 20}, { getownpropertydescriptor: function(target, prop) { console.log('called: ' + prop); return { configurable: true, enumerable: true, value: 10 }; } }); console.log(object.getownpropertydescriptor(p, 'a').value); // "called: a" ...
handler.getPrototypeOf() - JavaScript
{ getprototypeof(target) { return array.prototype; } }); console.log( object.getprototypeof(p) === array.prototype, // true reflect.getprototypeof(p) === array.prototype, // true p.__proto__ === array.prototype, // true array.prototype.isprototypeof(p), // true p instanceof array // true ); two kinds of
exceptions const obj = {}; const p = new proxy(obj, { getprototypeof(target) { return 'foo'; } }); object.getprototypeof(p); // typeerror: "foo" is not an object or null const obj = object.preventextensions({}); const p = new proxy(obj, { getprototypeof(target) { return {}; } }); object.getprototypeof(p); // typeerror: expected same prototype value specifications ...
handler.set() - JavaScript
m the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has undefined as its [[set]] attribute. in strict mode, a false return value from the set() handler will throw a typeerror
exception. examples trap setting of a property value the following code traps setting a property value. const p = new proxy({}, { set: function(target, prop, value, receiver) { target[prop] = value; console.log('property set: ' + prop + ' = ' + value); return true; } }) console.log('a' in p); // false p.a = 10; // "property set: a = 10" console.log('a' in p); // true ...
ReferenceError() constructor - JavaScript
the referenceerror object represents an error when a non-existent variable is referenced. syntax new referenceerror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error. filename optional optional. the name of the file containing the code that caused the
exception. linenumber optional optional. the line number of the code that caused the
exception. examples catching a referenceerror try { let a = undefinedvariable } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) ...
Reflect.apply() - JavaScript
ull request. syntax reflect.apply(target, thisargument, argumentslist) parameters target the target function to call. thisargument the value of this provided for the call to target. argumentslist an array-like object specifying the arguments with which target should be called. return value the result of calling the given target function with the specified this value and arguments.
exceptions a typeerror, if the target is not callable. description in es5, you typically use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). function.prototype.apply.call(math.floor, undefined, [1.75]); with reflect.apply() this becomes less verbose and easier to understand. examples using reflect.apply() ...
Reflect.construct() - JavaScript
argumentslist an array-like object specifying the arguments with which target should be called. newtarget optional the constructor whose prototype should be used. see also the new.target operator. if newtarget is not present, its value defaults to target. return value a new instance of target (or newtarget, if present), initialized by target as a constructor with the given argumentslist.
exceptions a typeerror, if target or newtarget are not constructors. description reflect.construct() allows you to invoke a constructor with a variable number of arguments. (this would also be possible by using the spread syntax combined with the new operator.) let obj = new foo(...args) let obj = reflect.construct(foo, args) reflect.construct() vs object.create() prior to the introduction of reflec...
Reflect.defineProperty() - JavaScript
s and send us a pull request. syntax reflect.defineproperty(target, propertykey, attributes) parameters target the target object on which to define the property. propertykey the name of the property to be defined or modified. attributes the attributes for the property being defined or modified. return value a boolean indicating whether or not the property was successfully defined.
exceptions a typeerror, if target is not an object. description the reflect.defineproperty method allows precise addition to or modification of a property on an object. for more details, see the object.defineproperty which is similar. one key difference: object.defineproperty returns the object or throws a typeerror if the property has not been successfully defined. reflect.defineproperty, however, si...
Reflect.deleteProperty() - JavaScript
ute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.deleteproperty(target, propertykey) parameters target the target object on which to delete the property. propertykey the name of the property to be deleted. return value a boolean indicating whether or not the property was successfully deleted.
exceptions a typeerror, if target is not an object. description the reflect.deleteproperty method allows you to delete a property on an object. it returns a boolean indicating whether or not the property was successfully deleted. it is almost identical to the non-strict delete operator. examples using reflect.deleteproperty() let obj = { x: 1, y: 2 } reflect.deleteproperty(obj, 'x') // true obj ...
Reflect.get() - JavaScript
a pull request. syntax reflect.get(target, propertykey[, receiver]) parameters target the target object on which to get the property. propertykey the name of the property to get. receiver optional the value of this provided for the call to target if a getter is encountered. when used with proxy, it can be an object that inherits from target. return value the value of the property.
exceptions a typeerror, if target is not an object. description the reflect.get method allows you to get a property on an object. it is like the property accessor syntax as a function. examples using reflect.get() // object let obj = { x: 1, y: 2 } reflect.get(obj, 'x') // 1 // array reflect.get(['zero', 'one'], 1) // "one" // proxy with a get handler let x = {p: 1}; let obj = new proxy(x, { g...
Reflect.getOwnPropertyDescriptor() - JavaScript
https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.getownpropertydescriptor(target, propertykey) parameters target the target object in which to look for the property. propertykey the name of the property to get an own property descriptor for. return value a property descriptor object if the property exists in target object; otherwise, undefined.
exceptions a typeerror, if target is not an object. description the reflect.getownpropertydescriptor method returns a property descriptor of the given property if it exists in the target object, undefined otherwise. the only difference to object.getownpropertydescriptor() is how non-object targets are handled. examples using reflect.getownpropertydescriptor() reflect.getownpropertydescriptor({x: 'hel...
Reflect.getPrototypeOf() - JavaScript
ored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.getprototypeof(target) parameters target the target object of which to get the prototype. return value the prototype of the given object. if there are no inherited properties, null is returned.
exceptions a typeerror, if target is not an object. description the reflect.getprototypeof method returns the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. examples using reflect.getprototypeof() reflect.getprototypeof({}) // object.prototype reflect.getprototypeof(object.prototype) // null reflect.getprototypeof(object.create(null)) //...
Reflect.has() - JavaScript
if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.has(target, propertykey) parameters target the target object in which to look for the property. propertykey the name of the property to check. return value a boolean indicating whether or not the target has the property.
exceptions a typeerror, if target is not an object. description the reflect.has method allows you to check if a property is in an object. it works like the in operator as a function. examples using reflect.has() reflect.has({x: 0}, 'x') // true reflect.has({x: 0}, 'y') // false // returns true for properties in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler metho...
Reflect.isExtensible() - JavaScript
interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.isextensible(target) parameters target the target object which to check if it is extensible. return value a boolean indicating whether or not the target is extensible.
exceptions a typeerror, if target is not an object. description the reflect.isextensible method allows you determine if an object is extensible (whether it can have new properties added to it). it is the same method as object.isextensible(). examples using reflect.isextensible() see also object.isextensible(). // new objects are extensible. let empty = {} reflect.isextensible(empty) // === true //...
Reflect.ownKeys() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.ownkeys(target) parameters target the target object from which to get the own keys. return value an array of the target object's own property keys.
exceptions a typeerror, if target is not an object. description the reflect.ownkeys method returns an array of the target object's own property keys. its return value is equivalent to object.getownpropertynames(target).concat(object.getownpropertysymbols(target)). examples using reflect.ownkeys() reflect.ownkeys({z: 3, y: 2, x: 1}) // [ "z", "y", "x" ] reflect.ownkeys([]) // ["lengt...
Reflect.preventExtensions() - JavaScript
in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.preventextensions(target) parameters target the target object on which to prevent extensions. return value a boolean indicating whether or not the target was successfully set to prevent extensions.
exceptions a typeerror, if target is not an object. description the reflect.preventextensions() method allows you to prevent new properties from ever being added to an object (i.e., prevents future extensions to the object). it is similar to object.preventextensions(). examples using reflect.preventextensions() see also object.preventextensions(). // objects are extensible by default. let empty = {}...
Reflect.set() - JavaScript
uest. syntax reflect.set(target, propertykey, value[, receiver]) parameters target the target object on which to set the property. propertykey the name of the property to set. value the value to set. receiver optional the value of this provided for the call to target if a setter is encountered. return value a boolean indicating whether or not setting the property was successful.
exceptions a typeerror, if target is not an object. description the reflect.set method allows you to set a property on an object. it does property assignment and is like the property accessor syntax as a function. examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // array let arr = ['duck', 'duck', 'duck'] reflect.set(arr, 2, 'goose')...
Reflect.setPrototypeOf() - JavaScript
bute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.setprototypeof(target, prototype) parameters target the target object of which to set the prototype. prototype the object's new prototype (an object or null). return value a boolean indicating whether or not the prototype was successfully set.
exceptions a typeerror, if target is not an object or if prototype is neither an object nor null. description the reflect.setprototypeof method changes the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. examples using reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null. reflect.s...
RegExp.prototype.dotAll - JavaScript
therwise: u+000a line feed (lf) ("\n") u+000d carriage return (cr) ("\r") u+2028 line separator u+2029 paragraph separator this effectively means the dot will match any character on the unicode basic multilingual plane (bmp). to allow it to match astral characters, the "u" (unicode) flag should be used. using both flags in conjunction allows the dot to match any unicode character, without
exceptions. you cannot change this property directly. examples using dotall var str1 = 'bar\nexample foo example'; var regex1 = new regexp('bar.example','s'); console.log(regex1.dotall); // output: true console.log(str1.replace(regex1,'')); // output: foo example var str2 = 'bar\nexample foo example'; var regex2 = new regexp('bar.example'); console.log(regex2.dotall); // output: false console.lo...
String.fromCodePoint() - JavaScript
his interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax string.fromcodepoint(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of code points. return value a string created by using the specified sequence of code points.
exceptions a rangeerror is thrown if an invalid unicode code point is given (e.g. "rangeerror: nan is not a valid code point"). description this method returns a string (and not a string object). 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. polyfill the string.fromcodepoint() method has be...
String.prototype.localeCompare() - JavaScript
.localecompare(b, 'fr', {ignorepunctuation: true})); // ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé'] check browser support for extended arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them, use the "i" argument (a requirement that illegal language tags are rejected) and look for a rangeerror
exception: function localecomparesupportslocales() { try { 'foo'.localecompare('bar', 'i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales the results provided by localecompare() vary between languages. in order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallba...
String.prototype.matchAll() - JavaScript
const regexp = regexp('[a-c]',''); const str = 'abc'; str.matchall(regexp); // typeerror matchall internally makes a clone of the regexp—so, unlike regexp.exec(), lastindex does not change as the string is scanned. const regexp = regexp('[a-c]','g'); regexp.lastindex = 1; const str = 'abc'; array.from(str.matchall(regexp), m => `${regexp.lastindex} ${m[0]}`); // ar...
String.raw() - JavaScript
ut escapes (e.g. \n) are not. syntax string.raw(callsite, ...substitutions) string.raw`templatestring` parameters callsite well-formed template call site object, like { raw: ['foo', 'bar', 'baz'] }. ...substitutions contains substitution values. templatestring a template string, optionally with substitutions (${...}). return value the raw string form of a given template string.
exceptions typeerror a typeerror is thrown if the first argument is not a well-formed object. description in most cases, string.raw() is used with template strings. 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). string.raw() is the only built-in tag function of template strings. ...
String.prototype.repeat() - JavaScript
ithub repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.repeat(count) parameters count an integer between 0 and +infinity, indicating the number of times to repeat the string. return value a new string containing the specified number of copies of the given string.
exceptions rangeerror: repeat count must be non-negative. rangeerror: repeat count must be less than infinity and not overflow maximum string size. polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can polyfill string.prototype.repeat() with the following snippet: if (!string.prototype.repeat) { st...
String.prototype.toLocaleLowerCase() - JavaScript
e locale parameter indicates the locale to be used to convert to lower case according to any locale-specific case mappings. if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. return value a new string representing the calling string converted to lower case, according to any locale-specific case mappings.
exceptions a rangeerror ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. a typeerror ("invalid element in locales argument") is thrown if an array element isn't of type string. description the tolocalelowercase() method returns the value of the string converted to lower case according to any locale-specific case mappings. tolocalelowercase() does not affect ...
String.prototype.toLocaleUpperCase() - JavaScript
e locale parameter indicates the locale to be used to convert to upper case according to any locale-specific case mappings. if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. return value a new string representing the calling string converted to upper case, according to any locale-specific case mappings.
exceptions a rangeerror ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. a typeerror ("invalid element in locales argument") is thrown if an array element isn't of type string. description the tolocaleuppercase() method returns the value of the string converted to upper case according to any locale-specific case mappings. tolocaleuppercase() does not affect ...
String.prototype.toUpperCase() - JavaScript
(the value will be converted to a string if it isn't one). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.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). description the touppercase() method returns the value of the string converted to uppercase. this method does not affect the value of the string itself since javascript strings are immutable. examples basic usage console.log('alphabet'.touppercase()); // 'alphabet' conversion of non...
URIError() constructor - JavaScript
the urierror() constructor creates an error when a global uri handling function was used in a wrong way. syntax new urierror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error. filename optional optional. the name of the file containing the code that caused the
exception. linenumber optional optional. the line number of the code that caused the
exception. examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) ...
WebAssembly.CompileError() constructor - JavaScript
the webassembly.compileerror() constructor creates a new webassembly compileerror object, which indicates an error during webassembly decoding or validation. syntax new webassembly.compileerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the
exception. linenumber optional the line number of the code that caused the
exception. examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console...
WebAssembly.LinkError() constructor - JavaScript
the webassembly.linkerror() constructor creates a new webassembly linkerror object, which indicates an error during module instantiation (besides traps from the start function). syntax new webassembly.linkerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the
exception. linenumber optional the line number of the code that caused the
exception. examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" co...
WebAssembly.Memory() constructor - JavaScript
up front. however, the engine may ignore or clamp this reservation request. unshared webassembly memories don't need to set a maximum, but shared memories do. shared optional a boolean value that defines whether the memory is a shared memory or not. if set to true, it is a shared memory. the default is false. note: a webassembly page has a constant size of 65,536 bytes, i.e., 64kib.
exceptions if memorydescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. examples creating a new memory instance there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. the following example creates a new webassembly memory instance with an initial size of 10 pages (640k...
WebAssembly.Module.customSections() - JavaScript
he given module with the given string name. syntax webassembly.module.customsections(module, sectionname); parameters module the webassembly.module object whose custom sections are being considered. sectionname the string name of the desired custom section. return value a (possibly empty) array containing arraybuffer copies of the contents of all custom sections matching sectionname.
exceptions if module is not a webassembly.module object instance, a typeerror is thrown. description a wasm module is comprised of a sequence of sections. most of these sections are fully specified and validated by the wasm spec, but modules can also contain custom sections that are ignored and skipped over during validation. (read high level structure for information on section structures, and how norm...
WebAssembly.Module.exports() - JavaScript
the webassembly.module.exports() function returns an array containing descriptions of all the declared exports of the given module. syntax webassembly.module.exports(module); parameters module a webassembly.module object. return value an array containing objects representing the exported functions of the given module.
exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(m...
WebAssembly.Module.imports() - JavaScript
the webassembly.imports() function returns an array containing descriptions of all the declared imports of the given module. syntax webassembly.module.imports(module); parameters module a webassembly.module object. return value an array containing objects representing the imported functions of the given module.
exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using imports the following example (see imports.html source code; see it live also) compiles the loaded simple.wasm module. this module is then queried for its imports. webassembly.compilestreaming(fetch('simple.wasm')) .then(function(mod) { var imports = webassembly.module.imports(mod); console.log(imports[0]); }); the output looks like this: { module: "imports", name:...
WebAssembly.RuntimeError() constructor - JavaScript
the webassembly.runtimeerror() constructor creates a new webassembly runtimeerror object — the type that is thrown whenever webassembly specifies a trap. syntax new webassembly.runtimeerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the
exception. linenumber optional the line number of the code that caused the
exception. examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.l...
WebAssembly.Table() constructor - JavaScript
arameters tabledescriptor an object that can contain the following members: element a string representing the type of value to be stored in the table. at the moment this can only have a value of "anyfunc" (functions). initial the initial number of elements of the webassembly table. maximum optional the maximum number of elements the webassembly table is allowed to grow to.
exceptions if tabledescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of ...
WebAssembly.Table.prototype.get() - JavaScript
the get() prototype method of the webassembly.table() object retrieves a function reference stored at a given index. syntax table.get(index); parameters index the index of the function reference you want to retrieve. return value a function reference — this is an exported webassembly function, a javascript wrapper for an underlying wasm function.
exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming() method. it then retrieves the references stored in the exported table. webassembly.instantiatestreaming(fetch('table.wasm')) .then(function(obj) { v...
WebAssembly.Table.prototype.grow() - JavaScript
the grow() prototype method of the webassembly.table object increases the size of the table instance by a specified number of elements. syntax table.grow(number); parameters number the number of elements you want to grow the table by. return value the previous length of the table.
exceptions if the grow() operation fails for whatever reason, a rangeerror is thrown. examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10. var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification ...
WebAssembly.Table.prototype.set() - JavaScript
pe method of the webassembly.table object mutates a reference stored at a given index to a different value. syntax table.set(index, value); parameters index the index of the function reference you want to mutate. value the value you want to mutate the reference to. this must be an exported webassembly function, a javascript wrapper for an underlying wasm function. return value void.
exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. if value is not an exported webassembly function or null, a typeerror is thrown. examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references. we then print out the table length and contents of ...
WebAssembly.compile() - JavaScript
fore it can be instantiated (otherwise, the webassembly.instantiate() function should be used). syntax promise<webassembly.module> webassembly.compile(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. return value a promise that resolves to a webassembly.module object representing the compiled module.
exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); fetch('simple.wasm').then(response => re...
WebAssembly.compileStreaming() - JavaScript
ly.instantiatestreaming() function should be used). syntax promise<webassembly.module> webassembly.compilestreaming(source); parameters source a response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream and compile. return value a promise that resolves to a webassembly.module object representing the compiled module.
exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. examples compile streaming the following example (see our compile-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles it to a webassembly.module object. because the compilestreamin...
WebAssembly.instantiateStreaming() - JavaScript
of the compiled module or else a webassembly.linkerror is thrown. return value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module. this module can be instantiated again or shared via postmessage(). instance: a webassembly.instance object that contains all the exported webassembly functions.
exceptions if either of the parameters are not of the correct type or structure, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. examples instantiating streaming the following example (see our instantiate-streaming.html demo on github, and view it live also)...
WebAssembly.validate() - JavaScript
ction validates a given typed array of webassembly binary code, returning whether the bytes form a valid wasm module (true) or not (false). syntax webassembly.validate(buffersource); parameters buffersource a typed array or arraybuffer containing webassembly binary code to be validated. return value a boolean that specifies whether buffersource is valid wasm code (true) or not (false).
exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown. examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array. the validate() method is then used to check whether the module is valid. fetch('simple.wasm').then(response => response.arraybuffer() ).then(function(byt...
decodeURI() - JavaScript
a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax decodeuri(encodeduri) parameters encodeduri a complete, encoded uniform resource identifier. return value a new string representing the unencoded version of the given encoded uniform resource identifier (uri).
exceptions throws an urierror ("malformed uri sequence")
exception when encodeduri contains invalid character sequences. description replaces each escape sequence in the encoded uri with the character that it represents, but does not decode escape sequences that could not have been introduced by encodeuri. the character “#” is not decoded from escape sequences. examples decoding a cyrillic url de...
decodeURIComponent() - JavaScript
f you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax decodeuricomponent(encodeduri) parameters encodeduri an encoded component of a uniform resource identifier. return value a new string representing the decoded version of the given encoded uniform resource identifier (uri) component.
exceptions throws an urierror ("malformed uri sequence")
exception when used wrongly. description replaces each escape sequence in the encoded uri component with the character that it represents. examples decoding a cyrillic url component decodeuricomponent('javascript_%d1%88%d0%b5%d0%bb%d0%bb%d1%8b'); // "javascript_шеллы" catching errors try { var a = decodeuricomponent('%e0%a4%a'); } cat...
escape() - JavaScript
icode characters.) escaped characters in string literals can be expanded by replacing the \x with %, then using the decodeuricomponent() function. syntax escape(str) parameters str a string to be encoded. return value a new string in which certain characters have been escaped. description the escape function is a property of the global object. special characters are encoded with the
exception of: @*_+-./ the hexadecimal form for characters, whose code unit value is 0xff or less, is a two-digit escape sequence: %xx. for characters with a greater code unit, the four-digit format %uxxxx is used. examples using escape escape('abc123'); // "abc123" escape('äöü'); // "%e4%f6%fc" escape('ć'); // "%u0107" // special characters escape('@*_+-./'); // "@*_+-./" s...
Exponentiation (**) - JavaScript
es and send us a pull request. syntax operator: var1 ** var2 description the exponentiation operator is right-associative: a ** b ** c is equal to a ** (b ** c). in most languages, such as php, python, and others that have an exponentiation operator (**), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary + and unary -, but there are a few
exceptions. for example, in bash, the ** operator is defined to have a lower precedence than unary operators. in javascript, it is impossible to write an ambiguous exponentiation expression. that is, you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number; doing so will cause a syntaxerror. -2 ** 2; // 4 in bash, -4 in other languages. // this is invalid in javascr...
instanceof - JavaScript
.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. unlike standard javascript globals, the test obj instanceof xpcominterface works as expected, even if obj is from a different scope. examples demonstrating that string and date are of type object and
exceptional cases the following code uses instanceof to demonstrate that string and date objects are also of type object (they are derived from object). however, objects created with the object literal notation are an
exception here: although the prototype is undefined, instanceof object returns true. let simplestr = 'this is a simple string' let mystring = new string() let newstr = new string('stri...
yield - JavaScript
ntil the generator's next() method is called. each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and return the generator's new value. the next time next() is called, execution resumes with the statement immediately after the yield. throw is used to throw an
exception from the generator. this halts execution of the generator entirely, and execution resumes in the caller (as is normally the case when an
exception is thrown). the end of the generator function is reached. in this case, execution of the generator ends and an iteratorresult is returned to the caller in which the value is undefined and done is true. a return statement is reached. in this case, exe...
async function - JavaScript
syntax async function name([param[, param[, ...param]]]) { statements } parameters name the function’s name. param the name of an argument to be passed to the function. statements the statements comprising the body of the function. the await mechanism may be used. return value a promise which will be resolved with the value returned by the async function, or rejected with an
exception thrown from, or uncaught within, the async function. description async functions can contain zero or more await expressions. await expressions suspend progress through an async function, yielding control and subsequently resuming progress only when an awaited promise-based asynchronous operation is either fulfilled or rejected. the resolved value of the promise is treated as the return value of...
Statements and declarations - JavaScript
pty an empty statement is used to provide no statement, although the javascript syntax would expect one. if...else executes a statement if a specified condition is true. if the condition is false, another statement can be executed. switch evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case. throw throws a user-defined
exception. try...catch marks a block of statements to try, and specifies a response, should an
exception be thrown. declarations var declares a variable, optionally initializing it to a value. let declares a block scope local variable, optionally initializing it to a value. const declares a read-only named constant. functions and classes function declares a function with the specified par...
Strict mode - JavaScript
gnments, which would accidentally create global variables, instead throw an error in strict mode: 'use strict'; // assuming no global variable mistypedvariable exists mistypevariable = 17; // this line throws a referenceerror due to the // misspelling of variable second, strict mode makes assignments which would otherwise silently fail to throw an
exception. for example, nan is a non-writable global variable. in normal code assigning to nan does nothing; the developer receives no failure feedback. in strict mode assigning to nan throws an
exception. any assignment that silently fails in normal code (assignment to a non-writable global or property, assignment to a getter-only property, assignment to a new property on a non-extensible object) will thr...
Web app manifests
eb app to be downloaded and be presented to the user similarly to a native app (e.g., be installed on the homescreen of a device, providing users with quicker access and a richer experience). pwa manifests include its name, author, icon(s), version, description, and list of all the necessary resources (among other things). can pwa manifest contain comments? it is a json-formatted file, with one
exception: it is allowed to contain "//"-style comments. members web manifests can contain the following keys. click each one for more information about it: background_colorcategoriesdescriptiondirdisplayiarc_rating_idiconslangnameorientationprefer_related_applicationsrelated_applicationsscopescreenshotsserviceworkershort_nameshortcutsstart_urltheme_color example manifest { "name": "hackerweb", "...
MathML documentation index - MathML
to display square roots (no index is displayed). the square root accepts only one argument, which leads to the following syntax: <msqrt> base </msqrt>. 30 <mstyle> mathml, mathml reference, mathml:element, mathml:general layout schemata the mathml <mstyle> element is used change the style of its children. it accepts all attributes of all mathml presentation elements with some
exceptions and additional attributes listed below. 31 <msub> mathml, mathml reference, mathml:element, mathml:script and limit schemata the mathml <msub> element is used to attach a subscript to an expression. 32 <msubsup> mathml, mathml reference, mathml:element, mathml:script and limit schemata the mathml <msubsup> element is used to attach both a subscript and a...
Autoplay guide for media and Web Audio APIs - Web media technologies
ple 2: detecting autoplay failure if you rely on autoplay for anything important, or if autoplay failure will impact your app in any way, you will probably want to be able to tell when it autoplay didn't begin. unfortunately, in the case of the autoplay attribute, recognizing whether or not autoplay successfully began is tricky. there's not an event triggered when autoplay fails. nor is there an
exception thrown or a callback you can set up or even a flag on the media element that tells you if autoplay worked. all you can really do is examine a few values and make an educated guess as to whether or not autoplay worked. a better approach, if you're able to adjust the direction you look at things from, is to instead rely on knowing that playback of the media has successfully started, instead of whe...
Digital audio concepts - Web media technologies
ally, lossy compression results in significantly smaller output than lossless compression methods; also, many lossy codecs are excellent, with the loss in quality and detail being difficult or even impossible for the average listener to discern. note: while a high-quality lossy compression algorithm's effect on sound quality may be difficult for the average person to detect, certain people have
exceptionally good hearing, or are particularly adept at noticing the kinds of changes introduced to music by lossy compression techniques. the majority of audio codecs use some form of lossy compression, because of the better compression ratio those algorithms offer. whereas lossless compression algorithms usually manage no better than a 40-50% of the size of the original, uncompressed sound data, moder...
Web video codec guide - Web media technologies
patents are licensed by mpeg la. theora theora, developed by xiph.org, is an open and free video codec which may be used without royalties or licensing. theora is comparable in quality and compression rates to mpeg-4 part 2 visual and avc, making it a very good if not top-of-...
Performance fundamentals - Web Performance
ication "back buffers" in many other operating systems), and by using special memory for graphics buffers that can be directly accessed by the compositor hardware. complex scenes are rendered using the device's gpu for maximum performance. to improve power usage, simple scenes are rendered using special dedicated composition hardware, while the gpu idles or turns off. fully static content is the
exception rather than the rule for rich applications. rich applications use dynamic content with animation and transition effects. transitions and animations are particularly important to applications: developers can use css to declare complicated behaviour with a simple, high-level syntax. in turn, gecko's graphics pipeline is highly optimized to render common animations efficiently. common-case animation...
Privacy, permissions, and information security
oncept of privacy is somewhat hard to define. everyone has some idea what it means to keep something private, but when talking about the privacy of data, it becomes murky. fundamentally, privacy of your data on the internet is about ensuring that information that has personal implications is kept out of the hands of unauthorized persons or organizations, regardless of how it's obtained. privacy
exceptions may be granted to specific sites or applications, but it may also be granted conditionally, such as by permitting only a select group of people to access it, or only allowing the information to be accessed and used for a limited period of time. security security is about the active protection of data or a system against being accessed, downloaded, or operated by people or organizations tha...
preserveAspectRatio - SVG: Scalable Vector Graphics
the preserveaspectratio attribute indicates how an element with a viewbox providing a given aspect ratio must fit into a viewport with a different aspect ratio. because the aspect ratio of an svg image is defined by the viewbox attribute, if this attribute isn't set, the preserveaspectratio attribute has no effect (with one
exception, the <image> element, as described below). example <svg viewbox="-1 -1 162 92" xmlns="http://www.w3.org/2000/svg"> <defs> <path id="smiley" d="m50,10 a40,40,1,1,1,50,90 a40,40,1,1,1,50,10 m30,40 q36,35,42,40 m58,40 q64,35,70,40 m30,60 q50,75,70,60 q50,75,30,60" /> </defs> <!-- (width>height) meet --> <svg preserveaspectratio="xmidymid meet" x="0" y="0" viewbox="0 0 100 100" width="20" height="10"><use href="#smiley" /></svg> <svg preserveaspect...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
n :focus and ::selection styles implementation status unknown geometry change notes x and y attributes removed from <pattern> and <filter> implementation status unknown auto value of width and height computes to 0 but 100% on <svg> not implemented coordinate systems, transformations and units change notes
exception for bad values on svgmatrix.skewx() and svgmatrix.skewy() implementation status unknown bounding box for element with no position at (0, 0) implementation status unknown defer keyword removed from preserveaspectratio attribute removed (bug 1280425) added non-scaling-size, non-rotation and fixed-position keywords for vector-effect property not implemented yet...
Scripting - SVG: Scalable Vector Graphics
broken in adobe's svg version 6 preview plugin. the suggested workaround is to use "top" instead of "parent". since it is a beta version of their plugin, we can probably safely ignore this. more information and some examples can be found on the svg wiki inter-document scripting page. setproperty has three parameters the function svgelement.style.setproperty("fill-opacity", "0.0") throws a dom
exception - syntax err in mozilla. this behaviour is specified by the w3c in the dom level 2 style specification. the function setproperty is defined as a function with three parameters. the above can be replaced with 'svgelement.style.setproperty("fill-opacity", "0.0", "")', which is standards compliant. links svg wiki on scripting and programming ...
Specification Deviations - SVG: Scalable Vector Graphics
ements. nevertheless, to allow mozilla to more cleanly share internal 'class' and 'style' related code, we will implement these attributes on all svg elements as of firefox 3. in general this change will not be visible to svg authors (the elements for which the svg specification does not define the 'class' and 'style' attribute are elements that are not displayed directly). however, there are two
exceptions. extending the 'class' attribute to apply to all svg elements will allow svg authors to use the selectors api to select any svg element based on class. this seems like a good thing. requiring svg authors to know which elements can and cannot take a 'class' attribute would just put an extra burden on them. extending the 'style' attribute to apply to all svg elements should only really be visible ...