Search completed in 1.70 seconds.
RTCErrorEvent.error - Web APIs
the read-only rtc
errorevent property
error contains an rtc
error object describing the details of the
error which the event is announcing. syntax let
errorinfo = rtc
errorevent.
error; value an rtc
error object whose properties provide details about the
error which has occurred in the context of a webrtc operation. since rtc
error is based upon domexception, it includes those properties. additional properties defined by rtc
error 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 onl...
... defined by rtc
error 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 if
errordetail is sctp-failure, this property is a long integer specifying the sctp cause code indicating the cause of the failed sctp negotiation. null if the
error isn't an sctp
error. sdplinenumber read only if
errordetail is sdp-syntax-
error, this property is a long integer identifying the line number of the sdp on which the syntax
error occurred. null if the
error isn't an sdp syntax
error. senta...
...re, this property is a long integer specifying the sctp cause code indicating the cause of the failed sctp negotiation. null if the
error isn't an sctp
error. sdplinenumber read only if
errordetail is sdp-syntax-
error, this property is a long integer identifying the line number of the sdp on which the syntax
error occurred. null if the
error isn't an sdp syntax
error. sentalert read only if
errordetail is dtls-failure, this property is an unsigned long integer indicating the fatal dtls
error that was sent out by this device. if null, no dtls
error was transmitted. all rtc
error objects have their name set to operation
error. ...
...And 13 more matches
SpeechRecognitionError.error - Web APIs
aborted speech input was aborted in some manner, perhaps by some user-agent-specific behavior like a button the user can press to cancel speech input. audio-capture audio capture failed. network network communication required for completing the recognition failed. not-allowed the user agent disallowed any speech input from occurring for reasons of security, privacy or user preference. ...
...input from occurring for reasons of security, privacy or user preference. service-not-allowed the user agent disallowed the requested speech recognition service, either because the user agent doesn't support it or because of reasons of security, privacy or user preference. in this case it would allow another more suitable speech recognition service to be used instead. ...
...y or user preference. in this case it would allow another more suitable speech recognition service to be used instead. bad-grammar there was an
error in the speech recognition grammar or semantic tags, or the chosen grammar format or semantic tag format was unsupported. language-not-supported the language was not supported. ...
...And 2 more matches
MediaRecorderErrorEvent.error - Web APIs
the read-only
error property in the mediarecorder
errorevent interface is a domexception object providing details about the exception that was thrown by a mediarecorder instance. when a mediarecorder
errorevent occurs, you can determine to some extent what went wrong by examining the
error property within the mediarecorder
errorevent received by the mediarecorder's
error event handler, on
error. syntax
error = mediarecorder
errorevent.
error; value a domexception 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 wh...
...ception 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 they may occur in the corresponding method references. invalidstate
error an operation was attempted in a context in which it isn't allowed, or a request has been made on an object that's deleted or removed. notsupported
error a mediarecorder couldn't be created because the specified options weren't valid. the message atttribute should provide additional information, if it exists. security
error the mediastream is configured to disallow recording. this may be the ca...
...ase, 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. ...
...n mediastream, configured to buffer data into an array and to watch for
errors. function recordstream(stream) { let recorder = null; let bufferlist = []; try { recorder = new mediarecorder(stream); } catch(err) { /* exception while trying to create the recorder; handle that */ } recorder.ondataavailable = function(event) { bufferlist.push(event.data); }; recorder.on
error = function(event) { let
error = event.
error; }; recorder.start(100); /* 100ms time slices per buffer */ return recorder; } specifications specification status comment mediastream recordingthe definition of 'mediarecorder
errorevent.
error' in that specification. working draft initial specification. ...
SensorErrorEvent.error - Web APIs
candidate recommendation initial definition. ...
... candidate recommendation initial definition. ...
... candidate recommendation initial definition. ...
... candidate recommendation initial definition. ...
SpeechRecognitionErrorEvent.error - Web APIs
aborted speech input was aborted in some manner, perhaps by some user-agent-specific behavior like a button the user can press to cancel speech input. audio-capture audio capture failed. network network communication required for completing the recognition failed. not-allowed the user agent disallowed any speech input from occurring for reasons of security, privacy or user preference. ...
...input from occurring for reasons of security, privacy or user preference. service-not-allowed the user agent disallowed the requested speech recognition service, either because the user agent doesn't support it or because of reasons of security, privacy or user preference. in this case it would allow another more suitable speech recognition service to be used instead. ...
...y or user preference. in this case it would allow another more suitable speech recognition service to be used instead. bad-grammar there was an
error in the speech recognition grammar or semantic tags, or the chosen grammar format or semantic tag format was unsupported. language-not-supported the language was not supported. examples var recognition = new speechrecognition(); recognition.on
error = function(event) { console.log('speech recognition
error detected: ' + event.
error); console.log('additional information: ' + event.message); } specifications specification status comment web speech apithe definition of '
error' in that specification. draft ...
SpeechSynthesisErrorEvent.error - Web APIs
possible codes are: canceled a speechsynthesis.cancel method call caused the speechsynthesisutterance to be removed from the queue before it had begun being spoken. interrupted a speechsynthesis.cancel method call caused the speechsynthesisutterance to be interrupted after it had begun being spoken and before it completed. ...
...system settings.) network the operation couldn't be completed at this time because some required network communication failed. synthesis-unavailable the operation couldn't be completed at this time because no synthesis engine was available (for example, the user may need to install or configure a synthesis engine.) synthesis-failed the operation failed because the synthesis engine raised an
error. language-unavailable no appropriate voice was available for the language set in speechsynthesisutterance.lang. voice-unavailable the voice set in speechsynthesisutterance.voice was not available. text-too-long the contents of the speechsynthesisutterance.text attribute was too long to synthesize. invalid-argument the content of the speechsynthesisutterance.rate, speechsynthesisutterance.
...voices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.on
error = function(event) { console.
error('an
error has occurred with the speech synthesis: ' + event.
error); } inputtxt.blur(); } specifications specification status comment web speech apithe definition of '
error' in that specification. draft ...
OverconstrainedError.OverconstrainedError() - Web APIs
the overconstrained
error constructor creates a new overconstrained
error object which indicates that the set of desired capabilities for the current mediastreamtrack cannot currently be met. when this event is thrown on a mediastreamtrack, it is muted until either the current constraints can be established or until satisfiable constraints are applied. syntax var overconstrained
error = new overconstrained
error() parameters constraint the constraint that was not satified. message text for the
error's message property. specifications specification status comment media capture and streamsthe definition of 'overconstrained
error' in that specification. candidate recommendation initial definition. ...
SensorErrorEvent.SensorErrorEvent() - Web APIs
the sensor
errorevent constructor creates a new sensor
errorevent object which provides information about
errors thrown by any of the interfaces based on sensor. syntax sensor
errorevent = new sensor
errorevent(type, {
error: domexception}); parameters type will always be 'sensor
errorevent'. options optional currently only one option is supported:
error: an instance of domexception. specifications specification status comment generic sensor apithe definition of 'sensor
errorevent' in that specification. candidate recommendation initial definition. ...
Error codes returned by Mozilla APIs
the following tables list
errors that can occur when calling various mozilla apis. each
error is listed by its name and an
error code in parentheses. an
error will typically be displayed on the
error console, but can be captured using a try-catch block in javascript. these constants can be accessed through components.results. for example, by using components.results.ns_
error_not_initialized general
errors the following
errors are general and can occur when using any component. ns_
error_not_initialized (0xc1f30001) an attempt was made to use a component or object which has not yet been initialized. these components usually provide an initialization method, often called init, which must be called before other methods are used. ...
...sing components.results.ns_
error_not_initialized general
errors the following
errors are general and can occur when using any component. ns_
error_not_initialized (0xc1f30001) an attempt was made to use a component or object which has not yet been initialized. these components usually provide an initialization method, often called init, which must be called before other methods are used. ns_
error_already_initialized (0xc1f30002) an attempt is made to initialize a component or object again which has already been initialized. ns_
error_not_implemented (0x80004001) this
error is caused by methods which are not implemented. ...
...re used. ns_
error_already_initialized (0xc1f30002) an attempt is made to initialize a component or object again which has already been initialized. ns_
error_not_implemented (0x80004001) this
error is caused by methods which are not implemented. this could occur because the implementation has not yet been written, or because the component intentionally does not support the desired feature. ns_
error_no_interface (0x80004002) an attempt was made to call queryinterface to retrieve an interface which an object does not support. ns_
error_null_pointer (0x80004003) an
error occurred because a value was set to null when this was not expected. ns_
error_abort (0x80004004) this
error indicates that an operation failed and the caller should abort whatever action is being performed. this typically ...
...And 102 more matches
JavaScript error reference - JavaScript
below, you'll find a list of
errors which are thrown by javascript. these
errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. the pages below will provide additional details about these
errors. each
error is an object based upon the
error object, and has a name and a message.
errors displayed in the web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code. for a beginner's introductory tutorial on fixing javascript
errors, see what went wrong? troubleshooting javascript. list of
errors in this list, each page is listed by name (the type of
error) and message (a more detailed human-readable
error message). together, these two properties provide a starting point toward understanding and ...
...ou quickly comprehend the problem in your code. for a beginner's introductory tutorial on fixing javascript
errors, see what went wrong? ...
... beginner's introductory tutorial on fixing javascript
errors, see what went wrong? ...
...And 32 more matches
Error - JavaScript
error objects are thrown when runtime
errors occur. the
error object can also be used as a base object for user-defined exceptions. see below for standard built-in
error types. description runtime
errors result in new
error objects being created and thrown.
error types besides the generic
error constructor, there are seven other core
error constructors in javascript. for client-side exceptions, see exception handling statements. eval
error creates an instance representing an
error that occurs regarding the global function eval(). internal
error creates an instance representing an
error that occurs when an internal
error in the javascript engine is thrown. e.g. "too much recursion". ...
...uctor, there are seven other core
error constructors in javascript. for client-side exceptions, see exception handling statements. eval
error creates an instance representing an
error that occurs regarding the global function eval(). internal
error creates an instance representing an
error that occurs when an internal
error in the javascript engine is thrown. e.g. "too much recursion". range
error creates an instance representing an
error that occurs when a numeric variable or parameter is outside of its valid range. reference
error creates an instance representing an
error that occurs when de-referencing an invalid reference. syntax
error creates an instance representing a syntax
error. ...
...en an internal
error in the javascript engine is thrown. e.g. "too much recursion". range
error creates an instance representing an
error that occurs when a numeric variable or parameter is outside of its valid range. reference
error creates an instance representing an
error that occurs when de-referencing an invalid reference. syntax
error creates an instance representing a syntax
error. type
error creates an instance representing an
error that occurs when a variable or parameter is not of a valid type. uri
error creates an instance representing an
error that occurs when encodeuri() or decodeuri() are passed invalid parameters. constructor
error() creates a new
error object. ...
...And 27 more matches
JSErrorReport
ismuted bool the web platform allows scripts to be loaded from arbitrary cross-origin sources. ...
... ismuted bool the web platform allows scripts to be loaded from arbitrary cross-origin sources. ...
... ismuted bool the web platform allows scripts to be loaded from arbitrary cross-origin sources. ...
...And 21 more matches
JS_ReportErrorNumber
report an
error with an application-defined
error code. ...
... report an
error with an application-defined
error code. ...
... report an
error with an application-defined
error code. ...
...And 19 more matches
AddressErrors - Web APIs
see the examples below to see how this works. properties addressline a domstring which, if present, indicates that the addressline property of the paymentaddress could not be validated. ...
... see the examples below to see how this works. properties addressline a domstring which, if present, indicates that the addressline property of the paymentaddress could not be validated. ...
... see the examples below to see how this works. properties addressline a domstring which, if present, indicates that the addressline property of the paymentaddress could not be validated. ...
...And 19 more matches
Control flow and error handling - JavaScript
nsole.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 purpose: ecmascript exceptions domexception and dom
error 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. the following code throws seve...
...you can then reference the object's properties in the catch block. ...
...g: function() { return "i'm an object!"; } }; note: you can specify an object when you throw an exception. you can then reference the object's properties in the catch block. // create an object type userexception function userexception(message) { this.message = message; this.name = 'userexception'; } // make the exception convert to a pretty string when used as a string // (e.g., by the
error console) userexception.prototype.tostring = function() { return `${this.name}: "${this.message}"`; } // create an instance of the object type and throw it throw new userexception('value too high'); try...catch statement the try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. if an exception is thrown, the try...catch st...
...And 18 more matches
nsIScriptError
js/xpconnect/idl/nsiscript
error.idlscriptable represents javascript
errors and warnings for use by the console service. 66 introduced gecko 1.0 inherits from: nsiconsolemessage last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/script
error;1. to create an instance, use: var script
error = components.classes["@mozilla.org/script
error;1"] .createinstance(components.interfaces.nsiscript
error); note: the nsiscript
error2 interface was merged into this interface in gecko 12.0. prior to that release, if you wanted to associate an outer window with a script
error, you had to use nsiscript
error2 instead. ...
...tance, use: var script
error = components.classes["@mozilla.org/script
error;1"] .createinstance(components.interfaces.nsiscript
error); note: the nsiscript
error2 interface was merged into this interface in gecko 12.0. prior to that release, if you wanted to associate an outer window with a script
error, you had to use nsiscript
error2 instead. that subclass offered the nsiscript
error.initwithwindowid() method for that purpose; that method is now available in this interface, however. method overview void init(in wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category); void initwithwindowid(in wstring message, in wstring sourcename, in wstring sourceline, in prui...
...ing category); void initwithwindowid(in wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category, in unsigned long long innerwindowid); autf8string tostring(); attributes attribute type description category string a string indicating the category of
error that occurred see categories for a list. read only. columnnumber pruint32 the column number where the
error occurred. this is used to draw the arrow pointing to the problem character. read only.
errormessage astring the
error message in a string format without any context/line number information. note: nsiconsolemessage.message will return the
error fo...
...And 16 more matches
NSPR Error Handling
this chapter describes the functions for retrieving and setting
errors and the
error codes set by nspr.
error type
error functions
error codes for information on naming conventions for nspr types, functions, and macros, see nspr naming conventions.
error type pr
errorcode
error functions pr_set
error pr_set
errortext pr_get
error pr_getos
error pr_get
errortextlength pr_get
errortext
error codes
error codes defined in pr
error.h: pr_out_of_memory_
error insufficient memory to perform request. pr_bad_descriptor_
error the file descriptor used as an argument in the preceding function is invalid. pr_would_block_
error the operation would have blocked, which conflicts with the semantics that have been established. ...
...or pr_get
errortextlength pr_get
errortext
error codes
error codes defined in pr
error.h: pr_out_of_memory_
error insufficient memory to perform request. pr_bad_descriptor_
error the file descriptor used as an argument in the preceding function is invalid. pr_would_block_
error the operation would have blocked, which conflicts with the semantics that have been established. pr_access_fault_
error one of the arguments of the preceding function specified an invalid memory address. pr_invalid_method_
error the preceding function is invalid for the type of file descriptor used. pr_illegal_access_
error one of the arguments of the preceding function specified an invalid memory address. pr_unknown_
error some unknown
error has occurred. ...
...ablished. pr_access_fault_
error one of the arguments of the preceding function specified an invalid memory address. pr_invalid_method_
error the preceding function is invalid for the type of file descriptor used. pr_illegal_access_
error one of the arguments of the preceding function specified an invalid memory address. pr_unknown_
error some unknown
error has occurred. pr_pending_interrupt_
error the operation terminated because another thread has interrupted it with pr_interrupt. pr_not_implemented_
error the preceding function has not been implemented. pr_io_
error the preceding i/o function encountered some sort of an
error, perhaps an invalid device. pr_io_timeout_
error the i/o operation has not completed in the time specified for the preceding function. ...
...And 15 more matches
IDBTransaction.error - Web APIs
this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with the idbtransaction.abort method. ...
... this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with the idbtransaction.abort method. ...
... this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with the idbtransaction.abort method. ...
...And 13 more matches
RTCError - Web APIs
the rtc
error interface describes an
error which has occurred while handling webrtc operations. it's based upon the standard domexception interface that describes general dom
errors. constructor rtc
error() creates and returns a new rtc
error object initialized with the properties of the provided rtc
errorinit 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, domexception, rtc
error 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 i...
...rties in addition to the properties defined by the parent interface, domexception, rtc
error 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 the
errordetail string is dtls-failure. if null, no dtls
error was received. sctpcausecode read only if
errordetail is sctp-failure, this property is a long integer specifying the sctp cause code indicating the cause of the failed sctp negotiation. null if the
error isn't an sctp
error. ...
...cating 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 if
errordetail is sctp-failure, this property is a long integer specifying the sctp cause code indicating the cause of the failed sctp negotiation. null if the
error isn't an sctp
error. sdplinenumber read only if
errordetail is sdp-syntax-
error, this property is a long integer identifying the line number of the sdp on which the syntax
error occurred. null if the
error isn't an sdp syntax
error. sentalert read only if
errordetail is dtls-failure, this property is an unsigned long integer indicating the fatal dtls
error that was sent out by this device. ...
...And 13 more matches
SyntaxError: JSON.parse: bad parsing - JavaScript
the javascript exceptions thrown by json.parse() occur when string failed to be parsed as json. ...
... the javascript exceptions thrown by json.parse() occur when string failed to be parsed as json. ...
... the javascript exceptions thrown by json.parse() occur when string failed to be parsed as json. ...
...And 13 more matches
RangeError - JavaScript
the range
error object indicates an
error when a value is not in the set or range of allowed values. description a range
error is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value. this can be encountered when: passing a value that is not one of the allowed string values to string.prototype.normalize(), or when attempting to create an array of an illegal length with the array constructor, or when passing bad values to the numeric methods number.prototype.toexponential(), number.prototype.tofixed() or number.prototype.toprecision(). constructor range
error() creates a new range
error object. instance properties range
error.prototype.message
error message. ...
...n attempting to create an array of an illegal length with the array constructor, or when passing bad values to the numeric methods number.prototype.toexponential(), number.prototype.tofixed() or number.prototype.toprecision(). constructor range
error() creates a new range
error object. instance properties range
error.prototype.message
error message. although ecma-262 specifies that range
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. range
error.prototype.name
error name. ...
...ential(), number.prototype.tofixed() or number.prototype.toprecision(). constructor range
error() creates a new range
error object. instance properties range
error.prototype.message
error message. although ecma-262 specifies that range
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. range
error.prototype.name
error name. inherited from
error. range
error.prototype.filename path to file that raised this
error. inherited from
error. range
error.prototype.linenumber line number in file that raised this
error. inherited from
error. range
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. ...
...And 12 more matches
SyntaxError - JavaScript
the syntax
error object represents an
error when trying to interpret syntactically invalid code. it is thrown when the javascript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code. constructor syntax
error() creates a new syntax
error object. instance properties syntax
error.prototype.message
error message. although ecma-262 specifies that syntax
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. syntax
error.prototype.name
error name. inherited from
error. syntax
error.prototype.filename path to file that raised this
error. inherited from
error. syntax
error.prototype.linenumber line number in file that raised this
error. inherited from
error. ...
...hough ecma-262 specifies that syntax
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. syntax
error.prototype.name
error name. inherited from
error. syntax
error.prototype.filename path to file that raised this
error. inherited from
error. syntax
error.prototype.linenumber line number in file that raised this
error. inherited from
error. syntax
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. syntax
error.prototype.stack stack trace. inherited from
error. ...
...
error. syntax
error.prototype.filename path to file that raised this
error. inherited from
error. syntax
error.prototype.linenumber line number in file that raised this
error. inherited from
error. syntax
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. syntax
error.prototype.stack stack trace. inherited from
error. ...
...And 12 more matches
GlobalEventHandlers.onerror - Web APIs
the on
error 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.on
error() 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 on
error() handler on the element is invoked. ...
... handlers) occurs, an
error event using interface
errorevent is fired at window and window.on
error() 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 on
error() handler on the element is invoked. these
error events do not bubble up to window, but (at least in firefox) can be handled with a window.addeventlistener configured with usecapture set to true. installing a global
error event handler is useful for automated collection of
error reports. ...
...tiated the load, and the on
error() handler on the element is invoked. these
error events do not bubble up to window, but (at least in firefox) can be handled with a window.addeventlistener configured with usecapture set to true. installing a global
error event handler is useful for automated collection of
error reports. syntax for historical reasons, different arguments are passed to window.on
error and element.on
error handlers (as well as on
error-type window.addeventlistener handlers). window.on
error window.on
error = function(message, source, lineno, colno,
error) { ... }; function parameters: message:
error message (string). available as event (sic!) in html on
error="" handler. ...
...And 11 more matches
JS_SetErrorReporter
obsolete since jsapi 52this 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. get or specify the
error reporting mechanism for an application. syntax js
errorreporter js_get
errorreporter(jsruntime *rt); js
errorreporter js_set
errorreporter(jsruntime *rt, js
errorreporter er); name type description cx jsruntime * pointer to a js runtime whose
errors should be reported via your function. ...
...any time. try to avoid using it. get or specify the
error reporting mechanism for an application. syntax js
errorreporter js_get
errorreporter(jsruntime *rt); js
errorreporter js_set
errorreporter(jsruntime *rt, js
errorreporter er); name type description cx jsruntime * pointer to a js runtime whose
errors should be reported via your function. er js
errorreporter the user-defined
error reporting function to use in your application, described below. callback syntax typedef void (* js
errorreporter)(jscontext *cx, const char *message, js
errorreport *report); name type description cx jscontext * the context in which the
error happened. message const char * an
error message. report j...
...eporter the user-defined
error reporting function to use in your application, described below. callback syntax typedef void (* js
errorreporter)(jscontext *cx, const char *message, js
errorreport *report); name type description cx jscontext * the context in which the
error happened. message const char * an
error message. report js
errorreport * an
error report record containing additional details about the
error. description js_set
errorreporter enables you to define and use your own
error reporting mechanism in your applications. the reporter you define is automatically passed a js
errorreport structure when an
error occurs and has been parsed by js_report
error. ...
...And 10 more matches
nsIErrorService
xpcom/base/nsi
errorservice.idlscriptable this is a service that allows nsresult codes to be mapped to string bundles that can be used to look up
error messages. string bundle keys can also be mapped. ...
... xpcom/base/nsi
errorservice.idlscriptable this is a service that allows nsresult codes to be mapped to string bundles that can be used to look up
error messages. string bundle keys can also be mapped. ...
... xpcom/base/nsi
errorservice.idlscriptable this is a service that allows nsresult codes to be mapped to string bundles that can be used to look up
error messages. string bundle keys can also be mapped. ...
...And 10 more matches
MediaError.message - Web APIs
the read-only property media
error.message returns a domstring which contains a human-readable string offering specific diagnostic details related to the
error described by the media
error object, or an empty string ("") if no diagnostic information can be determined or provided. syntax var
errormessage = media
error.message; value a domstring providing a detailed, specific explanation of what went wrong and possibly how it might be fixed. this is not simply a generic description of the media
error.code property's value, but instead goes deeper into the specifics of this particular
error and its circumstances. if no specific details are available, this string is empty. ...
...ing providing a detailed, specific explanation of what went wrong and possibly how it might be fixed. this is not simply a generic description of the media
error.code property's value, but instead goes deeper into the specifics of this particular
error and its circumstances. if no specific details are available, this string is empty. example this example creates a <audio> element, establishes an
error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute. the
error handler simply outputs a message to a box onscreen describing the
error, including both the code and the message. only the relevant parts of the code are displayed; you can see the complete source code here. the example creates an <audio> el...
...ute. the
error handler simply outputs a message to a box onscreen describing the
error, including both the code and the message. only the relevant parts of the code are displayed; you can see the complete source code here. the example creates an <audio> element and lets the user assign either a valid music file to it, or a link to a file which doesn't exist. this lets us see the behavior of the
error event handler, which is received by an event handler we add to the <audio> element itself. ...
...And 10 more matches
AggregateError - JavaScript
the aggregate
error object represents an
error when several
errors need to be wrapped in a single
error. it is thrown when multiple
errors need to be reported by an operation, for example by promise.any(), when all promises passed to it reject. constructor aggregate
error() creates a new aggregate
error object. instance properties aggregate
error.prototype.message
error message, defaults to "". aggregate
error.prototype.name
error name, defaults to aggregate
error. ...
...thrown when multiple
errors need to be reported by an operation, for example by promise.any(), when all promises passed to it reject. constructor aggregate
error() creates a new aggregate
error object. instance properties aggregate
error.prototype.message
error message, defaults to "". aggregate
error.prototype.name
error name, defaults to aggregate
error. ...
...orted by an operation, for example by promise.any(), when all promises passed to it reject. constructor aggregate
error() creates a new aggregate
error object. instance properties aggregate
error.prototype.message
error message, defaults to "". aggregate
error.prototype.name
error name, defaults to aggregate
error. ...
...And 8 more matches
WebAssembly.RuntimeError - JavaScript
the webassembly.runtime
error object is the
error type that is thrown whenever webassembly specifies a trap. constructor webassembly.runtime
error() creates a new webassembly.runtime
error object. instance properties webassembly.runtime
error.prototype.message
error message. although ecma-262 specifies that uri
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. webassembly.runtime
error.prototype.name
error name. inherited from
error. webassembly.runtime
error.prototype.filename path to file that raised this
error. inherited from
error. webassembly.runtime
error.prototype.linenumber line number in file that raised this
error. inherited from
error. ...
...vide its own message property, in spidermonkey, it inherits
error.prototype.message. webassembly.runtime
error.prototype.name
error name. inherited from
error. webassembly.runtime
error.prototype.filename path to file that raised this
error. inherited from
error. webassembly.runtime
error.prototype.linenumber line number in file that raised this
error. inherited from
error. webassembly.runtime
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. webassembly.runtime
error.prototype.stack stack trace. inherited from
error. instance methods webassembly.runtime
error.prototype.tosource() returns code that could eval to the same
error. inherited from
error. ...
...hat raised this
error. inherited from
error. webassembly.runtime
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. webassembly.runtime
error.prototype.stack stack trace. inherited from
error. instance methods webassembly.runtime
error.prototype.tosource() returns code that could eval to the same
error. inherited from
error. webassembly.runtime
error.prototype.tostring() returns a string representing the specified
error object.. inherited from
error. ...
...And 8 more matches
PR_SetError
the runtime merely stores the value and returns it when requested. ...
...the runtime merely stores the value and returns it when requested. ...
...the runtime merely stores the value and returns it when requested. ...
...And 7 more matches
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 my
error = request.
error; value a dom
error containing the relevant
error. in chrome 48+/firefox 58+ this property returns a domexception because dom
error has been removed from the dom standard. the following
error codes are returned under certain conditions:
error explanation abort
error if you abort the transaction, then all requests still in progress receive this
error. constraint
error if you insert data that doesn't conform to a constraint. it's an exception type for creating stores and indexes. ...
... been removed from the dom standard. the following
error codes are returned under certain conditions:
error explanation abort
error if you abort the transaction, then all requests still in progress receive this
error. constraint
error 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 the record. quotaexceeded
error if you run out of disk quota and the user declined to grant you more space. unknown
error if the operation failed for reasons unrelated to the database itself. a failure due to disk io
errors is such an example. ...
... type for creating stores and indexes. you get this
error, for example, if you try to add a new key that already exists in the record. quotaexceeded
error if you run out of disk quota and the user declined to grant you more space. unknown
error if the operation failed for reasons unrelated to the database itself. a failure due to disk io
errors is such an example. no
error if the request succeeds. version
error 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 b...
...And 7 more matches
RTCDataChannel: error event - Web APIs
a webrtc
error event is sent to an rtcdatachannel object's on
error error handler when an
error occurs on the data channel. bubbles yes cancelable no interface rtc
errorevent event handler property on
error the rtc
errorevent object provides details about the
error that occurred; see that article for details. ...
... cancelable no interface rtc
errorevent event handler property on
error the rtc
errorevent object provides details about the
error that occurred; see that article for details. ...
...operty on
error the rtc
errorevent object provides details about the
error that occurred; see that article for details. ...
...And 7 more matches
Network Error Logging - HTTP
network
error logging is a mechanism that can be configured via the nel http response header. this experimental header allows web sites and applications to opt-in to receive reports about failed (and, if desired, successful) network fetches from supporting browsers. reports are sent to a reporting group defined within a report-to header. usage web applications opt in to this behaviour with the nel header, which is a json-encoded object: nel: { "report_to": "nel", "max_age": 31556952 } an origin considered secure by the browser is required. the following object keys can be specified in the nel header: report_to the reporting api group to send network
error reports to (see below). max_age specifies the lifetime of the policy, in seconds (in a similar way to e.g. hsts po...
.... defaults to 1, so that all failed network requests will be reported if the key is not present in the json payload. ...
...reporting group referenced above is defined in the usual manner within the report-to header, for example: report-to: { "group": "nel", "max_age": 31556952, "endpoints": [ { "url": "https://example.com/csp-reports" } ] }
error reports in these examples, the entire reporting api payload is shown. the top-level "body" key contains the network
error report. ...
...And 7 more matches
SyntaxError() constructor - JavaScript
the syntax
error constructor creates a new
error object that represents an
error when trying to interpret syntactically invalid code. ...
... the syntax
error constructor creates a new
error object that represents an
error when trying to interpret syntactically invalid code. ...
... the syntax
error constructor creates a new
error object that represents an
error when trying to interpret syntactically invalid code. ...
...And 7 more matches
WebAssembly.CompileError - JavaScript
the webassembly.compile
error object indicates an
error during webassembly decoding or validation. constructor webassembly.compile
error() creates a new webassembly.compile
error object. instance properties webassembly.compile
error.prototype.message
error message. although ecma-262 specifies that uri
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. webassembly.compile
error.prototype.name
error name. inherited from
error. webassembly.compile
error.prototype.filename path to file that raised this
error. inherited from
error. webassembly.compile
error.prototype.linenumber line number in file that raised this
error. inherited from
error. webassembly.compile
error.prototype.columnnumber column number in line that raised this
error. inh...
...sembly.compile
error.prototype.name
error name. inherited from
error. webassembly.compile
error.prototype.filename path to file that raised this
error. inherited from
error. webassembly.compile
error.prototype.linenumber line number in file that raised this
error. inherited from
error. webassembly.compile
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. webassembly.compile
error.prototype.stack stack trace. inherited from
error. instance methods webassembly.compile
error.prototype.tosource() returns code that could eval to the same
error. inherited from
error. webassembly.compile
error.prototype.tostring() returns a string representing the specified
error object.. inherited from
error. ...
...herited from
error. webassembly.compile
error.prototype.stack stack trace. inherited from
error. instance methods webassembly.compile
error.prototype.tosource() returns code that could eval to the same
error. inherited from
error. webassembly.compile
error.prototype.tostring() returns a string representing the specified
error object.. inherited from
error. ...
...And 7 more matches
WebAssembly.LinkError - JavaScript
the webassembly.link
error object indicates an
error during module instantiation (besides traps from the start function). constructor webassembly.link
error() creates a new webassembly.link
error object. instance properties webassembly.link
error.prototype.message
error message. although ecma-262 specifies that uri
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. webassembly.link
error.prototype.name
error name. inherited from
error. webassembly.link
error.prototype.filename path to file that raised this
error. inherited from
error. webassembly.link
error.prototype.linenumber line number in file that raised this
error. inherited from
error. webassembly.link
error.prototype.columnnumber column number in line that raised this
error. i...
...sage. webassembly.link
error.prototype.name
error name. inherited from
error. webassembly.link
error.prototype.filename path to file that raised this
error. inherited from
error. webassembly.link
error.prototype.linenumber line number in file that raised this
error. inherited from
error. webassembly.link
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. webassembly.link
error.prototype.stack stack trace. inherited from
error. instance methods webassembly.link
error.prototype.tosource() returns code that could eval to the same
error. inherited from
error. webassembly.link
error.prototype.tostring() returns a string representing the specified
error object.. inherited from
error. ...
...is
error. inherited from
error. webassembly.link
error.prototype.stack stack trace. inherited from
error. instance methods webassembly.link
error.prototype.tosource() returns code that could eval to the same
error. inherited from
error. webassembly.link
error.prototype.tostring() returns a string representing the specified
error object.. inherited from
error. ...
...And 7 more matches
TypeError: setting getter-only property "x" - JavaScript
there is an attempt to set a new value to a property for which only a getter is specified. ...
... there is an attempt to set a new value to a property for which only a getter is specified. ...
... there is an attempt to set a new value to a property for which only a getter is specified. ...
...And 6 more matches
RangeError: precision is out of range - JavaScript
the javascript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into tofixed or toprecision. ...
... the javascript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into tofixed or toprecision. ...
... the javascript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into tofixed or toprecision. ...
...And 6 more matches
TypeError: "x" is (not) "y" - JavaScript
what went wrong? there was an unexpected type. this occurs oftentimes with undefined or null values. ...
... what went wrong? there was an unexpected type. this occurs oftentimes with undefined or null values. ...
... what went wrong? there was an unexpected type. this occurs oftentimes with undefined or null values. ...
...And 6 more matches
Error.prototype.stack - JavaScript
the non-standard stack property of
error objects offer a trace of which functions were called, in what order, from which line and file, and with what arguments. the stack string proceeds from the most recent calls to earlier ones, leading back to the original global scope call. description each step will be separated by a newline, with the first part of the line being the function name (if not a call from the global scope), then by an at (@) sign, the file location (except when the function is the
error constructor as the
error is being thrown), a colon, and, if there is a file location, the line number. ...
..., leading back to the original global scope call. description each step will be separated by a newline, with the first part of the line being the function name (if not a call from the global scope), then by an at (@) sign, the file location (except when the function is the
error constructor as the
error is being thrown), a colon, and, if there is a file location, the line number. (note that the
error object also possesses the filename, linenumber and columnnumber properties for retrieving these from the
error thrown (but only the
error, and not its trace).) note that this is the format used by firefox. there is no standard formatting. however, safari 6+ and opera 12- use a very similar format. browsers using the v8 javascript engine (such as chrome, opera 15+, android browser) and ie10+, on ...
... argument values in the stack: prior to firefox 14, the function name would be followed by the argument values converted to string in parentheses immediately before the at (@) sign. ...
...And 6 more matches
WebAssembly.RuntimeError() constructor - JavaScript
the webassembly.runtime
error() constructor creates a new webassembly runtime
error object — the type that is thrown whenever webassembly specifies a trap. syntax new webassembly.runtime
error(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. ...
...ype that is thrown whenever webassembly specifies a trap. syntax new webassembly.runtime
error(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. ...
...syntax new webassembly.runtime
error(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. ...
...And 6 more matches
DedicatedWorkerGlobalScope: messageerror event - Web APIs
the message
error event is fired on a dedicatedworkerglobalscope object when it receives a message that can't be deserialized. ...
... the message
error event is fired on a dedicatedworkerglobalscope object when it receives a message that can't be deserialized. ...
... the message
error event is fired on a dedicatedworkerglobalscope object when it receives a message that can't be deserialized. ...
...And 5 more matches
ErrorEvent - Web APIs
the
errorevent interface represents events providing information related to
errors in scripts or in files. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/event" target="_top"><rect x="1" y="1" width="75" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">event</text></a><polyline points="76,25 86,20 86,30 76,25" stroke="#d4dde4" fill="none"/><line x1="86" y1...
...75" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">event</text></a><polyline points="76,25 86,20 86,30 76,25" stroke="#d4dde4" fill="none"/><line x1="86" y1="25" x2="116" y2="25" stroke="#d4dde4"/><a xlink:href="/docs/web/api/
errorevent" target="_top"><rect x="116" y="1" width="100" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="166" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">
errorevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties also inherits prope...
...6" y="1" width="100" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="166" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">
errorevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties also inherits properties from its parent event.
errorevent.message read only is a domstring containing a human-readable
error message describing the problem. ...
...And 5 more matches
MediaRecorder.onerror - Web APIs
the mediarecorder interface's on
error 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 mediarecorder
errorevent, and its
error property contains a domexception object that describes the
error that occurred. syntax mediarecorder.on
error =
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 mediarecorder
errorevent.
error.name. ...
...at occurred. syntax mediarecorder.on
error =
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 mediarecorder
errorevent.
error.name. invalidstate
error 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. security
error the mediastream is configured to disallow recording. this may be the case, for example, with sources obtained using g...
... a source that has been deleted or removed. security
error 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. notsupported
error an attempt was made to instantiate a mediarecorder using a mime type that isn't supported on the user's device; one or more of the requested container, codecs, or profiles as well as other information may be invalid. unknown
error an non-security related
error occurred that cannot otherwise be categorized. recording stops, the mediarecorder's state becomes inactive, one last dataavailable event...
...And 5 more matches
RTCErrorEvent - Web APIs
methods no additional methods are provided beyond any found on the parent interface, event. ...
... methods no additional methods are provided beyond any found on the parent interface, event. ...
... methods no additional methods are provided beyond any found on the parent interface, event. ...
...And 5 more matches
RTCPeerConnection: icecandidateerror event - Web APIs
the webrtc api event icecandidate
error is sent to an rtcpeerconnection if an
error occurs while performing ice negotiations through a stun or turn server. the event object is of type rtcpeerconnectionice
errorevent, and contains information describing the
error in some amount of detail. bubbles no cancelable no interface rtcpeerconnectionice
errorevent event handler property rtcpeerconnection.onicecandidate
error description the
error object's
errorcode property is one of the numeric stun
error codes. there is one additional, webrtc-specific,
error which lies outside the valid stun
error code range: 701. ...
...me amount of detail. bubbles no cancelable no interface rtcpeerconnectionice
errorevent event handler property rtcpeerconnection.onicecandidate
error description the
error object's
errorcode property is one of the numeric stun
error codes. there is one additional, webrtc-specific,
error which lies outside the valid stun
error code range: 701.
error 701 indicates that none of the ice candidates were able to successfully make contact with the stun or turn server. the 701
error is fired only once per server url from the list of available stun or turn servers provided when creating the rtcpeerconnection. these
errors occur only when the connection's ice gathering state is gathering. example the following example establishes a handler for ice...
...cates that none of the ice candidates were able to successfully make contact with the stun or turn server. the 701
error is fired only once per server url from the list of available stun or turn servers provided when creating the rtcpeerconnection. these
errors occur only when the connection's ice gathering state is gathering. example the following example establishes a handler for icecandidate
errors that occur on the rtcpeerconnection pc. this handler looks specifically for 701
errors that indicate that candidates couldn't reach the stun or turn server. ...
...And 5 more matches
Window: messageerror event - Web APIs
the message
error event is fired on a window object when it receives a message that can't be deserialized. ...
... the message
error event is fired on a window object when it receives a message that can't be deserialized. ...
... the message
error event is fired on a window object when it receives a message that can't be deserialized. ...
...And 5 more matches
SyntaxError: illegal character - JavaScript
use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign ( - ) versus a dash ( – ) or simple quotes ( " ) vs non-standard quotation marks ( “ ). ...
...use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign ( - ) versus a dash ( – ) or simple quotes ( " ) vs non-standard quotation marks ( “ ). ...
...use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign ( - ) versus a dash ( – ) or simple quotes ( " ) vs non-standard quotation marks ( “ ). ...
...And 5 more matches
TypeError: invalid assignment to const "x" - JavaScript
a constant is a value that cannot be altered by the program during normal execution. it cannot change through re-assignment, and it can't be redeclared. ...
... a constant is a value that cannot be altered by the program during normal execution. it cannot change through re-assignment, and it can't be redeclared. ...
... a constant is a value that cannot be altered by the program during normal execution. it cannot change through re-assignment, and it can't be redeclared. ...
...And 5 more matches
SyntaxError: Malformed formal parameter - JavaScript
the last argument is the source code for the new function you're creating. all the rest make up your new function's argument list. the argument list is invalid somehow. ...
...the last argument is the source code for the new function you're creating. all the rest make up your new function's argument list. the argument list is invalid somehow. ...
...the last argument is the source code for the new function you're creating. all the rest make up your new function's argument list. the argument list is invalid somehow. ...
...And 5 more matches
TypeError: "x" is not a non-null object - JavaScript
null is not an object and won't work. you must provide a proper object in the given situation. ...
...null is not an object and won't work. you must provide a proper object in the given situation. ...
...null is not an object and won't work. you must provide a proper object in the given situation. ...
...And 5 more matches
TypeError: "x" is not a function - JavaScript
some code expects you to provide a function, but that didn't happen. ...
...some code expects you to provide a function, but that didn't happen. ...
...some code expects you to provide a function, but that didn't happen. ...
...And 5 more matches
SyntaxError: Unexpected token - JavaScript
a specific language construct was expected, but something else was provided. this might be a simple typo. ...
... a specific language construct was expected, but something else was provided. this might be a simple typo. ...
... a specific language construct was expected, but something else was provided. this might be a simple typo. ...
...And 5 more matches
Error.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified
error object. syntax e.tostring() return value a string representing the specified
error object. description the
error object overrides the object.prototype.tostring() method inherited by all objects. ...
... the tostring() method returns a string representing the specified
error object. syntax e.tostring() return value a string representing the specified
error object. description the
error object overrides the object.prototype.tostring() method inherited by all objects. ...
...ntax e.tostring() return value a string representing the specified
error object. description the
error object overrides the object.prototype.tostring() method inherited by all objects. ...
...And 5 more matches
TypeError - JavaScript
the type
error object represents an
error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. a type
error may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or when attempting to modify a value that cannot be changed; or when attempting to use a value in an inappropriate way. constructor type
error() creates a new type
error object. instance properties type
error.prototype.message
error message. although ecma-262 specifies that type
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. type
error.prototype.name
error name. inherited from
error. ...
...ged; or when attempting to use a value in an inappropriate way. constructor type
error() creates a new type
error object. instance properties type
error.prototype.message
error message. although ecma-262 specifies that type
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. type
error.prototype.name
error name. inherited from
error. type
error.prototype.filename path to file that raised this
error. inherited from
error. type
error.prototype.linenumber line number in file that raised this
error. inherited from
error. type
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. ...
...key, it inherits
error.prototype.message. type
error.prototype.name
error name. inherited from
error. type
error.prototype.filename path to file that raised this
error. inherited from
error. type
error.prototype.linenumber line number in file that raised this
error. inherited from
error. type
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. type
error.prototype.stack stack trace. inherited from
error. ...
...And 5 more matches
WebAssembly.CompileError() constructor - JavaScript
the webassembly.compile
error() constructor creates a new webassembly compile
error object, which indicates an
error during webassembly decoding or validation. syntax new webassembly.compile
error(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. ...
...cates an
error during webassembly decoding or validation. syntax new webassembly.compile
error(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. ...
...syntax new webassembly.compile
error(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. ...
...And 5 more matches
WebAssembly.LinkError() constructor - JavaScript
the webassembly.link
error() constructor creates a new webassembly link
error object, which indicates an
error during module instantiation (besides traps from the start function). syntax new webassembly.link
error(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. ...
...g module instantiation (besides traps from the start function). syntax new webassembly.link
error(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. ...
...ction). syntax new webassembly.link
error(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. ...
...And 5 more matches
OS.File.Error
instances of os.file.
error are used by os.file to notify of file-related
errors. using os.file.
error example: finding out whether the problem is due to a file that does not exist try { let file = os.file.open("myfile.txt"); // ... } catch (ex) { if (ex instanceof os.file.
error && ex.becausenosuchfile) { // the file does not exist } } global object os.file.
error methods overview the following functions are utility functions that may be used to construct instances of os.file.
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.er...
...cross-platform attributes operation the human-readable name of the failed operation. ...
...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. ...
...And 4 more matches
Components.utils.reportError
components.utils.report
error 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. it must be called with one parameter, usually an object which was caught by an exception handler. 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.report
error to report debugging messages to the
error console, just like dump() can be used to print messages to the native console. however you should use nsiconsoleservice for logging, as it logs the messages with normal severity, unlike report
error. function mydump(amessage) { var console...
...to show them, set the preference 'javascript.options.showinconsole' to true, or use nsconsoleservice instead to show a message. ...
...eservice for logging, as it logs the messages with normal severity, unlike report
error. function mydump(amessage) { var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); consoleservice.logstringmessage("my component: " + amessage); } firefox 3: the
error console will not display chrome
errors by default. to show them, set the preference 'javascript.options.showinconsole' to true, or use nsconsoleservice instead to show a message. firefox 4: the preference 'javascript.options.showinconsole' is set to true by default in this version. ...
...And 4 more matches
AddressErrors.country - Web APIs
if the paymentaddress object's country property was determined to be valid, this property is not included in the dictionary. ...
... if the paymentaddress object's country property was determined to be valid, this property is not included in the dictionary. ...
... if the paymentaddress object's country property was determined to be valid, this property is not included in the dictionary. ...
...And 4 more matches
FileError - Web APIs
represents an
error that occurs while using the filereader interface. note: this interface is obsolete per the latest specification. use the new dom4 dom
error interface instead. in the file system api, a file
error represents
error conditions that you might encounter while accessing the file system using the asynchronous api. it extends the file
error interface described in file writer and adds several new
error codes. file
error 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. ...
...a web app could fail for various reasons, so you don't want to spend the rest of your day guessing what's going on and going through maddening troubleshooting. ...
...a web app could fail for various reasons, so you don't want to spend the rest of your day guessing what's going on and going through maddening troubleshooting. ...
...And 4 more matches
MediaRecorder: error event - Web APIs
the mediarecorder interface's
error event is fired when an
error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. bubbles no cancelable no interface mediarecorder
errorevent event handler property on
error for details of the all the possible
errors see the documentation for the event handler property: on
error. ...
...r occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. bubbles no cancelable no interface mediarecorder
errorevent event handler property on
error for details of the all the possible
errors see the documentation for the event handler property: on
error. ...
... event handler property on
error for details of the all the possible
errors see the documentation for the event handler property: on
error. ...
...And 4 more matches
SyntaxError: invalid regular expression flag "x" - JavaScript
in a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. ...
...in a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. ...
...in a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. ...
...And 4 more matches
SyntaxError: missing : after property id - JavaScript
when creating objects with the object initializer syntax, a colon (:) separates keys and values for the object's properties. ...
... when creating objects with the object initializer syntax, a colon (:) separates keys and values for the object's properties. ...
... when creating objects with the object initializer syntax, a colon (:) separates keys and values for the object's properties. ...
...And 4 more matches
SyntaxError: missing variable name - JavaScript
probably a comma is wrong somewhere or you struggled with coming up with a name. totally understandable! naming things is so hard. check to ensure the previous lines / declaration does not end with a comma instead of a semi-colon. ...
...probably a comma is wrong somewhere or you struggled with coming up with a name. totally understandable! naming things is so hard. check to ensure the previous lines / declaration does not end with a comma instead of a semi-colon. ...
...probably a comma is wrong somewhere or you struggled with coming up with a name. totally understandable! naming things is so hard. check to ensure the previous lines / declaration does not end with a comma instead of a semi-colon. ...
...And 4 more matches
RangeError: argument is not a valid code point - JavaScript
the javascript exception "invalid code point" occurs when nan values, negative integers (-1), non-integers (5.4), or values larger than 0x10ffff (1114111) are used with string.fromcodepoint(). message range
error: {0} is not a valid code point (firefox) range
error: invalid code point {0} (chromium)
error type range
error what went wrong? string.fromcodepoint() throws this
error when passed nan values, negative integers (-1), non-integers (5.4), or values larger than 0x10ffff (1114111). ...
...r: invalid code point {0} (chromium)
error type range
error what went wrong? ...
...ype range
error what went wrong? ...
...And 4 more matches
SyntaxError: "x" is a reserved identifier - JavaScript
reserved keywords will throw in if they are used as identifiers. ...
... reserved keywords will throw in if they are used as identifiers. ...
... reserved keywords will throw in if they are used as identifiers. ...
...And 4 more matches
RangeError: repeat count must be less than infinity - JavaScript
it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. ...
...it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. ...
...it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. ...
...And 4 more matches
InternalError: too much recursion - JavaScript
what went wrong? a function that calls itself is called a recursive function. once a condition is met, the function stops calling itself. this is called a base case. in some ways, recursion is analogous to a loop. ...
... what went wrong? a function that calls itself is called a recursive function. once a condition is met, the function stops calling itself. this is called a base case. in some ways, recursion is analogous to a loop. ...
... what went wrong? a function that calls itself is called a recursive function. once a condition is met, the function stops calling itself. this is called a base case. in some ways, recursion is analogous to a loop. ...
...And 4 more matches
TypeError: invalid 'instanceof' operand 'x' - JavaScript
the javascript exception "invalid 'instanceof' operand" occurs when the right hand side operands of the instanceof operator isn't used with a constructor object, i.e. an object which has a prototype property and is callable. ...
... the javascript exception "invalid 'instanceof' operand" occurs when the right hand side operands of the instanceof operator isn't used with a constructor object, i.e. an object which has a prototype property and is callable. ...
... the javascript exception "invalid 'instanceof' operand" occurs when the right hand side operands of the instanceof operator isn't used with a constructor object, i.e. an object which has a prototype property and is callable. ...
...And 4 more matches
InternalError - JavaScript
the internal
error object indicates an
error that occurred internally in the javascript engine. example cases are mostly when something is too large, e.g.: "too many switch cases", "too many parentheses in regular expression", "array initializer too large", "too much recursion". constructor internal
error() creates a new internal
error object. instance properties internal
error.prototype.message
error message. inherited from
error. internal
error.prototype.name
error name. inherited from
error. internal
error.prototype.filename path to file that raised this
error. inherited from
error. internal
error.prototype.linenumber line number in file that raised this
error. inherited from
error. ...
... examples too much recursion this recursive function runs 10 times, as per the exit condition. ...
... examples too much recursion this recursive function runs 10 times, as per the exit condition. ...
...And 4 more matches
ReferenceError - JavaScript
the reference
error object represents an
error when a non-existent variable is referenced. constructor reference
error() creates a new reference
error object. instance properties reference
error.prototype.message
error message. although ecma-262 specifies that reference
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. reference
error.prototype.name
error name. inherited from
error. reference
error.prototype.filename path to file that raised this
error. inherited from
error. reference
error.prototype.linenumber line number in file that raised this
error. inherited from
error. reference
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. reference
error.prototype.stack stack trace. inherit...
...ror name. inherited from
error. reference
error.prototype.filename path to file that raised this
error. inherited from
error. reference
error.prototype.linenumber line number in file that raised this
error. inherited from
error. reference
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. reference
error.prototype.stack stack trace. inherited from
error. ...
...nce
error.prototype.filename path to file that raised this
error. inherited from
error. reference
error.prototype.linenumber line number in file that raised this
error. inherited from
error. reference
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. reference
error.prototype.stack stack trace. inherited from
error. ...
...And 4 more matches
Error.number - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the
error.number property returns or sets the numeric value associated with a specific
error. the
error object's default property is number. syntax object .number [=
errornumber] parameters 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 { // ca...
...ror 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. ...
...ity 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 message: ") document.write (e.message) } example the output of this code is as follows. ...
...And 3 more matches
JS::CreateError
this article covers features introduced in spidermonkey 38 create an
error object. syntax // added in spidermonkey 45 bool js::create
error(jscontext *cx, jsexntype type, handleobject stack, handlestring filename, uint32_t linenumber, uint32_t columnnumber, js
errorreport *report, handlestring message, mutablehandlevalue rval); // obsolete since jsapi 39 bool js::create
error(jscontext *cx, jsexntype type, handlestring stack, handlestring filename, uint32_t linenumber, uint32_t columnnumber, js
errorreport *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_...
...andlestring 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. ...
...cription 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 js
errorreport * a pointer to js
errorreport instance. message js::handlestring the value of
error.prototype.message. rval js::mutablehandlevalue out parameter. receives the...
...And 3 more matches
Source map errors - Firefox Developer Tools
e maps are json files providing a way to associate transformed sources, as seen by the browser, with their original sources, as written by the developer. you can sometimes encounter problems working with source maps. this page explains the most common problems and how to fix them. note: if you're new to source maps, you can learn more about them in how to use a source map. ...
...iginal sources, as written by the developer. you can sometimes encounter problems working with source maps. this page explains the most common problems and how to fix them. note: if you're new to source maps, you can learn more about them in how to use a source map. general source map
error reporting if you do see a problem, a message will appear in the webconsole. this message will show an
error message, the resource url, and the source map url: here, the resource url tells us that bundle.js mentions a source map, and the source map url tells us where to find the source map data (in this case, relative to the resource). the
error tells us that the source map is not json data — so we're serving the wrong file. there are a few common ways that source maps can go wrong; they are deta...
...ys that source maps can go wrong; they are detailed in the following sections. source map missing or inaccessible the source map resource can be missing or inaccessible. the fix here is to make sure the file is being served and is accessible to the browser invalid source map the source map data can be invalid — either simply not a json file at all, or with an incorrect structure. ...
...And 3 more matches
AddressErrors.regionCode - Web APIs
usage notes the region code is derived from the iso 3166-2 country subdivision name standard. ...
... usage notes the region code is derived from the iso 3166-2 country subdivision name standard. ...
... usage notes the region code is derived from the iso 3166-2 country subdivision name standard. ...
...And 3 more matches
Document: pointerlockerror event - Web APIs
the pointerlock
error event is fired when locking the pointer failed (for technical reasons or because the permission was denied). ...
... the pointerlock
error event is fired when locking the pointer failed (for technical reasons or because the permission was denied). ...
... the pointerlock
error event is fired when locking the pointer failed (for technical reasons or because the permission was denied). ...
...And 3 more matches
IDBDatabase.onerror - Web APIs
the on
error event handler of the idbdatabase interface handles the
error event, fired when a request returns an
error and bubbles up to the connection object. note: consider using idbopendbrequest.onsuccess instead (see idbrequest.onsuccess, where it is inherited from). note: this feature is available in web workers. syntax idbdatabase.on
error = function(event) { ... } example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes on
error and onabort functions to handle non-success cases. ...
...s, where it is inherited from). note: this feature is available in web workers. syntax idbdatabase.on
error = function(event) { ... } example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes on
error and onabort functions to handle non-success cases. ...
...is available in web workers. syntax idbdatabase.on
error = function(event) { ... } example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes on
error and onabort functions to handle non-success cases. ...
...And 3 more matches
IDBRequest: error event - Web APIs
the
error handler is executed when an
error caused a request to fail. ...
... the
error handler is executed when an
error caused a request to fail. ...
... the
error handler is executed when an
error caused a request to fail. ...
...And 3 more matches
IDBTransaction.onerror - Web APIs
the on
error event handler of the idbtransaction interface handles the
error event, fired when a request returns an
error and bubbles up to the transaction object. note: consider using idbtransaction.onabort instead to handle non- successful completion of the transaction. note: this feature is available in web workers. syntax transaction.on
error = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. ...
...this feature is available in web workers. syntax transaction.on
error = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.on
error = function(event) { }; block, making use of transaction.
error to help in reporting what went wrong when the transaction was unsuccessful. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</...
...ay: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error: ' + transaction.
error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report t...
...And 3 more matches
RTCPeerConnectionIceErrorEvent.address - Web APIs
this address identifies the network interface on the local device which is being used to attempt to establish the connection to the remote peer. this can be useful on multi-homed systems—devices with more than one network connection—to determine which network interface is being used. ...
...this address identifies the network interface on the local device which is being used to attempt to establish the connection to the remote peer. ...
......
...And 3 more matches
SpeechRecognition: error event - Web APIs
the
error event of the web speech api speechrecognition object is fired when a speech recognition
error occurs. ...
... the
error event of the web speech api speechrecognition object is fired when a speech recognition
error occurs. ...
... the
error event of the web speech api speechrecognition object is fired when a speech recognition
error occurs. ...
...And 3 more matches
SpeechSynthesisUtterance: error event - Web APIs
the
error event of the web speech api speechsynthesisutterance object is fired when an
error occurs that prevents the utterance from being succesfully spoken. ...
... the
error event of the web speech api speechsynthesisutterance object is fired when an
error occurs that prevents the utterance from being succesfully spoken. ...
... the
error event of the web speech api speechsynthesisutterance object is fired when an
error occurs that prevents the utterance from being succesfully spoken. ...
...And 3 more matches
XMLHttpRequest: error event - Web APIs
the
error event is fired when the request encountered an
error. ...
... the
error event is fired when the request encountered an
error. ...
... the
error event is fired when the request encountered an
error. ...
...And 3 more matches
SyntaxError: return not in function - JavaScript
a return or yield statement is called outside of a function. maybe there are missing curly brackets somewhere? ...
... a return or yield statement is called outside of a function. maybe there are missing curly brackets somewhere? ...
... a return or yield statement is called outside of a function. maybe there are missing curly brackets somewhere? ...
...And 3 more matches
TypeError: can't redefine non-configurable property "x" - JavaScript
the configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. ...
...the configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. ...
...the configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. ...
...And 3 more matches
TypeError: cyclic object value - JavaScript
the json format per se doesn't support object references (although an ietf draft exists), hence json.stringify() doesn't try to solve them and fails accordingly. ...
... the json format per se doesn't support object references (although an ietf draft exists), hence json.stringify() doesn't try to solve them and fails accordingly. ...
... the json format per se doesn't support object references (although an ietf draft exists), hence json.stringify() doesn't try to solve them and fails accordingly. ...
...And 3 more matches
SyntaxError: missing = in const declaration - JavaScript
it cannot change through re-assignment, and it can't be redeclared. ...
...it cannot change through re-assignment, and it can't be redeclared. ...
...it cannot change through re-assignment, and it can't be redeclared. ...
...And 3 more matches
SyntaxError: missing ) after condition - JavaScript
in any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. the if statement executes a statement if a specified condition is truthy. ...
...in any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. the if statement executes a statement if a specified condition is truthy. ...
...in any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. the if statement executes a statement if a specified condition is truthy. ...
...And 3 more matches
SyntaxError: missing ; before statement - JavaScript
the javascript exception "missing ; before statement" occurs when there is a semicolon (;) missing somewhere and can't be added by automatic semicolon insertion (asi). you need to provide a semicolon, so that javascript can parse the source code correctly. message syntax
error: expected ';' (edge) syntax
error: missing ; before statement (firefox)
error type syntax
error. what went wrong? there is a semicolon (;) missing somewhere. javascript statements must be terminated with semicolons. some of them are affected by automatic semicolon insertion (asi), but in this case you need to provide a semicolon, so that javascript can parse the source code correctly. however, oftentimes, this
error is only a consequence of another
error, like not escaping strings properly, or using var wrongly. you...
...colons. some of them are affected by automatic semicolon insertion (asi), but in this case you need to provide a semicolon, so that javascript can parse the source code correctly. however, oftentimes, this
error is only a consequence of another
error, like not escaping strings properly, or using var wrongly. you might also have too many parenthesis somewhere. carefully check the syntax when this
error is thrown. examples unescaped strings this
error can occur easily when not escaping strings properly and the javascript engine is expecting the end of your string already. ...
...equence of another
error, like not escaping strings properly, or using var wrongly. you might also have too many parenthesis somewhere. carefully check the syntax when this
error is thrown. examples unescaped strings this
error can occur easily when not escaping strings properly and the javascript engine is expecting the end of your string already. for example: var foo = 'tom's bar'; // syntax
error: missing ; before statement you can use double quotes, or escape the apostrophe: var foo = "tom's bar"; var foo = 'tom\'s bar'; declaring properties with var you cannot declare properties of an object or array with a var declaration. ...
...And 3 more matches
TypeError: can't delete non-configurable array element - JavaScript
when shortening an array, the elements beyond the new array length will be deleted, which failed in this situation. ...
...when shortening an array, the elements beyond the new array length will be deleted, which failed in this situation. ...
...when shortening an array, the elements beyond the new array length will be deleted, which failed in this situation. ...
...And 3 more matches
SyntaxError: redeclaration of formal parameter "x" - JavaScript
the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. ...
... the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. ...
... the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. ...
...And 3 more matches
AggregateError() constructor - JavaScript
the aggregate
error() constructor creates an
error for several
errors that need to be wrapped in a single
error. syntax new aggregate
error(
errors[, message]) parameters
errors an iterable of
errors, may not actually be
error instances. messageoptional an optional human-readable description of the aggregate
error. ...
... the aggregate
error() constructor creates an
error for several
errors that need to be wrapped in a single
error. syntax new aggregate
error(
errors[, message]) parameters
errors an iterable of
errors, may not actually be
error instances. messageoptional an optional human-readable description of the aggregate
error. ...
... the aggregate
error() constructor creates an
error for several
errors that need to be wrapped in a single
error. syntax new aggregate
error(
errors[, message]) parameters
errors an iterable of
errors, may not actually be
error instances. messageoptional an optional human-readable description of the aggregate
error. ...
...And 3 more matches
EvalError - JavaScript
the eval
error object indicates an
error regarding the global eval() function. this exception is not thrown by javascript anymore, however the eval
error object remains for compatibility. constructor eval
error() creates a new eval
error object. instance properties eval
error.prototype.message
error message. although ecma-262 specifies that eval
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. eval
error.prototype.name
error name. inherited from
error. eval
error.prototype.filename path to file that raised this
error. inherited from
error. eval
error.prototype.linenumber line number in file that raised this
error. inherited from
error. eval
error.prototype.columnnumber column number in line that raised this
error. inherited from erro...
...key, it inherits
error.prototype.message. eval
error.prototype.name
error name. inherited from
error. eval
error.prototype.filename path to file that raised this
error. inherited from
error. eval
error.prototype.linenumber line number in file that raised this
error. inherited from
error. eval
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. eval
error.prototype.stack stack trace. inherited from
error. examples eval
error is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
...or.prototype.columnnumber column number in line that raised this
error. inherited from
error. eval
error.prototype.stack stack trace. inherited from
error. examples eval
error is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
...And 3 more matches
RangeError() constructor - JavaScript
the range
error() constructor creates an
error when a value is not in the set or range of allowed values. syntax new range
error([message[, filename[, linenumber]]]) parameters message optional human-readable description of the
error. ...
... creates an
error when a value is not in the set or range of allowed values. syntax new range
error([message[, filename[, linenumber]]]) parameters message optional human-readable description of the
error. ...
...filename[, linenumber]]]) parameters message optional human-readable description of the
error. ...
...And 3 more matches
ReferenceError() constructor - JavaScript
the reference
error object represents an
error when a non-existent variable is referenced. syntax new reference
error([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. ...
...-existent variable is referenced. syntax new reference
error([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. ...
...ber]]]) parameters message optional optional. human-readable description of the
error. filename optional optional. the name of the file containing the code that caused the exception. linenumber optional optional. the line number of the code that caused the exception. ...
...And 3 more matches
TypeError() constructor - JavaScript
the type
error() 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 type
error([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. ...
...ely) when a value is not of the expected type. syntax new type
error([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. ...
...([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. ...
...And 3 more matches
URIError() constructor - JavaScript
the uri
error() constructor creates an
error when a global uri handling function was used in a wrong way. syntax new uri
error([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. ...
...handling function was used in a wrong way. syntax new uri
error([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. ...
...e[, 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. ...
...And 3 more matches
Error Console - Archive of obsolete content
the
error console is deprecated in firefox, and is now only made available if you set the devtools.
errorconsole.enabled preference to true. use the web console instead, for web content, or the browser console for chrome content. the
error console is a tool available in most mozilla-based applications that is used for reporting
errors in the application chrome and in web pages user opens. it reports javascript-related
errors and warnings, css
errors and arbitrary messages from chrome code. in firefox, the
error console can be opened from the tools menu or by ctrl-shift-j. 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 e...
... warning usually lets the program compile but warns of bad coding and suggests design flaws. ...
...an 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). types of
errors
error usually a syntax
error that prevents the program from compiling. warning usually lets the program compile but warns of bad coding and suggests design flaws. message very similar to warning, used very rarely. manipulating da...
...And 2 more matches
JS_ReportError
create a formatted
error or warning message to pass to a user-defined
error reporting function. this function can also raise a javascript exception which a currently executing script can catch. syntax void js_report
error(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. ... ...
error message variables to insert into the format string. ...
... 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. ... ...
error message variables to insert into the format string. description js_report
error is the simplest jsapi function for reporting
errors. ...
...ime 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. ... ...
error message variables to insert into the format string. description js_report
error 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 js
errorreporter callback, if any. if the caller is in a jsapi callback, js_report
error 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 pr...
...And 2 more matches
mozIStorageError
the mozistorage
error interface represents
errors returned by the storage api, offering attributes to obtain the
error code as well as a human-readable
error message corresponding to the
error that occurred. storage/public/mozistorage
error.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports attributes attribute type description message autf8string a human readable
error string with details; this may be null if no details are available. read only. result long one of the
error code values listed under constants on this page. constants constant value desc...
... corrupt 11 the database on disk is malformed. full 13 an insertion failed because the database is full. ...
... corrupt 11 the database on disk is malformed. full 13 an insertion failed because the database is full. ...
...And 2 more matches
nsIScriptError2
js/src/xpconnect/idl/nsiscript
error.idlscriptable represents javascript
errors and warnings for use by the console service; augments nsiscript
error by adding a way to initialize the
error with the window id of the outer window with which the
error is associated. 1.0 66 introduced gecko 2.0 obsolete gecko 12.0 inherits from: nsiscript
error last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) in gecko 12.0 this interface was merged into the nsiscript
error interface. method overview void initwithwindowid(in wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category, in unsigned long long innerwindowid); attribu...
...interface. method overview void initwithwindowid(in wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category, in unsigned long long innerwindowid); attributes attribute type description innerwindowid unsigned long long the inner window id with which the
error is associated. this is zero if the
error was initialized by calling nsiscript
error.init() instead of initwithwindowid(). read only. outerwindowid unsigned long long the window id with which the
error is associated. this is zero if the
error was initialized by calling nsiscript
error.init() instead of initwithwindowid(). read only. timestamp long long elapsed time, in...
...age was created. read only. methods initwithwindowid() void init( in wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category, in unsigned long long innerwindowid ); parameters message the text of the message to add to the log. sourcename the url of the file in which the
error occurred. this will be a hyperlink in the javascript console, so you should use a real url. you may pass null if it's not applicable. sourceline the line number in the source file on which the
error occurred. you are responsible for providing that line. you may pass null if you are lazy; that will prevent showing the source line in javascript console. linenumber the number of the line where t...
...And 2 more matches
NS_ERROR
summary macro throws a assertion (ns_assertion) with the text "
error: (
error text)", so writes this text to console (stderr) and to debug logs (nspr logging). ...
... summary macro throws a assertion (ns_assertion) with the text "
error: (
error text)", so writes this text to console (stderr) and to debug logs (nspr logging). ...
... summary macro throws a assertion (ns_assertion) with the text "
error: (
error text)", so writes this text to console (stderr) and to debug logs (nspr logging). ...
...And 2 more matches
AddressErrors.languageCode - Web APIs
this validation might be as simple as ensuring the text of the string is compliant with the syntax defined in bcp-47, or as detailed as actually verifying that the specified string matches a value from a database. ...
... this validation might be as simple as ensuring the text of the string is compliant with the syntax defined in bcp-47, or as detailed as actually verifying that the specified string matches a value from a database. ...
... this validation might be as simple as ensuring the text of the string is compliant with the syntax defined in bcp-47, or as detailed as actually verifying that the specified string matches a value from a database. ...
...And 2 more matches
HTMLMediaElement: error event - Web APIs
the
error event is fired when the resource could not be loaded due to an
error (for example, a network connectivity problem). ...
... the
error event is fired when the resource could not be loaded due to an
error (for example, a network connectivity problem). ...
... the
error event is fired when the resource could not be loaded due to an
error (for example, a network connectivity problem). ...
...And 2 more matches
IDBDatabase: error event - Web APIs
the
error event is fired on idbdatabase when a request returns an
error and the event bubbles up to the connection object. ...
... the
error event is fired on idbdatabase when a request returns an
error and the event bubbles up to the connection object. ...
... the
error event is fired on idbdatabase when a request returns an
error and the event bubbles up to the connection object. ...
...And 2 more matches
IDBTransaction: error event - Web APIs
the
error event is fired on idbtransaction when a request returns an
error and the event bubbles up to the transaction object. ...
... the
error event is fired on idbtransaction when a request returns an
error and the event bubbles up to the transaction object. ...
... the
error event is fired on idbtransaction when a request returns an
error and the event bubbles up to the transaction object. ...
...And 2 more matches
MessagePort: messageerror event - Web APIs
the message
error event is fired on a messageport object when it receives a message that can't be deserialized. ...
... the message
error event is fired on a messageport object when it receives a message that can't be deserialized. ...
...ps://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessage('init', targetorigin, [channel.port2]); the target can receive the port and start listening for messages and message
errors on it using code like this: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.addeventlistener('message
error', (event) => { console.
error(event.data); }); myport.start(); }); note that the listener must call messageport.start() be...
...And 2 more matches
PayerErrors.email - Web APIs
the email property is included in a payer
errors object if the paymentresponse.payeremail property failed validation; in this case, the property should contain a string describing how to correct the problem. if the payer's email address passed validation, this property is not included in the payer
errors object. syntax payeremail = payer
errors.email; value if validation of the payer's email address (paymentresponse.payeremail) found problems, this property should be set to a domstring that explains the validation problem and how to correct it. if the email address is valid, this property should be omitted from the payer
errors object. ...
...= payer
errors.email; value if validation of the payer's email address (paymentresponse.payeremail) found problems, this property should be set to a domstring that explains the validation problem and how to correct it. if the email address is valid, this property should be omitted from the payer
errors object. ...
...alue if validation of the payer's email address (paymentresponse.payeremail) found problems, this property should be set to a domstring that explains the validation problem and how to correct it. if the email address is valid, this property should be omitted from the payer
errors object. ...
...And 2 more matches
PayerErrors.name - Web APIs
the name property is included in a payer
errors object if the payername returned in the response couldn't be validated. the value is a string explaining the problem. if the payer's name validated successfully, the name property is omitted from the payer
errors object. syntax payername = payer
errors.name; value if this property is present in the payer
errors object, the payer's name couldn't be successfully validated, and the name property's value is a domstring explaining the
error. this string will be displayed to the user by the user agent's payment handling user interface. if the payer's name is valid, this property is left out of the payer
errors object. ...
...rrors object, the payer's name couldn't be successfully validated, and the name property's value is a domstring explaining the
error. this string will be displayed to the user by the user agent's payment handling user interface. if the payer's name is valid, this property is left out of the payer
errors object. ...
...s name couldn't be successfully validated, and the name property's value is a domstring explaining the
error. this string will be displayed to the user by the user agent's payment handling user interface. if the payer's name is valid, this property is left out of the payer
errors object. ...
...And 2 more matches
PayerErrors.phone - Web APIs
the phone property is found in a payer
errors object if the payername returned in the response couldn't be validated as a valid phone number. the value of this property is a string explaining the problem. if the payer's phone number validated successfully, the phone property is omitted from the payer
errors object. syntax payerphone = payer
errors.phone; value if this property is present in the payer
errors object, the payer's phone number couldn't be successfully validated, and the phone property's value is a domstring explaining the
error. this string will be displayed to the user by the user agent's payment handling user interface as appropriate. if the phone number is valid, this property is omitted from the payer
errors object. example function validatepayment(response) { c...
... phone number couldn't be successfully validated, and the phone property's value is a domstring explaining the
error. this string will be displayed to the user by the user agent's payment handling user interface as appropriate. if the phone number is valid, this property is omitted from the payer
errors object. ...
...e successfully validated, and the phone property's value is a domstring explaining the
error. this string will be displayed to the user by the user agent's payment handling user interface as appropriate. if the phone number is valid, this property is omitted from the payer
errors object. ...
...And 2 more matches
RTCIdentityErrorEvent - Web APIs
the rtcidentity
errorevent interface represents an
error associated with the identity provider (idp). this is usually for an rtcpeerconnection. two events are sent with this type: idpassertion
error and idpvalidation
error. firefox implements this interface under the following name: rtcpeerconnectionidentity
errorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. properties a rtcidentity
errorevent being an event, this event also implements these properties. rtcidentity
errorevent.idp read only is a domstring describing the domain name of the identity provider (idp) generating the
error response. ...
...t. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. properties a rtcidentity
errorevent being an event, this event also implements these properties. rtcidentity
errorevent.idp read only is a domstring describing the domain name of the identity provider (idp) generating the
error response. rtcidentity
errorevent.loginurl read only is a domstring giving the url where the user can complete the authentication. it can be null and is provided by the identity provider (idp). ...
...ng an event, this event also implements these properties. rtcidentity
errorevent.idp read only is a domstring describing the domain name of the identity provider (idp) generating the
error response. rtcidentity
errorevent.loginurl read only is a domstring giving the url where the user can complete the authentication. it can be null and is provided by the identity provider (idp). rtcidentity
errorevent.protocol read only is a domstring describing the idp protocol in use. methods a rtcidentity
errorevent being an event, this event also implements these properties. there is no specific rtcidentity
errorevent method. ...
...And 2 more matches
RTCPeerConnectionIceErrorEvent - Web APIs
the rtcpeerconnectionice
errorevent interface—based upon the event interface—provides details pertaining to an ice
error announced by sending an icecandidate
error event to the rtcpeerconnection object. constructor rtcpeerconnectionice
errorevent() creates and returns a new rtcpeerconnectionice
errorevent object, with its type and other properties initialized as specified in the parameters. you will not normally create an object of this type yourself. ...
...rtaining to an ice
error announced by sending an icecandidate
error event to the rtcpeerconnection object. constructor rtcpeerconnectionice
errorevent() creates and returns a new rtcpeerconnectionice
errorevent object, with its type and other properties initialized as specified in the parameters. you will not normally create an object of this type yourself. properties the rtcpeerconnectionice
errorevent interface includes the properties found on the event interface, as well as the following properties: address read only a domstring providing the local ip address used to communicate with the stun or turn server being used to negotiate the connection, or null if the local ip address has not yet been exposed as part of a local ice candidate. ...
...f. properties the rtcpeerconnectionice
errorevent interface includes the properties found on the event interface, as well as the following properties: address read only a domstring providing the local ip address used to communicate with the stun or turn server being used to negotiate the connection, or null if the local ip address has not yet been exposed as part of a local ice candidate.
errorcode read only an unsigned integer value stating the numeric stun
error code returned by the stun or turn server. if no host candidate can reach the server, this property is set to the number 701, which is outside the range of valid stun
error codes. the 701
error is fired only once per server url, and only while the is icegatheringstate is gathering. ...
...And 2 more matches
Sensor.onerror - Web APIs
candidate recommendation initial definition. ...
... candidate recommendation initial definition. ...
... candidate recommendation initial definition. ...
...And 2 more matches
ServiceWorkerContainer.onerror - Web APIs
the on
error property of the serviceworkercontainer interface is an event handler fired whenever an
error event occurs in the associated service workers. syntax serviceworkercontainer.on
error = function(
errorevent) { ... ...
... the on
error property of the serviceworkercontainer interface is an event handler fired whenever an
error event occurs in the associated service workers. syntax serviceworkercontainer.on
error = function(
errorevent) { ... ...
... the on
error property of the serviceworkercontainer interface is an event handler fired whenever an
error event occurs in the associated service workers. syntax serviceworkercontainer.on
error = function(
errorevent) { ... ...
...And 2 more matches
Worker: messageerror event - Web APIs
the message
error event is fired on a worker object when it receives a message that can't be deserialized. ...
... the message
error event is fired on a worker object when it receives a message that can't be deserialized. ...
... the message
error event is fired on a worker object when it receives a message that can't be deserialized. ...
...And 2 more matches
TypeError: invalid Array.prototype.sort argument - JavaScript
the argument of array.prototype.sort() is expected to be either undefined or a function which compares its operands. ...
... the argument of array.prototype.sort() is expected to be either undefined or a function which compares its operands. ...
... the argument of array.prototype.sort() is expected to be either undefined or a function which compares its operands. ...
...And 2 more matches
SyntaxError: missing ] after element list - JavaScript
likely there is a closing bracket ("]") or a comma (",") missing. ...
...likely there is a closing bracket ("]") or a comma (",") missing. ...
...likely there is a closing bracket ("]") or a comma (",") missing. ...
...And 2 more matches
SyntaxError: missing } after function body - JavaScript
also check if any closing curly brackets or parenthesis are in the correct order. ...
...also check if any closing curly brackets or parenthesis are in the correct order. ...
...also check if any closing curly brackets or parenthesis are in the correct order. ...
...And 2 more matches
SyntaxError: function statement requires a name - JavaScript
the javascript exception "function statement requires a name" occurs when there is a function statement in the code that requires a name. message syntax
error: expected identifier (edge) syntax
error: function statement requires a name [firefox] syntax
error: unexpected token ( [chrome]
error type syntax
error 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. examples statements vs expressions a function statement (or function declaration) requires a name, this won't work: function () { return 'hello world'; } // syntax
error:...
...ife (immediately invoked function expression), which is a function that runs as soon as it is defined. you will need a few more braces in this case: (function () { })(); labeled functions if you are using function labels, you will still need to provide a function name after the function keyword. this doesn't work: function greeter() { german: function () { return "moin"; } } // syntax
error: function statement requires a name this would work, for example: function greeter() { german: function g() { return "moin"; } } object methods if you intended to create a method of an object, you will need to create an object. the following syntax without a name after the function keyword is valid then. var greeter = { german: function () { return "moin"; } }; callback syn...
...of an object, you will need to create an object. the following syntax without a name after the function keyword is valid then. ...
...And 2 more matches
EvalError() constructor - JavaScript
the eval
error constructor creates a new
error regarding the global eval() function. this exception is not thrown by javascript anymore, however the eval
error object remains for compatibility. syntax new eval
error([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 eval
error is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
... 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 eval
error is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
...file containing the code that caused the exception linenumber optional. the line number of the code that caused the exception examples eval
error is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
...And 2 more matches
URIError - JavaScript
the uri
error object represents an
error when a global uri handling function was used in a wrong way. constructor uri
error() creates a new uri
error object. instance properties uri
error.prototype.message
error message. although ecma-262 specifies that uri
error should provide its own message property, in spidermonkey, it inherits
error.prototype.message. uri
error.prototype.name
error name. inherited from
error. uri
error.prototype.filename path to file that raised this
error. inherited from
error. uri
error.prototype.linenumber line number in file that raised this
error. inherited from
error. uri
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. uri
error.prototype.stack stack trace. inherited from
error. examples catching an urie...
...rror. inherited from
error. uri
error.prototype.linenumber line number in file that raised this
error. inherited from
error. uri
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. uri
error.prototype.stack stack trace. inherited from
error. ...
...uri
error.prototype.columnnumber column number in line that raised this
error. inherited from
error. uri
error.prototype.stack stack trace. inherited from
error. ...
...And 2 more matches
Error.description - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the
error.description property returns or sets the descriptive string associated with a specific
error. syntax object .description [= stringexpression] parameters object required. any instance of an
error object. stringexpression optional. a string expression containing a description of the
error. remarks the description property contains the
error message string associated with a specific
error. use the value contained in this property to alert a user to an
error. the description and message properties provide the same functionality; the descriptionproperty provides backward compatibility; the message property complies with the ecma standard. example the following example...
...ssage string associated with a specific
error. use the value contained in this property to alert a user to an
error. the description and message properties provide the same functionality; the descriptionproperty provides backward compatibility; the message property complies with the ecma standard. example the following example illustrates the use of the description property. ...
...e the value contained in this property to alert a user to an
error. the description and message properties provide the same functionality; the descriptionproperty provides backward compatibility; the message property complies with the ecma standard. example the following example illustrates the use of the description property. ...
..." "); // prints "'y' is undefined": document.write(e.message) } requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). applies to:
error object see also number property (
error) message property (
error) name property (
error) ...
Error.stackTraceLimit - Archive of obsolete content
the
error.stacktracelimit property gets or sets the stack trace limit, which is equivalent to the number of
error frames to display. the default limit is 10. syntax
error.stacktracelimit remarks you can set the stacktracelimit property to any positive value between 0 and infinity. if the stacktracelimit property is set to 0 at the time an
error is thrown, no stack trace is shown. if the property is set to a negative value or a non-numeric value, the value is converted to 0. if the stacktracelimit is set to infinity, the entire stack is shown. otherwise, touint32 is used to convert the value. example the following example shows how to set and then get the stack trace limit. ...
...operty is set to 0 at the time an
error is thrown, no stack trace is shown. if the property is set to a negative value or a non-numeric value, the value is converted to 0. if the stacktracelimit is set to infinity, the entire stack is shown. otherwise, touint32 is used to convert the value. example the following example shows how to set and then get the stack trace limit. ...
...set to 0 at the time an
error is thrown, no stack trace is shown. if the property is set to a negative value or a non-numeric value, the value is converted to 0. if the stacktracelimit is set to infinity, the entire stack is shown. otherwise, touint32 is used to convert the value. example the following example shows how to set and then get the stack trace limit. try { var err = new
error("my
error");
error.stacktracelimit = 7; throw err; } catch(e) { document.write("
error stack trace limit: ") document.write(
error.stacktracelimit); } requirements supported in internet explorer 10 and in windows 8.x store apps. ...
...nt32 is used to convert the value. example the following example shows how to set and then get the stack trace limit. ...
PR_GetErrorText
returns the actual number of bytes copied. ...
... returns the actual number of bytes copied. ...
... returns the actual number of bytes copied. ...
... returns the actual number of bytes copied. ...
BroadcastChannel: messageerror event - Web APIs
the message
error event is fired on a broadcastchannel object when a message arrives on the channel that can't be deserialized. ...
... the message
error event is fired on a broadcastchannel object when a message arrives on the channel that can't be deserialized. ...
... the message
error event is fired on a broadcastchannel object when a message arrives on the channel that can't be deserialized. ...
... bubbles no cancelable no interface messageevent event handler property onmessage
error examples this code uses addeventlistener to listen for messages and
errors: const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); channel.addeventlistener('message
error', (event) => { console.
error(event); }); the same, but using the onmessage and onmessage
error event handler properties: const channel = new broadcastchannel('example-channel'); channel.onmessage = (event) => { received.textcontent = event.data; }; channel.onmessage
error = (event) => { console.log(event); }; specifications specification status html living standard...
DOMError - Web APIs
the dom
error interface describes an
error object that contains an
error name. properties dom
error.name read only returns a domstring representing one of the
error type names (see below). dom
error.message read only returns a domstring representing a message or description associated with the given
error type name.
error types type description indexsize
error the index is not in the allowed range (e.g. thrown in a range object). hierarchyrequest
error the node tree hierarchy is not correct. wrongdocument
error the object is in the wrong document. invalidcharacter
error the string contains invalid characters. nomodificationallowed
error the object can not be modified. ...
... indexsize
error the index is not in the allowed range (e.g. thrown in a range object). hierarchyrequest
error the node tree hierarchy is not correct. wrongdocument
error the object is in the wrong document. invalidcharacter
error the string contains invalid characters. nomodificationallowed
error the object can not be modified. notfound
error the object can not be found here. notsupported
error the operation is not supported invalidstate
error the object is in an invalid state. syntax
error the string did not match the expected pattern. invalidmodification
error the object can not be modified in this way. ...
...wed
error the object can not be modified. notfound
error the object can not be found here. notsupported
error the operation is not supported invalidstate
error the object is in an invalid state. syntax
error the string did not match the expected pattern. invalidmodification
error the object can not be modified in this way. namespace
error the operation is not allowed by namespaces in xml invalidaccess
error the object does not support the operation or argument. typemismatch
error the type of the object does not match the expected type. security
error the operation is insecure. network
error a network
error occurred. abort
error the operation was aborted. urlmismatc...
... the operation is not allowed by namespaces in xml invalidaccess
error the object does not support the operation or argument. typemismatch
error the type of the object does not match the expected type. security
error the operation is insecure. network
error a network
error occurred. abort
error the operation was aborted. urlmismatch
error the given url does not match another url. quotaexceeded
error the quota has been exceeded. timeout
error the operation timed out. invalidnodetype
error the node is incorrect or has an incorrect ancestor for this operation. dataclone
error the object can not be cloned. ...
Document: fullscreenerror event - Web APIs
the fullscreen
error event is fired when the browser cannot switch to full-screen mode. bubbles yes cancelable no interface event event handler property onfullscreen
error as with the fullscreenchange event, two fullscreen
error events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which owns that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. ...
...with the fullscreenchange event, two fullscreen
error events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which owns that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. ...
..., two fullscreen
error events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which owns that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. ...
...screen
error events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which owns that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. ...
Element: error event - Web APIs
the
error event is fired on an element object when a resource failed to load, or can't be used. for example, if a script has an execution
error or an image can't be found or is invalid. bubbles no cancelable no interface event or uievent event handler property on
error the event object is a uievent instance if it was generated from a user interface element, or an event instance otherwise. ...
...t has an execution
error or an image can't be found or is invalid. bubbles no cancelable no interface event or uievent event handler property on
error the event object is a uievent instance if it was generated from a user interface element, or an event instance otherwise. ...
... can't be found or is invalid. bubbles no cancelable no interface event or uievent event handler property on
error the event object is a uievent instance if it was generated from a user interface element, or an event instance otherwise. ...
...isplay: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } js const log = document.queryselector('.event-log-contents'); const badimg = document.queryselector('.bad-img'); badimg.addeventlistener('
error', (event) => { log.textcontent = log.textcontent + `${event.type}: loading image\n`; console.log(event) }); const img
error = document.queryselector('#img-
error'); img
error.addeventlistener('click', () => { badimg.setattribute('src', 'i-dont-exist'); }); result specifications specification status ui events working draft ...
Element: fullscreenerror event - Web APIs
the fullscreen
error event is fired when the browser cannot switch to full-screen mode. bubbles yes cancelable no interface event event handler property onfullscreen
error as with the fullscreenchange event, two fullscreen
error events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which contains that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. ...
...the fullscreenchange event, two fullscreen
error events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which contains that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. ...
... fullscreen
error events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which contains that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. ...
...n
error events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which contains that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. ...
FileReader: error event - Web APIs
the
error event is fired when the read failed due to an
error (for example, because the file was not found or not readable). ...
... the
error event is fired when the read failed due to an
error (for example, because the file was not found or not readable). ...
...t readable). ...
... cancelable no interface progressevent event handler property filereader.on
error examples const fileinput = document.queryselector('input[type="file"]'); const reader = new filereader(); function handleselected(e) { const selectedfile = fileinput.files[0]; if (selectedfile) { reader.addeventlistener('
error', () => { console.
error(`
error occurred reading file: ${selectedfile.name}`); }); reader.addeventlistener('load', () => { console.
error(`file: ${selectedfile.name} read successfully`); }); reader.readasdataurl(selectedfile); } } fileinput.addeventlistener('change', handleselected); specifications specification status file api working draft...
IDBRequest.onerror - Web APIs
the on
error event handler of the idbrequest interface handles the
error event, fired when a request returns an
error. the event handler takes one parameter, an
error event with type="
error". note: this feature is available in web workers. syntax request.on
error = function(event) { ... }; 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. also included at the bottom is an on
error function that reports what the
error was if the request fails. for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction...
...e the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; objectstoretitlerequest.on
error = function() { // if an
error occurs with the request, log what it is console.log("there has been an
error with retrieving your data: " + objectstoretitlerequest.
error); // todo what about event parameter into on
error()? what will be inside of this event? }; specifications specification status comment indexed database api 2.0the definition of 'on
error' in that spec...
... 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. ...
...ion 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. ...
MediaError.code - Web APIs
the read-only property media
error.code returns a numeric value which represents the kind of
error that occurred on a media element. to get a text string with specific diagnostic information, see media
error.message. syntax var my
error = media
error.code; value a numeric value indicating the general type of
error which occurred. the possible values are described below, in media
error code constants. media
error code constants name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network
error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite havin...
...value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network
error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an
error occurred while trying to decode the media resource, resulting in an
error. ...
...le. media_err_decode 3 despite having previously been determined to be usable, an
error occurred while trying to decode the media resource, resulting in an
error. media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. example this example creates a <video> element, establishes an
error handler for it, and then sets the element's src attribute to the video resource to present in the element. ...
... trying to decode the media resource, resulting in an
error. media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. example this example creates a <video> element, establishes an
error handler for it, and then sets the element's src attribute to the video resource to present in the element. the
error handler simply outputs a message var obj = document.createelement('video'); obj.on
error = function() {console.log("
error with media: " + obj.
error.code);} obj.src="https://example.com/blahblah.mp4"; specifications specification status comment html living standardthe definition of 'media
error.code' in that specification. living standard initial definition ...
MediaError - Web APIs
the media
error interface represents an
error which occurred while handling media in an html media element based on htmlmediaelement, such as <audio> or <video>. a media
error object describes the
error in general terms using a numeric code categorizing the kind of
error, and a message, which provides specific diagnostics about what went wrong. properties this interface doesn't inherit any properties. media
error.code a number which represents the general type of
error that occurred, as follows: name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. ...
...agnostics about what went wrong. properties this interface doesn't inherit any properties. media
error.code a number which represents the general type of
error that occurred, as follows: name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network
error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an
error occurred while trying to decode the media resource, resulting in an
error. media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastrea...
...uccessfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an
error occurred while trying to decode the media resource, resulting in an
error. media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. media
error.message a domstring object containing a human-readable string which provides specific diagnostic information to help the reader understand the
error condition which occurred; specifically, it isn't simply a summary of what the
error code means, but actual diagnostic information to help in understanding what exactly went wrong. this text and its format is not defined by the specification and will...
... living standard ...
PaymentDetailsUpdate.error - Web APIs
this happens if both of the following are true: the paymentrequest specifies using its requestshipping property that shipping information is required. the paymentdetailsupdate object specifies no valid shipping options in its shippingoptions list. ...
...this happens if both of the following are true: the paymentrequest specifies using its requestshipping property that shipping information is required. the paymentdetailsupdate object specifies no valid shipping options in its shippingoptions list. ...
...this happens if both of the following are true: the paymentrequest specifies using its requestshipping property that shipping information is required. the paymentdetailsupdate object specifies no valid shipping options in its shippingoptions list. ...
... candidate recommendation initial definition. ...
PaymentValidationErrors - Web APIs
the paymentvalidation
errors dictionary represents objects providing information about any and all
errors that occurred while processing a payment request. when validation of the paymentresponse returned by the paymentrequest.show() or paymentresponse.retry() methods fails, your code creates a paymentvalidation
errors object to pass into retry() so that the user agent knows what needs to be fixed and what if any
error messages to display to the user. properties
error optional a general description of a payment
error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. ...
...() methods fails, your code creates a paymentvalidation
errors object to pass into retry() so that the user agent knows what needs to be fixed and what if any
error messages to display to the user. properties
error optional a general description of a payment
error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information.
error can be provided all by itself to provide only a generic
error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to
errors in specific fields in the payment form. payer optional a payer
errors compliant object which provides appropriate
error messages for any of the fields describing the payer which failed validation. paymentmet...
...only a generic
error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to
errors in specific fields in the payment form. payer optional a payer
errors compliant object which provides appropriate
error messages for any of the fields describing the payer which failed validation. paymentmethod optional any payment method specific
errors which may have occurred. this object's contents will vary depending on the payment used. for example, if the user chose to pay by credit card using the basic-card payment method, this is a basiccard
errors object. shippingaddress optional an address
errors object which contains
error messages for any of the fields in the shipping address that failed validation. example specifications ...
...s a basiccard
errors object. shippingaddress optional an address
errors object which contains
error messages for any of the fields in the shipping address that failed validation. example specifications specification status comment payment request api candidate recommendation initial definition. ...
RTCDataChannel.onerror - Web APIs
the rtcdatachannel.on
error property is an eventhandler which specifies a function to be called when the
error event is received. when an
error occurs on the data channel, the function receives as input an
errorevent object describing the
error which occurred. syntax rtcdatachannel.on
error = function; value a function which the browser will call to handle the
error event when it occurs on the data channel. this function receives as its only input an
errorevent object describing the event which was received. that event object, in turn, describes the
error that took place. example in the example below, a data channel is established, and an on
error handler is added to it. ...
...rror = function; value a function which the browser will call to handle the
error event when it occurs on the data channel. this function receives as its only input an
errorevent object describing the event which was received. that event object, in turn, describes the
error that took place. example in the example below, a data channel is established, and an on
error handler is added to it. the
error handler passes information about the
error to a ui library's alert box function to present an
error message to the user. ...
...as received. that event object, in turn, describes the
error that took place. example in the example below, a data channel is established, and an on
error handler is added to it. the
error handler passes information about the
error to a ui library's alert box function to present an
error message to the user. let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("playercontrol"); dc.on
error = function(event) { myuilibrary.doalertbox({ 'network
error', // alert title 'the
error "' + event.message + '" occurred while handling player control network messages.', event.filename, event.lineno, event.colno }); } /* ... */ specifications specification status comment webrtc 1.0: real-time communication between browsers...
...oalertbox({ 'network
error', // alert title 'the
error "' + event.message + '" occurred while handling player control network messages.', event.filename, event.lineno, event.colno }); } /* ... */ specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.on
error' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.onidpassertionerror - Web APIs
the rtcpeerconnection.onidpassertion
error event handler is a property containing the code to execute whent the idpassertion
error event, of type rtcidentity
errorevent, is received by this rtcpeerconnection. such an event is sent when the associated identity provider (idp) encounters an
error while generating an identity assertion. this event handler is deprecated. you should instead detect idp assertion
errors by handling rejection of the promise returned by rtcpeerconnection.peeridentity. syntax peerconnection.onidpassertion
error = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of ...
...andling rejection of the promise returned by rtcpeerconnection.peeridentity. syntax peerconnection.onidpassertion
error = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. ...
...d by rtcpeerconnection.peeridentity. syntax peerconnection.onidpassertion
error = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type rtcidentity
errorevent. ...
... peerconnection.onidpassertion
error = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type rtcidentity
errorevent. ...
RTCPeerConnection.onidpvalidationerror - Web APIs
the rtcpeerconnection.onidpvalidation
error event handler is a property containing the code to execute whent the idpvalidation
error event, of type rtcidentity
errorevent, is received by this rtcpeerconnection. such an event is sent when the associated identity provider (idp) encounters an
error while validating an identity assertion. this event handler is obsolete. you should instead detect idp validation
errors by watching for the promise returned by rtcpeerconnection.peeridentity to be rejected. syntax peerconnection.onidpvalidation
error = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, ...
... for the promise returned by rtcpeerconnection.peeridentity to be rejected. syntax peerconnection.onidpvalidation
error = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. ...
...ction.peeridentity to be rejected. syntax peerconnection.onidpvalidation
error = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type rtcidentity
errorevent. ...
...eerconnection.onidpvalidation
error = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type rtcidentity
errorevent. ...
SpeechRecognitionError.message - Web APIs
the message read-only property of the speechrecognition
error interface returns a message describing the
error in more detail. this speechrecognition
error interface was renamed to speechrecognition
errorevent in the web speech api specification. syntax var my
errormsg = event.message; value a domstring containing more details about the
error that was raised. note that the spec does not define the exact wording of these messages — this is up to the implementors to decide upon. ...
...nterface was renamed to speechrecognition
errorevent in the web speech api specification. syntax var my
errormsg = event.message; value a domstring containing more details about the
error that was raised. note that the spec does not define the exact wording of these messages — this is up to the implementors to decide upon. ...
...eb speech api specification. syntax var my
errormsg = event.message; value a domstring containing more details about the
error that was raised. note that the spec does not define the exact wording of these messages — this is up to the implementors to decide upon. ...
...n. syntax var my
errormsg = event.message; value a domstring containing more details about the
error that was raised. note that the spec does not define the exact wording of these messages — this is up to the implementors to decide upon. ...
SpeechRecognitionError - Web APIs
the speechrecognition
error interface of the web speech api represents
error messages from the recognition service. this speechrecognition
error interface was renamed to speechrecognition
errorevent in the web speech api specification. properties speechrecognition
error also inherits properties from its parent interface, event. speechrecognition
error.
error read only returns the type of
error raised. speechrecognition
error.message read only returns a message describing the
error in more detail. ...
...cognition
errorevent in the web speech api specification. properties speechrecognition
error also inherits properties from its parent interface, event. speechrecognition
error.
error read only returns the type of
error raised. speechrecognition
error.message read only returns a message describing the
error in more detail. ...
...roperties speechrecognition
error also inherits properties from its parent interface, event. speechrecognition
error.
error read only returns the type of
error raised. speechrecognition
error.message read only returns a message describing the
error in more detail. ...
...on
error also inherits properties from its parent interface, event. speechrecognition
error.
error read only returns the type of
error raised. speechrecognition
error.message read only returns a message describing the
error in more detail. ...
Window: error event - Web APIs
the
error event is fired on a window object when a resource failed to load or couldn't be used — for example if a script has an execution
error. bubbles no cancelable no interface event or uievent event handler property on
error the event object is a uievent instance if it was generated from a user interface element, or an event instance otherwise. ...
...n't be used — for example if a script has an execution
error. bubbles no cancelable no interface event or uievent event handler property on
error the event object is a uievent instance if it was generated from a user interface element, or an event instance otherwise. ...
...pt has an execution
error. bubbles no cancelable no interface event or uievent event handler property on
error the event object is a uievent instance if it was generated from a user interface element, or an event instance otherwise. ...
...rol log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } js const log = document.queryselector('.event-log-contents'); window.addeventlistener('
error', (event) => { log.textcontent = log.textcontent + `${event.type}: ${event.message}\n`; console.log(event) }); const script
error = document.queryselector('#script-
error'); script
error.addeventlistener('click', () => { const badcode = 'const s;'; eval(badcode); }); result specifications specification status ui events working draft ...
CORS errors - HTTP
) is a standard that allows a server to relax the same-origin policy. this is used to explicitly allow some cross-origin requests while rejecting others. for example, if a site offers an embeddable service, it may be necessary to relax certain restrictions. setting up such a cors configuration isn't necessarily easy and may present some challenges. in these pages, we'll look into some common cors
error messages and how to resolve them. if the cors configuration isn't setup correctly, the browser console will present an
error like "cross-origin request blocked: the same origin policy disallows reading the remote resource at $somesite" indicating that the request was blocked due to violating the cors security rules. this might not necessarily be a set-up mistake, though. it's possible that the r...
...e, some debugging is needed to succeed. identifying the issue to understand the underlying issue with the cors configuration, you need to find out which request is at fault and why. these steps may help you do so: navigate to the web site or web app in question and open the developer tools. now try to reproduce the failing transaction and check the console if you are seeing a cors violation
error message. it will probably look like this: the text of the
error message will be something similar to the following: cross-origin request blocked: the same origin policy disallows reading the remote resource at https://some-url-here. (reason: additional information here). note: for security reasons, specifics about what went wrong with a cors request are not available to javascript code. al...
...ook like this: the text of the
error message will be something similar to the following: cross-origin request blocked: the same origin policy disallows reading the remote resource at https://some-url-here. (reason: additional information here). note: for security reasons, specifics about what went wrong with a cors request are not available to javascript code. all the code knows is that an
error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. cors
error messages firefox's console displays messages in its console when requests fail due to cors. part of the
error text is a "reason" message that provides added insight into what went wrong. the reason messages are listed below; click the message to open an article explaini...
...ed. the only way to determine what specifically went wrong is to look at the browser's console for details. cors
error messages firefox's console displays messages in its console when requests fail due to cors. part of the
error text is a "reason" message that provides added insight into what went wrong. the reason messages are listed below; click the message to open an article explaining the
error in more detail and offering possible solutions. reason: cors disabled reason: cors request did not succeed reason: cors header ‘origin’ cannot be added reason: cors request external redirect not allowed reason: cors request not http reason: cors header ‘access-control-allow-origin’ missing reason: cors header ‘access-control-allow-origin’ does not match ‘xyz’ reason: cre...
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
javascript execution won't be halted. what went wrong? there is a deprecated source map syntax in a javascript source. ...
...javascript execution won't be halted. what went wrong? there is a deprecated source map syntax in a javascript source. ...
...javascript execution won't be halted. what went wrong? there is a deprecated source map syntax in a javascript source. ...
...javascript execution won't be halted. what went wrong? there is a deprecated source map syntax in a javascript source. ...
RangeError: invalid array length - JavaScript
the javascript exception "invalid array length" occurs when creating an array or an arraybuffer which has a length which is either negative or larger or equal to 232, or when setting the array.length property to a value which is either negative or larger or equal to 232. ...
... the javascript exception "invalid array length" occurs when creating an array or an arraybuffer which has a length which is either negative or larger or equal to 232, or when setting the array.length property to a value which is either negative or larger or equal to 232. ...
... the javascript exception "invalid array length" occurs when creating an array or an arraybuffer which has a length which is either negative or larger or equal to 232, or when setting the array.length property to a value which is either negative or larger or equal to 232. ...
...y length" occurs when creating an array or an arraybuffer which has a length which is either negative or larger or equal to 232, or when setting the array.length property to a value which is either negative or larger or equal to 232. message range
error: array length must be a finite positive integer (edge) range
error: invalid array length (firefox) range
error: invalid array length (chrome) range
error: invalid array buffer length (chrome)
error type range
error what went wrong? an invalid array length might appear in these situations: when creating an array or an arraybuffer which has a length which is either negative or larger or equal to 232, or when setting the array.length property to a value which is either negative or larger or equal to 232. why are array and arraybuffer length...
URIError: malformed URI sequence - JavaScript
the javascript exception "malformed uri sequence" occurs when uri encoding or decoding wasn't successful. message uri
error: the uri to be encoded contains invalid character (edge) uri
error: malformed uri sequence (firefox) uri
error: uri malformed (chrome)
error type uri
error what went wrong? uri encoding or decoding wasn't successful. an argument given to either the decodeuri, encodeuri, encodeuricomponent, or decodeuricomponent function was not valid, so that the function was unable encode or decode properly. examples encoding encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the utf-8 encoding of the character. an uri
error will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, ...
...ion was not valid, so that the function was unable encode or decode properly. examples encoding encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the utf-8 encoding of the character. an uri
error will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, for example: encodeuri('\ud800'); // "uri
error: malformed uri sequence" encodeuri('\udfff'); // "uri
error: malformed uri sequence" a high-low pair is ok. ...
...not part of a high-low pair, for example: encodeuri('\ud800'); // "uri
error: malformed uri sequence" encodeuri('\udfff'); // "uri
error: malformed uri sequence" a high-low pair is ok. for example: encodeuri('\ud800\udfff'); // "%f0%90%8f%bf" decoding decoding replaces each escape sequence in the encoded uri component with the character that it represents. ...
...; // "uri
error: malformed uri sequence" encodeuri('\udfff'); // "uri
error: malformed uri sequence" a high-low pair is ok. for example: encodeuri('\ud800\udfff'); // "%f0%90%8f%bf" decoding decoding replaces each escape sequence in the encoded uri component with the character that it represents. ...
SyntaxError: missing } after property list - JavaScript
might be in fact a missing curly bracket, but could also be a missing comma, for example. ...
...might be in fact a missing curly bracket, but could also be a missing comma, for example. ...
...might be in fact a missing curly bracket, but could also be a missing comma, for example. ...
...might be in fact a missing curly bracket, but could also be a missing comma, for example. ...
SyntaxError: missing formal parameter - JavaScript
your function declaration is missing valid parameters. in the declaration of a function, the parameters must be identifiers, not any value like numbers, strings, or objects. declaring functions and calling functions are two separate steps. declarations require identifier as parameters, and only when calling (invoking) the function, you provide the values the function should use. ...
... and may not start with a digit. an identifier differs from a string in that a string is data, while an identifier is part of the code. examples provide proper function parameters function parameters must be identifiers when setting up a function. ...
...ata, while an identifier is part of the code. examples provide proper function parameters function parameters must be identifiers when setting up a function. ...
...ction parameters must be identifiers when setting up a function. ...
SyntaxError: missing ) after argument list - JavaScript
the javascript exception "missing ) after argument list" occurs when there is an
error with how a function is called. this might be a typo, a missing operator, or an unescaped string. message syntax
error: expected ')' (edge) syntax
error: missing ) after argument list (firefox)
error type syntax
error. what went wrong? ...
... the javascript exception "missing ) after argument list" occurs when there is an
error with how a function is called. this might be a typo, a missing operator, or an unescaped string. message syntax
error: expected ')' (edge) syntax
error: missing ) after argument list (firefox)
error type syntax
error. what went wrong? ...
...
error. what went wrong? ...
... argument for the log function to be just "pi: ". in that case, it should be terminated by a closing parenthesis. console.log('pi: ' math.pi); // syntax
error: missing ) after argument list you can correct the log call by adding the "+" operator: console.log('pi: ' + math.pi); // "pi: 3.141592653589793" unterminated strings console.log('"java" + "script" = \"' + 'java' + 'script\"); // syntax
error: missing ) after argument list here javascript thinks that you meant to have ); inside the string and ignores it, and it ends up not knowing that you meant the ); to end the function console.log. to fix this, we could put a' after the "script" string: console.log('"java" + "script" = \"' + 'java' + 'script\"'); // '"java" + "script" = "javascript"' ...
TypeError: "x" is read-only - JavaScript
the javascript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property. message type
error: assignment to read-only properties is not allowed in strict mode (edge) type
error: "x" is read-only (firefox) type
error: 0 is read-only (firefox) type
error: cannot assign to read only property 'x' of #<object> (chrome) type
error: cannot assign to read only property '0' of [object array] (chrome)
error type type
error what went wrong? the global variable or object property that was assigned to is a read-only property. (technically, it is a non-writable data property.) this
error happens only in strict mode code. in non-strict code, the assignment is silently ignored. examples invalid cases read-only properties are no...
...ly property. (technically, it is a non-writable data property.) this
error happens only in strict mode code. in non-strict code, the assignment is silently ignored. examples invalid cases read-only properties are not super common, but they can be created using object.defineproperty() or object.freeze(). 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); obj.score = 0; // type
error 'use strict'; object.defineproperty(this, 'lung_count', {value: 2, writable: false}); lung_count = 3; // type
error 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray[0]++; // type
error there are also a few read-only properties built into javascript. maybe you tried to redefine a mathematical constant. 'use strict'; math.pi = 4; // type
error sorry, you can't do that. ...
...rror 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray[0]++; // type
error there are also a few read-only properties built into javascript. maybe you tried to redefine a mathematical constant. 'use strict'; math.pi = 4; // type
error sorry, you can't do that. ...
...rray[0]++; // type
error there are also a few read-only properties built into javascript. maybe you tried to redefine a mathematical constant. 'use strict'; math.pi = 4; // type
error sorry, you can't do that. ...
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
the javascript exception "'use strict' not allowed in function" occurs when a "use strict" directive is used at the top of a function with default parameters, rest parameters, or destructuring parameters. message edge: cannot apply strict mode on functions with non-simple parameter list firefox: syntax
error: "use strict" not allowed in function with default parameter syntax
error: "use strict" not allowed in function with rest parameter syntax
error: "use strict" not allowed in function with destructuring parameter chrome: syntax
error: illegal 'use strict' directive in function with non-simple parameter list
error type syntax
error. what went wrong? a "use strict" directive is written at the top of a function that has one of the following parameters: default parameters rest parameter...
...t" directive is written at the top of a function that has one of the following parameters: default parameters rest parameters destructuring parameters a "use strict" directive is not allowed at the top of such functions per the ecmascript specification. ...
... strict'; return a + b; } if the function should be in strict mode, and the entire script or enclosing function is also okay to be in strict mode, you can move the "use strict" directive outside of the function: 'use strict'; function sum(a = 1, b = 2) { return a + b; } function expression a function expression can use yet another workaround: var sum = function sum([a, b]) { // syntax
error: "use strict" not allowed in function with destructuring parameter 'use strict'; return a + b; }; this can be converted to the following expression: var sum = (function() { 'use strict'; return function sum([a, b]) { return a + b; }; })(); arrow function if an arrow function needs to access the this variable, you can use the arrow function as the enclosing function: var callb...
...nction with destructuring parameter 'use strict'; return a + b; }; this can be converted to the following expression: var sum = (function() { 'use strict'; return function sum([a, b]) { return a + b; }; })(); arrow function if an arrow function needs to access the this variable, you can use the arrow function as the enclosing function: var callback = (...args) => { // syntax
error: "use strict" not allowed in function with rest parameter 'use strict'; return this.run(args); }; this can be converted to the following expression: var callback = (() => { 'use strict'; return (...args) => { return this.run(args); }; })(); ...
TypeError: 'x' is not iterable - JavaScript
the javascript exception "is not iterable" occurs when 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. message type
error: 'x' is not iterable (firefox, chrome) type
error: 'x' is not a function or its return value is not iterable (chrome)
error type type
error 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. examples iterating over object properties in javascript, objects are not iterable unless they implement the it...
...le type such as array, string or map, a generator result, or an object implementing the iterable protocol. examples iterating over object properties in javascript, objects are not iterable unless they implement the iterable protocol. therefore, you cannot use for…of to iterate over the properties of an object. var obj = { 'france': 'paris', 'england': 'london' }; for (let p of obj) { // type
error: obj is not iterable // … } instead you have to use object.keys or object.entries, to iterate over the properties or entries of an object. var obj = { 'france': 'paris', 'england': 'london' }; // iterate over the property names: for (let country of object.keys(obj)) { var capital = obj[country]; console.log(country, capital); } for (const [country, capital] of object.entries(obj...
...s()) { let capital = map[country]; console.log(country, capital); } for (let capital of map.values()) console.log(capital); for (const [country, capital] of map.entries()) console.log(country, capital); iterating over a generator generators are functions you call to produce an iterable object. function* generate(a, b) { yield a; yield b; } for (let x of generate) // type
error: generate is not iterable console.log(x); when they are not called, the function object corresponding to the generator is callable, but not iterable. calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator. function* generate(a, b) { yield a; yield b; } for (let x of generate(1,2)) console.log(x); itera...
...able custom iterables can be created by implementing the symbol.iterator method. you must be certain that your iterator method returns an object which is an iterator, which is to say it must have a next method. ...
getLastError - Archive of obsolete content
getlast
error returns the most recent nonzero
error code. method of install object syntax int getlast
error (); parameters none. returns the most recent nonzero
error code. for a list of possible values, see return codes. description use getlast
error method to obtain the most recent nonzero
error code since initinstall or reset
error were called. this method allows you to defer checking for
error codes each time you call addfile or adddirectory until the last addfile or adddirectory call. the getlast
error method does not return
errors from methods that return objects, such as getfolder. ...
...e getlast
error method to obtain the most recent nonzero
error code since initinstall or reset
error were called. this method allows you to defer checking for
error codes each time you call addfile or adddirectory until the last addfile or adddirectory call. the getlast
error method does not return
errors from methods that return objects, such as getfolder. ...
...odes each time you call addfile or adddirectory until the last addfile or adddirectory call. the getlast
error method does not return
errors from methods that return objects, such as getfolder. ...
resetError - Archive of obsolete content
reset
error resets a saved
error code to zero. method of install object syntax void reset
error (); parameters none. returns nothing. description the reset
error method resets any saved
error code to zero. see getlast
error for additional information. ...
... reset
error resets a saved
error code to zero. method of install object syntax void reset
error (); parameters none. returns nothing. description the reset
error method resets any saved
error code to zero. see getlast
error for additional information. ...
... reset
error resets a saved
error code to zero. method of install object syntax void reset
error (); parameters none. returns nothing. description the reset
error method resets any saved
error code to zero. see getlast
error for additional information. ...
Syntax error - MDN Web Docs Glossary: Definitions of Web-related terms
an exception caused by the incorrect use of a pre-defined syntax. syntax
errors are detected while compiling or parsing source code. for example, if you leave off a closing brace (}) when defining a javascript function, you trigger a syntax
error. browser development tools display javascript and css syntax
errors in the console. ...
... an exception caused by the incorrect use of a pre-defined syntax. syntax
errors are detected while compiling or parsing source code. for example, if you leave off a closing brace (}) when defining a javascript function, you trigger a syntax
error. browser development tools display javascript and css syntax
errors in the console. ...
...an exception caused by the incorrect use of a pre-defined syntax. syntax
errors are detected while compiling or parsing source code. for example, if you leave off a closing brace (}) when defining a javascript function, you trigger a syntax
error. browser development tools display javascript and css syntax
errors in the console. ...
mozbrowsererror
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowser
error event is fired when an
error occurs while trying to load content within a browser <iframe>. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event. bubbles read only boolean whether the event normally bub...
... the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. detail the detail property returns an anonymous javascript object with the following properties: type a domstring representing the type of
error that occurred. possible values are: fatal(crash) unknownprotocolfound filenotfound dnsnotfound connectionfailure netinterrupt nettimeout cspblocked phishingblocked malwareblocked unwantedblocked offline malformeduri redirectloop unknownsockettype netreset notcached isprinting deniedportaccess proxyresolvefailure proxyconnectfailure contentencodingfail...
... unknownprotocolfound filenotfound dnsnotfound connectionfailure netinterrupt nettimeout cspblocked phishingblocked malwareblocked unwantedblocked offline malformeduri redirectloop unknownsockettype netreset notcached isprinting deniedportaccess proxyresolvefailure proxyconnectfailure contentencodingfailure remotexul unsafecontenttype corruptedcontent
error cert
error other example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowser
error", function( event ) { console.log("an
error occurred:" + event.detail); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow moz...
JSErrorFormatString
this article covers features introduced in spidermonkey 17 represent
error message and type. syntax typedef struct js
errorformatstring { const char *format; uint16_t argcount; int16_t exntype; } js
errorformatstring; name type description format const char * the
error format string in ascii. argcount uint16_t the number of arguments to expand in the formatted
error message. exntype int16_t one of the jsexntype constants. description js
errorformatstring is a struct to represent
error message and type, returned by js_report
errornumber function. ...
...ion format const char * the
error format string in ascii. argcount uint16_t the number of arguments to expand in the formatted
error message. exntype int16_t one of the jsexntype constants. description js
errorformatstring is a struct to represent
error message and type, returned by js_report
errornumber function. ...
...the
error format string in ascii. argcount uint16_t the number of arguments to expand in the formatted
error message. exntype int16_t one of the jsexntype constants. description js
errorformatstring is a struct to represent
error message and type, returned by js_report
errornumber function. ...
JS_ErrorFromException
get or create js
errorreport from an exception object. syntax js
errorreport * js_
errorfromexception(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_
errorfromexception 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. ...
... 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_
errorfromexception will return the address of that struct. otherwise, it returns nullptr. ...
.... description if obj is an exception object, the exception will have (or be able to lazily create) an
error report struct, and js_
errorfromexception will return the address of that struct. otherwise, it returns nullptr. ...
JS_GetErrorPrototype
this article covers features introduced in spidermonkey 38 return the original value of
error.prototype. syntax jsobject * js_get
errorprototype(jscontext *cx); 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. ...
...rs features introduced in spidermonkey 38 return the original value of
error.prototype. syntax jsobject * js_get
errorprototype(jscontext *cx); 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. description js_get
errorprototype returns the original value of
error.prototype from the global object of the current compartment of cx. ...
... 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. ...
Element.onfullscreenerror - Web APIs
the element interface's onfullscreen
error property is an event handler for the fullscreen
error event which is sent to the element when an
error occurs while attempting to transition into or out of full-screen mode. syntax targetelement.onfullscreen
error = fullscreen
errorhandler; value an
error handler for the fullscreen
error event. example this example attempts to switch into full-screen mode from outside a handler for a user-initiated event (such as a click or keypress event). ...
...to or out of full-screen mode. syntax targetelement.onfullscreen
error = fullscreen
errorhandler; value an
error handler for the fullscreen
error event. example this example attempts to switch into full-screen mode from outside a handler for a user-initiated event (such as a click or keypress event). since full-screen mode changes are only permitted in response to a user input, this causes an
error to occur, which triggers the delivery of the fullscreen
error event to the
error handler, let elem = document.queryselector("video")}} elem.onfullscreen
error = function ( event ) { displaywarning("unable to switch into full-screen mode."); }; //.... elem.requestfullscreen(); specifications specification status comment fullscreen apithe definition of 'onfullscree...
...to occur, which triggers the delivery of the fullscreen
error event to the
error handler, let elem = document.queryselector("video")}} elem.onfullscreen
error = function ( event ) { displaywarning("unable to switch into full-screen mode."); }; //.... elem.requestfullscreen(); specifications specification status comment fullscreen apithe definition of 'onfullscreen
error' in that specification. living standard initial definition. ...
GeolocationPositionError - Web APIs
the geolocationposition
error interface represents the reason of an
error occurring when using the geolocating device. properties the geolocationposition
error interface doesn't inherit any property. geolocationposition
error.code read only secure context returns an unsigned short representing the
error code. the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position returned an internal
error. 3 timeout the time allowed to acquire the geolocation, ...
...idn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position returned an internal
error. 3 timeout the time allowed to acquire the geolocation, defined by positionoptions.timeout information was reached before the information was obtained. geolocationposition
error.message read only secure context returns a human-readable domstring describing the details of the
error. specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface. methods the geolocationposition
error interface neither implements nor inherits any method. specifications specification status comment geol...
...an-readable domstring describing the details of the
error. specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface. methods the geolocationposition
error interface neither implements nor inherits any method. specifications specification status comment geolocation apithe definition of 'geolocationposition
error' in that specification. recommendation initial specification. ...
HTMLMediaElement.error - Web APIs
the htmlmediaelement.
error is the media
error object for the most recent
error, or null if there has not been an
error. when an
error event is received by the element, you can determine details about what happened by examining this object. syntax var my
error = htmlmediaelement.
error; value a media
error object describing the most recent
error to occur on the media element or null if no
errors have occurred. example this example establishes a video element and adds an
error handler to it; the
error handler simply logs the details to console. ...
...mining this object. syntax var my
error = htmlmediaelement.
error; value a media
error object describing the most recent
error to occur on the media element or null if no
errors have occurred. example this example establishes a video element and adds an
error handler to it; the
error handler simply logs the details to console. var videoelement = document.createelement('video'); videoelement.on
error = function() { console.log("
error " + videoelement.
error.code + "; details: " + videoelement.
error.message); } videoelement.src = "https://example.com/bogusvideo.mp4"; specifications specification status comment html living standardthe definition of 'htmlmediaelement.
error' in that specification. living standard html5the definition of 'htmlmediaelemen...
... function() { console.log("
error " + videoelement.
error.code + "; details: " + videoelement.
error.message); } videoelement.src = "https://example.com/bogusvideo.mp4"; specifications specification status comment html living standardthe definition of 'htmlmediaelement.
error' in that specification. living standard html5the definition of 'htmlmediaelement.
error' in that specification. recommendation ...
MediaRecorderErrorEvent() - Web APIs
the mediarecorder
errorevent() constructor creates a new mediarecorder
errorevent object that represents an
error that occurred during the recording of media by the mediastream recording api. in general, you won't create these yourself; they are delivered to your implementation of mediarecorder.on
error when
errors occur while recording media. syntax var
errorevent = new mediarecorder
errorevent(
errorinfo) parameters
errorinfo an object describing the
error object to be created. it must contain the
error property at a minimum.
error a domexception 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. ...
...ent = new mediarecorder
errorevent(
errorinfo) parameters
errorinfo an object describing the
error object to be created. it must contain the
error property at a minimum.
error a domexception 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 rely on this information in a production environment. ...
...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 rely on this information in a production environment. specifications specification status comment mediastream recordingthe definition of 'mediarecorder
errorevent()' in that specification. working draft initial definition. ...
RTCIdentityErrorEvent.idp - Web APIs
the read-only property rtcidentity
errorevent.idp returns the domstring describing the domain name of the identity provider (idp) generating the
error response event. firefox implements the interface of this property under the following name: rtcpeerconnectionidentity
errorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
...ider (idp) generating the
error response event. firefox implements the interface of this property under the following name: rtcpeerconnectionidentity
errorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
...kely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCPeerConnection.onicecandidateerror - Web APIs
the rtcpeerconnection.onicecandidate
error property is an eventhandler which specifies a function which is called to handle the icecandidate
error event when it occurs on an rtcpeerconnection instance. this event is fired when an
error occurs during the ice candidate gathering process. syntax rtcpeerconnection.onicecandidate
error = eventhandler; value this should be set to a function you provide which is passed a single parameter: an rtcpeerconnectionice
errorevent object describing the icecandidate
error event. the event offers properties describing the
error to help you handle it appropriately. example pc.onicecandidate
error = function(event) { if (event.
errorcode >= 300 && event.
errorcode <= 699) { // stun
errors are in the range 300-699. see rfc 5389, section 15.6 // for a l...
... an rtcpeerconnectionice
errorevent object describing the icecandidate
error event. the event offers properties describing the
error to help you handle it appropriately. example pc.onicecandidate
error = function(event) { if (event.
errorcode >= 300 && event.
errorcode <= 699) { // stun
errors are in the range 300-699. see rfc 5389, section 15.6 // for a list of codes. turn adds a few more
error codes; see // rfc 5766, section 15 for details. } else if (event.
errorcode >= 700 && event.
errorcode <= 799) { // server could not be reached; a specific
error number is // provided but these are not yet specified. } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.o...
... // rfc 5766, section 15 for details. } else if (event.
errorcode >= 700 && event.
errorcode <= 799) { // server could not be reached; a specific
error number is // provided but these are not yet specified. } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.onicecandidate
error' in that specification. candidate recommendation initial specification. ...
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 type
error 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...
... living standard initial definition. ...
...ot 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
error() to manually trigger a stream
error if another part of the system it relies on fails. specifications specification status comment streamsthe definition of '
error()' in that specification. living standard initial definition. ...
SpeechSynthesisUtterance.onerror - Web APIs
}; examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... ...
...}; examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... ...
...voices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.on
error = function(event) { console.log('an
error has occurred with the speech synthesis: ' + event.
error); } inputtxt.blur(); } specifications specification status comment web speech apithe definition of 'on
error' in that specification. draft ...
WebGLRenderingContext.getError() - Web APIs
the webglrenderingcontext.get
error() method of the webgl api returns
error information. syntax glenum gl.get
error(); parameters none. return value constant description gl.no_
error no
error has been recorded. the value of this constant is 0. gl.invalid_enum an unacceptable value has been specified for an enumerated argument. the command is ignored and the
error flag is set. gl.invalid_value a numeric argument is out of range. the command is ignored and the
error flag is set. gl.invalid_operation the specified command is not allowed for the current state. the command is ignored and the
error flag is set. gl.invalid_framebuffer_operation the currently bound framebuffer is not framebuffer complete when trying to ren...
...ified command is not allowed for the current state. the command is ignored and the
error flag is set. gl.invalid_framebuffer_operation the currently bound framebuffer is not framebuffer complete when trying to render to or to read from it. gl.out_of_memory not enough memory is left to execute the command. gl.context_lost_webgl if the webgl context is lost, this
error is returned on the first call to get
error. afterwards and until the context has been restored, it returns gl.no_
error. examples gl.get
error(); // gl.no_
error (0) gl.enable(gl.foobar); gl.get
error(); // gl.invalid_enum; specifications specification status comment webgl 1.0the definition of 'get
error' in that specification. recommendation initial definition...
...rwards and until the context has been restored, it returns gl.no_
error. examples gl.get
error(); // gl.no_
error (0) gl.enable(gl.foobar); gl.get
error(); // gl.invalid_enum; specifications specification status comment webgl 1.0the definition of 'get
error' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glget
error' in that specification. standard man page of the opengl api. ...
XMLHttpRequestEventTarget.onerror - Web APIs
the xmlhttprequesteventtarget.on
error is the function called when an xmlhttprequest transaction fails due to an
error. syntax xmlhttprequest.on
error = callback; values callback is the function to be executed when the request fails. ...
... the xmlhttprequesteventtarget.on
error is the function called when an xmlhttprequest transaction fails due to an
error. syntax xmlhttprequest.on
error = callback; values callback is the function to be executed when the request fails. ...
...
error is the function called when an xmlhttprequest transaction fails due to an
error. syntax xmlhttprequest.on
error = callback; values callback is the function to be executed when the request fails. ...
500 Internal Server Error - HTTP
the hypertext transfer protocol (http) 500 internal server
error server
error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. this
error response is a generic "catch-all" response. usually, this indicates the server cannot find a better 5xx
error code to response. sometimes, server administrators log
error responses like the 500 status code with more details about the request to prevent the
error from happening again in the future. ...
...ed condition that prevented it from fulfilling the request. this
error response is a generic "catch-all" response. usually, this indicates the server cannot find a better 5xx
error code to response. sometimes, server administrators log
error responses like the 500 status code with more details about the request to prevent the
error from happening again in the future. ...
...e. usually, this indicates the server cannot find a better 5xx
error code to response. sometimes, server administrators log
error responses like the 500 status code with more details about the request to prevent the
error from happening again in the future. ...
TypeError: can't access property "x" of "y" - JavaScript
the javascript exception "can't access property" occurs when property access was operated on undefined or null values. message type
error: unable to get property {x} of undefined or null reference (edge) type
error: can't access property {x} of {y} (firefox) type
error: {y} is undefined, can't access property {x} of it (firefox) type
error: {y} is null, can't access property {x} of it (firefox) examples: type
error: x is undefined, can't access property "prop" of it type
error: x is null, can't access property "prop" of it type
error: can't access property "prop" of undefined type
error: can't access property "prop" of null
error type type
error. what went wrong? the property access was operated on undefined or null value. examples invalid cases // undefined and null cases on which the subst...
... if (typeof foo !== 'undefined') { // now we know that foo is defined, we are good to go. ...
... if (typeof foo !== 'undefined') { // now we know that foo is defined, we are good to go. ...
TypeError: can't define property "x": "obj" is not extensible - JavaScript
the javascript exception "can't define property "x": "obj" is not extensible" occurs when object.preventextensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. message type
error: cannot create property for a non-extensible object (edge) type
error: can't define property "x": "obj" is not extensible (firefox) type
error: cannot define property: "x", object is not extensible. (chrome)
error type type
error what went wrong? usually, an object is extensible and new properties can be added to it. however, in this case object.preventextensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. ...
...s extensible and new properties can be added to it. however, in this case object.preventextensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. examples adding new properties to a non-extensible objects in strict mode, attempting to add new properties to a non-extensible object throws a type
error. in sloppy mode, the addition of the "x" property is silently ignored. 'use strict'; var obj = {}; object.preventextensions(obj); obj.x = 'foo'; // type
error: can't define property "x": "obj" is not extensible in both, strict mode and sloppy mode, a call to object.defineproperty() throws when adding a new property to a non-extensible object. var obj = { }; object.preventextensions(obj); ob...
...tly ignored. 'use strict'; var obj = {}; object.preventextensions(obj); obj.x = 'foo'; // type
error: can't define property "x": "obj" is not extensible in both, strict mode and sloppy mode, a call to object.defineproperty() throws when adding a new property to a non-extensible object. var obj = { }; object.preventextensions(obj); object.defineproperty(obj, 'x', { value: "foo" } ); // type
error: can't define property "x": "obj" is not extensible to fix this
error, you will either need to remove the call to object.preventextensions() entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible. of course you can also remove the property that was attempted to be added, if you don't need it. 'use strict'; var obj = {}; o...
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
the javascript exception "property is non-configurable and can't be deleted" occurs when it was attempted to delete a property, but that property is non-configurable. message type
error: calling delete on 'x' is not allowed in strict mode (edge) type
error: property "x" is non-configurable and can't be deleted. (firefox) type
error: cannot delete property 'x' of #<object> (chrome)
error type type
error in strict mode only. what went wrong? it was attempted to delete a property, but that property is non-configurable. the configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. this
error happens only in strict mode code. in non-strict code, the operation returns false. examples attempting to delete...
...writable) can be changed. this
error happens only in strict mode code. in non-strict code, the operation returns false. examples attempting to delete non-configurable properties non-configurable properties are not super common, but they can be created using object.defineproperty() or object.freeze(). 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); delete obj.score; // type
error 'use strict'; var obj = {}; object.defineproperty(obj, 'foo', {value: 2, configurable: false}); delete obj.foo; // type
error 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray.pop(); // type
error there are also a few non-configurable properties built into javascript. maybe you tried to delete a mathematical constant. ...
...e; // type
error 'use strict'; var obj = {}; object.defineproperty(obj, 'foo', {value: 2, configurable: false}); delete obj.foo; // type
error 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray.pop(); // type
error there are also a few non-configurable properties built into javascript. maybe you tried to delete a mathematical constant. ...
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
the javascript strict mode-only exception "applying the 'delete' operator to an unqualified name is deprecated" occurs when variables are attempted to be deleted using the delete operator. message syntax
error: calling delete on expression not allowed in strict mode (edge) syntax
error: applying the 'delete' operator to an unqualified name is deprecated (firefox) syntax
error: delete of an unqualified identifier in strict mode. (chrome)
error type syntax
error in strict mode only. what went wrong? normal variables in javascript can't be deleted using the delete operator. in strict mode, an attempt to delete a variable will throw an
error and is not allowed. the delete operator can only delete properties on an object. object properties are "qualified" if they are configurable. unlike what ...
...
error and is not allowed. the delete operator can only delete properties on an object. object properties are "qualified" if they are configurable. unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. memory management is done indirectly via breaking references, see the memory management page and the delete operator page for more details. this
error only happens in strict mode code. in non-strict code, the operation just returns false. examples freeing the contents of a variable attempting to delete a plain variable, doesn't work in javascript and it throws an
error in strict mode: 'use strict'; var x; // ... ...
...aking references, see the memory management page and the delete operator page for more details. this
error only happens in strict mode code. in non-strict code, the operation just returns false. examples freeing the contents of a variable attempting to delete a plain variable, doesn't work in javascript and it throws an
error in strict mode: 'use strict'; var x; // ... delete x; // syntax
error: applying the 'delete' operator to an unqualified name // is deprecated to free the contents of a variable, you can set it to null: 'use strict'; var x; // ... x = null; // x can be garbage collected ...
SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated - JavaScript
the javascript strict mode-only exception "0-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead" occurs when deprecated octal literals and octal escape sequences are used. message syntax
error: octal numeric literals and escape characters not allowed in strict mode (edge) syntax
error: "0"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead
error type syntax
error in strict mode only. what went wrong? octal literals and octal escape sequences are deprecated and will throw a syntax
error in strict mode. with ecmascript 2015 and later, the standardized syntax uses a leading zero followed by a lowercase or uppercase latin letter "o" (0o or 0o). examples "0"-prefixed oc...
... "0o" prefix instead
error type syntax
error in strict mode only. what went wrong? ...
...cated and will throw a syntax
error in strict mode. with ecmascript 2015 and later, the standardized syntax uses a leading zero followed by a lowercase or uppercase latin letter "o" (0o or 0o). ...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
what went wrong? there was an assignment (=) when you would normally expect a test for equality (==). to help debugging, javascript (with strict warnings enabled) warns about this pattern. ...
... what went wrong? there was an assignment (=) when you would normally expect a test for equality (==). to help debugging, javascript (with strict warnings enabled) warns about this pattern. ...
... what went wrong? there was an assignment (=) when you would normally expect a test for equality (==). to help debugging, javascript (with strict warnings enabled) warns about this pattern. ...
SyntaxError: missing name after . operator - JavaScript
you will have to specify the name of the property that you want to access. for computed property access, you might need to change your property access from using a dot to using square brackets. these will allow you to compute an expression. maybe you intended to do concatenation instead? a plus operator (+) is needed in that case. ...
...ute an expression. maybe you intended to do concatenation instead? a plus operator (+) is needed in that case. please see the examples below. examples property access property accessors in javascript use either the dot (.) or square brackets ([]), but not both. square brackets allow computed property access. var obj = { foo: { bar: "baz", bar2: "baz2" } }; var i = 2; obj.[foo].[bar] // syntax
error: missing name after . operator obj.foo."bar"+i; // syntax
error: missing name after . operator to fix this code, you need to access the object like this: obj.foo.bar; // "baz" // or alternatively obj["foo"]["bar"]; // "baz" // computed properties require square brackets obj.foo["bar" + i]; // "baz2" property access vs. concatenation if you are coming from another programming language (like...
...operator instead you need to use a plus sign for concatenation: console.log("hello" + "world"); ...
TypeError: "x" is not a constructor - JavaScript
the javascript exception "is not a constructor" occurs when there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. message type
error: object doesn't support this action (edge) type
error: "x" is not a constructor type
error: math is not a constructor type
error: json is not a constructor type
error: symbol is not a constructor type
error: reflect is not a constructor type
error: intl is not a constructor type
error: atomics is not a constructor
error type type
error 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. there are many global objects, like string or a...
... are many global objects, like string or array, which are constructable using new. however, some global objects are not and their properties and methods are static. the following javascript standard built-in objects are not a constructor: math, json, symbol, reflect, intl, atomics. generator functions cannot be used as constructors either. examples invalid cases var car = 1; new car(); // type
error: car is not a constructor new math(); // type
error: math is not a constructor new symbol(); // type
error: symbol is not a constructor function* f() {}; var obj = new f; // type
error: f is not a constructor a car constructor suppose you want to create an object type for cars. you want this type of object to be called car, and you want it to have properties for make, model, and year. to do th...
...= make; this.model = model; this.year = year; } now you can create an object called mycar as follows: var mycar = new car('eagle', 'talon tsi', 1993); in promises when returning an immediately-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it. ...
ReferenceError: assignment to undeclared variable "x" - JavaScript
the javascript strict mode-only exception "assignment to undeclated variable" occurs when the value has been assigned to an undeclared variable. message reference
error: assignment to undeclared variable "x" (firefox) reference
error: "x" is not defined (chrome) reference
error: variable undefined in strict mode (edge)
error type reference
error 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. three things to note about declared and undeclared variables: declared variables are constrained in the execution co...
...lared variables are always global. declared variables are created before any code is executed. undeclared variables do not exist until the code assigning to them is executed. declared variables are a non-configurable property of their execution context (function or global). undeclared variables are configurable (e.g. can be deleted). for more details and examples, see the var reference page. ...
...declared variables are configurable (e.g. can be deleted). for more details and examples, see the var reference page.
errors about undeclared variable assignments occur in strict mode code only. in non-strict code, they are silently ignored. examples invalid cases in this case, the variable "bar" is an undeclared variable. function foo() { 'use strict'; bar = true; } foo(); // reference
error: assignment to undeclared variable bar valid cases to make "bar" a declared variable, you can add the var keyword in front of it. function foo() { 'use strict'; var bar = true; } foo(); ...
error - Archive of obsolete content
read only. cancelable boolean is it possible to cancel the event? ...
...get (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete
error ...
PR_SetErrorText
sets the text associated with an
error. syntax #include <pr
error.h> void pr_set
errortext(printn textlength, const char *text) parameters the function has these parameters: textlength the length of the text in the text. may be null. if not null, and if text is zero, the string is assumed to be a null-terminated c string. otherwise the text is assumed to be the length specified and to possibly include null characters (as might occur in a multilingual string). text the text to associate with the
error. description the text is copied into the thread structure and remains there until the next call to pr_set
error. if there is
error text already present in the thread, the previous value is first deleted. the new value is copied into storage allocated and owned by nspr and remains th...
...t occur in a multilingual string). text the text to associate with the
error. description the text is copied into the thread structure and remains there until the next call to pr_set
error. if there is
error text already present in the thread, the previous value is first deleted. the new value is copied into storage allocated and owned by nspr and remains there until the next call to pr_set
error or another call to pr_set
errortext. nspr makes no use of this function. clients may use it for their own purposes. ...
nsISSLErrorListener
security/manager/ssl/public/nsissl
errorlistener.idlscriptable a mechanism to report a broken ssl connection. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) note: the recipient of this ssl status notification should not block. method overview boolean notifyssl
error(in nsiinterfacerequestor socketinfo, in print32
error, in autf8string targetsite); methods notifyssl
error() called in case of an ssl
error. boolean notifyssl
error( in nsiinterfacerequestor socketinfo, in print32
error, in autf8string targetsite ); parameters socketinfo a network communication context that can be used to obtain more information about the active connection.
error the code associated with the
error. the ssl status object that de...
... in autf8string targetsite ); parameters socketinfo a network communication context that can be used to obtain more information about the active connection.
error the code associated with the
error. the ssl status object that describes the problem(s). targetsite the site name that was used to open the current connection. return value the consumer shall return true if it wants to suppress the
error message related to the
error (the connection will still get canceled). see also nsisockettransport ...
AddressErrors.addressLine - Web APIs
an object based on address
errors includes an addressline property when validation of the address finds one or more
errors in the array of strings in the address's addressline. the returned string explains the
error and should offer suggestions for how to correct it. syntax var addressline
error = address
errors.addressline; value if an
error occurred during validation of the address due to one of the strings in the addressline array having an invalid value, this property is set to a domstring providing a human-readable
error message explaining the validation
error. the text should also include, when possible, advice about how to go about correcting the
error. ...
...ne of the strings in the addressline array having an invalid value, this property is set to a domstring providing a human-readable
error message explaining the validation
error. the text should also include, when possible, advice about how to go about correcting the
error. if the paymentaddress object's addressline property was determined to be valid, this property is not included in the address
errors dictionary. specifications specification status comment payment request apithe definition of 'address
errors.addressline' in that specification. candidate recommendation initial definition. ...
AddressErrors.dependentLocality - Web APIs
an object based on address
errors includes a dependentlocality property when the address's dependentlocality property couldn't be validated. the returned string explains the
error and should offer suggestions for how to correct it. syntax var locality
error = address
errors.dependentlocality; value if the value specified in the paymentaddress object's dependentlocality property could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. if the dependentlocality value was validated successfully, this property is not included in the address
errors object. ...
...ty could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. if the dependentlocality value was validated successfully, this property is not included in the address
errors object. specifications specification status comment payment request apithe definition of 'address
errors.dependentlocality' in that specification. candidate recommendation initial definition. ...
AddressErrors.organization - Web APIs
an object based on address
errors includes an organization property when the address's organization property couldn't be validated. the returned string explains the
error and should offer suggestions for how to correct it. syntax var organization
error = address
errors.organization; value if the value specified in the paymentaddress object's organization property could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. for example, if validation simply ensures that only permitted characters are included in the organization's name, this might return a string such as "the organization name may only contain the letters a-z, digits, spaces, and commas." if the organization value was validat...
...f the validation
error and offers suggestions for correcting it. for example, if validation simply ensures that only permitted characters are included in the organization's name, this might return a string such as "the organization name may only contain the letters a-z, digits, spaces, and commas." if the organization value was validated successfully, this property is not included in the address
errors object. specifications specification status comment payment request apithe definition of 'address
errors.organization' in that specification. candidate recommendation initial definition. ...
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. msg a javascript string containing zero or more substitution strings. subst1 ... substn javascript objects with which to replace substitution strings within msg. this gives you additional control over the format of the output. ...
... containing zero or more substitution strings. subst1 ... substn javascript objects with which to replace substitution strings within msg. this gives you additional control over the format of the output. see outputting text to the console in the documentation of console for details. specifications specification status comment console apithe definition of 'console.
error()' in that specification. living standard initial definition ...
Document.onfullscreenerror - Web APIs
the document.onfullscreen
error property is an event handler for the fullscreen
error event that is sent to the document when it fails to transition into full-screen mode after a prior call to element.requestfullscreen(). syntax targetdocument.onfullscreen
error = fullscreen
errorhandler; value an event handler for the fullscreen
error event. example this example attempts to call requestfullscreen() outside of an event handler. since requestfullscreen() can only be called in response to user action, for security reasons, this will fail, causing the fullscreen
error to be sent to the document. document.onfullscreen
error = function ( event ) { displaywarning("unable to switch into full-screen mode."); }; //.... document.documentelement.requestfullscreen(); specifications speci...
...to user action, for security reasons, this will fail, causing the fullscreen
error to be sent to the document. document.onfullscreen
error = function ( event ) { displaywarning("unable to switch into full-screen mode."); }; //.... document.documentelement.requestfullscreen(); specifications specification status comment fullscreen apithe definition of 'onfullscreen
error' in that specification. living standard initial definition. ...
GeolocationPositionError.code - Web APIs
the geolocationposition
error.code read-only property is an unsigned short representing the
error code. syntax let typeerr = geolocationposition
errorinstance.code value an unsigned short representing the
error code. the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because one or several internal sources of position returned an internal
error. 3 timeout the time allowed to acquire the geolocation, defined by positionoptions.timeout information that was reached before the information was obtained. ...
... of the geolocation failed because one or several internal sources of position returned an internal
error. 3 timeout the time allowed to acquire the geolocation, defined by positionoptions.timeout information that was reached before the information was obtained. specifications specification status comment geolocation apithe definition of 'position
error.code' in that specification. recommendation initial definition ...
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
the webglcontextcreation
error event of the webgl api is fired if the user agent is unable to create a webglrenderingcontext context. this event has a webglcontextevent.statusmessage property, which can contain a platform dependent string with more information about the failure. ...
... context. this event has a webglcontextevent.statusmessage property, which can contain a platform dependent string with more information about the failure. bubbles yes cancelable yes interface webglcontextevent event handler property none example var canvas = document.getelementbyid('canvas'); canvas.addeventlistener('webglcontextcreation
error', function(e) { console.log(e.statusmessage || 'unknown
error'); }, false); var gl = canvas.getcontext('webgl'); // logs statusmessage or "unknown
error" if unable to create webgl context specifications specification status comment webgl 1.0the definition of 'webglcontextcreation
error' in that specification. recommendation initial definition. ...
OverconstrainedError - Web APIs
the overconstrained
error interface of the media capture and streams api indicates that the set of desired capabilities for the current mediastreamtrack cannot currently be met. when this event is thrown on a mediastreamtrack, it is muted until either the current constraints can be established or until satisfiable constraints are applied. constructor overconstrained
error.overconstrained
error() creates a new overconstrained
error object. properties overconstrained
error.constraint read only returns the constraint that was supplied in the constructor, meaning the constraint that was not satisfied. overconstrained
error.message read only returns the text supplied in the constructor. overconstrained
error.name read only will always return overconstrained
error. methods no...
... that was supplied in the constructor, meaning the constraint that was not satisfied. overconstrained
error.message read only returns the text supplied in the constructor. overconstrained
error.name read only will always return overconstrained
error. methods none. specifications specification status comment media capture and streamsthe definition of 'overconstrained
error' in that specification. candidate recommendation initial definition. ...
PayerErrors - Web APIs
the payer
errors dictionary is used by the payment request api to indicate the presence of—and to explain how to correct—validation
errors in the payer details. for each field in the payment information that fails validation, the payer
errors object contains a string explaining the
error. the payer details include the payer's name, phone number, and email address. properties email optional if present, this domstring is a string describing the validation
error from which the payer's email address—as given by paymentresponse.payeremail—currently suffers. if this property is absent from the payer
errors object, the email address passed validation. name optional if this domstring is present in the object, the paymentresponse.payername property failed validation, and this string explai...
...sponse.payeremail—currently suffers. if this property is absent from the payer
errors object, the email address passed validation. name optional if this domstring is present in the object, the paymentresponse.payername property failed validation, and this string explains what needs to be corrected. if this property is absent, the paer name is fine phone optional if present, this string is an
error message explaining why the payer's phone number (paymentresponse.payerphone) failed validation. this property is absent if the phone number passed validation. example specifications specification status comment payment request apithe definition of 'payer
errors' in that specification. candidate recommendation initial definition. ...
PaymentDetailsUpdate.shippingAddressErrors - Web APIs
the paymentdetailsupdate dictionary's shippingaddress
errors property, if present, contains an address
errors object whose contents provide
error messages for one or more of the values in the paymentaddress specified as paymentrequest.shippingaddress. syntax var address
errors = paymentdetailsupdate.shippingaddress
errors; value an address
errors object, which contains domstrings describing
errors in the properties of a paymentaddress. for each property in paymentaddress, a property by the same name is found in shippingaddress
errors if and only if a validation
error occurred for that property. in that case, the property in shippingaddress
errors is a string describing the validation
error, ideally including suggestions about fixing the
error. specifications specification ...
...ame name is found in shippingaddress
errors if and only if a validation
error occurred for that property. in that case, the property in shippingaddress
errors is a string describing the validation
error, ideally including suggestions about fixing the
error. specifications specification status comment payment request apithe definition of 'paymentdetailsupdate.shippingaddress
errors' in that specification. candidate recommendation initial definition. ...
RTCIdentityErrorEvent.loginUrl - Web APIs
the read-only property rtcidentity
errorevent.loginurl is a domstring giving the url where the user can complete the authentication. it can be null and is provided by the identity provider (idp). firefox implements the interface of this property under the following name: rtcpeerconnectionidentity
errorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
... provider (idp). firefox implements the interface of this property under the following name: rtcpeerconnectionidentity
errorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCIdentityErrorEvent.protocol - Web APIs
the read-only property rtcidentity
errorevent.protocol is a domstring describing the idp protocol in use. firefox implements the interface of this property under the following name: rtcpeerconnectionidentity
errorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
...domstring describing the idp protocol in use. firefox implements the interface of this property under the following name: rtcpeerconnectionidentity
errorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCPeerConnection: idpvalidationerror event - Web APIs
an idpvalidation
error event informs the target, a rtcpeerconnection object's onidpvalidation
error event handler, that the identity provider (idp) encountered an
error while validating an identity assertion. an event handler for this event can be added using the rtcpeerconnection.onidpvalidation
error property. bubbles no cancelable no interface rtcidentity
errorevent event handler property onidpvalidation
error warning: this event is no longer used; instead, you can detect a validation
error by detecting when the promise returned by rtcpeerconnection.peeridentity is rejected. ...
...ty
errorevent event handler property onidpvalidation
error warning: this event is no longer used; instead, you can detect a validation
error by detecting when the promise returned by rtcpeerconnection.peeridentity is rejected. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'idpvalidation
error' in that specification. candidate recommendation ...
RTCPeerConnection: idpvalidationerror event - Web APIs
an idpvalidation
error event informs the target, a rtcpeerconnection object, that the identity provider (idp) encountered an
error when trying to validate an identity assertion. an event handler for this event can be added via the rtcpeerconnection.onidpvalidation
error property. bubbles no cancelable no interface rtcidentity
errorevent event handler property onidpvalidation
error important: this event is no longer used; it was removed from the specification long ago. instead, you should watch for the rtcpeerconnection.peeridentity promise to be rejected with an operation
error. ...
...er property onidpvalidation
error important: this event is no longer used; it was removed from the specification long ago. instead, you should watch for the rtcpeerconnection.peeridentity promise to be rejected with an operation
error. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'idpvalidation
error' in that specification. candidate recommendation initial definition. ...
SpeechSynthesisErrorEvent - Web APIs
the speechsynthesis
errorevent interface of the web speech api contains information about any
errors that occur while processing speechsynthesisutterance objects in the speech service. properties speechsynthesis
errorevent extends the speechsynthesisevent interface, which inherits properties from its parent interface, event. speechsynthesis
errorevent.
error read only returns an
error code indicating what has gone wrong with a speech synthesis attempt. methods speechsynthesis
errorevent extends the speechsynthesisevent interface, which inherits methods from its parent interface, event. examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voi...
...voices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.on
error = function(event) { console.log('an
error has occurred with the speech synthesis: ' + event.
error); } inputtxt.blur(); } specifications specification status comment web speech apithe definition of 'speechsynthesis
errorevent' in that specification. draft ...
WritableStreamDefaultController.error() - Web APIs
the
error() method of the writablestreamdefaultcontroller interface causes any future interactions with the associated stream to
error. this method is rarely used, since usually it suffices to return 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 type
error the stream you are trying to
error is not a writablestream. examples const writablestream = new writablestream({ start(controller) { // do stuff with controller // e...
...reamdefaultcontroller.
error(e); parameters e a domstring representing the
error you want future interactions to fail with. return value undefined. exceptions type
error 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 specification status comment streamsthe definition of '
error()' in that specification. living standard initial definition. ...
::grammar-error - CSS: Cascading Style Sheets
the ::grammar-
error css pseudo-element represents a text segment which the user agent has flagged as grammatically incorrect. allowable properties only a small subset of css properties can be used in a rule with ::grammar-
error in its selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::grammar-
error examples simple document grammar check in this example, eventual supporting browsers should highlight any flagged grammatical
errors with the styles shown. ...
...ground-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::grammar-
error examples simple document grammar check in this example, eventual supporting browsers should highlight any flagged grammatical
errors with the styles shown. html <p>my friends is coming to the party tonight.</p> css ::grammar-
error { text-decoration: underline red; color: red; } result specifications specification status comment css pseudo-elements level 4the definition of '::grammar-
error' in that specification. working draft initial definition. ...
::spelling-error - CSS: Cascading Style Sheets
the ::spelling-
error css pseudo-element represents a text segment which the user agent has flagged as incorrectly spelled. allowable properties only a small subset of css properties can be used in a rule with ::spelling-
error in its selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::spelling-
error examples simple document spell check in this example, eventual supporting browsers should highlight any flagged spelling
errors with the styles shown. ...
...nd its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::spelling-
error examples simple document spell check in this example, eventual supporting browsers should highlight any flagged spelling
errors with the styles shown. html <p contenteditable spellcheck="true">my friends are coegdfgfddffbgning to the party tonight.</p> css ::spelling-
error { text-decoration: wavy red; } result specifications specification status comment css pseudo-elements level 4the definition of '::spelling-
error' in that specification. working draft initial definition. ...
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
the javascript exception "can't access lexical declaration `variable' before initialization" occurs when a lexical variable was accessed before it was initialized. this happens within any block statement, when let or const declarations are accessed before they are defined. message reference
error: use before delaration (edge) reference
error: can't access lexical declaration `x' before initialization (firefox) reference
error: 'x' is not defined (chrome)
error type reference
error what went wrong? a lexical variable was accessed before it was initialized. this happens within any block statement, when let or const declarations are accessed before they are defined. examples invalid cases in this case, the variable "foo" is redeclared in the block statement using let. function test() { l...
...eference
error what went wrong? a lexical variable was accessed before it was initialized. this happens within any block statement, when let or const declarations are accessed before they are defined. examples invalid cases in this case, the variable "foo" is redeclared in the block statement using let. function test() { let foo = 33; if (true) { let foo = (foo + 55); // reference
error: can't access lexical // declaration `foo' before initialization } } test(); valid cases to change "foo" inside the if statement, you need to remove the let that causes the redeclaration. function test(){ let foo = 33; if (true) { foo = (foo + 55); } } test(); ...
TypeError: can't assign to property "x" on "y": not an object - JavaScript
the javascript strict mode exception "can't assign to property" occurs when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean. primitive values cannot hold any property. message type
error: can't assign to property "x" on {y}: not an object (firefox) type
error: cannot create property 'x' on {y} (chrome)
error type type
error. what went wrong? in strict_mode, a type
error is raised when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean. primitive values cannot hold any property. the problem might be that an unexpected value is flowing at an unexpected place, or that an object variant of a string or a number is expected. examples invalid cases 'use strict'; var foo = "my string"; // the...
...n primitive value such as a symbol, a string, a number or a boolean. primitive values cannot hold any property. the problem might be that an unexpected value is flowing at an unexpected place, or that an object variant of a string or a number is expected. examples invalid cases 'use strict'; var foo = "my string"; // the following line does nothing if not in strict mode. foo.bar = {}; // type
error: can't assign to property "bar" on "my string": not an object fixing the issue either fix the code to prevent the primitive from being used in such places, or fix the issue is to create the object equivalent object. 'use strict'; var foo = new string("my string"); foo.bar = {}; ...
SyntaxError: identifier starts immediately after numeric literal - JavaScript
the javascript exception "identifier starts immediately after numeric literal" occurs when an identifier started with a digit. identifiers can only start with a letter, underscore (_), or dollar sign ($). message syntax
error: unexpected identifier after numeric literal (edge) syntax
error: identifier starts immediately after numeric literal (firefox) syntax
error: unexpected number (chrome)
error type syntax
error what went wrong? the names of variables, called identifiers, conform to certain rules, which your code must adhere to! a javascript identifier must start with a letter, underscore (_), or dollar sign ($). they can't start with a digit! only subsequent characters can be digits (0-9). examples variable names starting with numeric literals variable names can't start with numbers...
...identifiers, conform to certain rules, which your code must adhere to! a javascript identifier must start with a letter, underscore (_), or dollar sign ($). they can't start with a digit! only subsequent characters can be digits (0-9). examples variable names starting with numeric literals variable names can't start with numbers in javascript. the following fails: var 1life = 'foo'; // syntax
error: identifier starts immediately after numeric literal var foo = 1life; // syntax
error: identifier starts immediately after numeric literal alert(1.foo); // syntax
error: identifier starts immediately after numeric literal you will need to rename your variable to avoid the leading number. var life1 = 'foo'; var foo = life1; ...
SyntaxError: for-in loop head declarations may not have initializers - JavaScript
the javascript strict mode-only exception "for-in loop head declarations may not have initializers" occurs when the head of a for...in contains an initializer expression, such as |for (var i = 0 in obj)|. this is not allowed in for-of loops in strict mode. message syntax
error: for-in loop head declarations cannot have an initializer (edge) syntax
error: for-in loop head declarations may not have initializers (firefox) syntax
error: for-in loop variable declaration may not have an initializer. (chrome)
error type syntax
error in strict mode only. what went wrong? the head of a for...in loop contains an initializer expression. that is, a variable is declared and assigned a value |for (var i = 0 in obj)|. in non-strict mode, this head declaration is silently ignored and behaves like |for (var...
...riable declaration may not have an initializer. (chrome)
error type syntax
error in strict mode only. what went wrong? the head of a for...in loop contains an initializer expression. that is, a variable is declared and assigned a value |for (var i = 0 in obj)|. in non-strict mode, this head declaration is silently ignored and behaves like |for (var i in obj)|. in strict mode, however, a syntax
error is thrown. examples this example throws a syntax
error: "use strict"; var obj = {a: 1, b: 2, c: 3 }; for (var i = 0 in obj) { console.log(obj[i]); } // syntax
error: for-in loop head declarations may not have initializers valid for-in loop you can remove the initializer (i = 0) in the head of the for-in loop. "use strict"; var obj = {a: 1, b: 2, c: 3 }; for (var i in obj) { console.
SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript
the javascript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a for...of loop contains an initializer expression such as |for (var i = 0 of iterable)|. this is not allowed in for-of loops. message syntax
error: for-of loop head declarations cannot have an initializer (edge) syntax
error: a declaration in the head of a for-of loop can't have an initializer (firefox) syntax
error: for-of loop variable declaration may not have an initializer. (chrome)
error type syntax
error what went wrong? the head of a for...of loop contains an initializer expression. that is, a variable is declared and assigned a value |for (var i = 0 of iterable)|. this is not allowed in for-of loops. you might want a for loop that does allow an initializer. examp...
...maybe you intended to make 50 an offset value, in that case you could add it to the loop body, for example. ...
TypeError: "x" has no properties - JavaScript
the javascript exception "null (or undefined) has no properties" occurs when you attempt to access properties of null and undefined. they don't have any. message type
error: unable to get property {x} of undefined or null reference (edge) type
error: null has no properties (firefox) type
error: undefined has no properties (firefox)
error type type
error. ...
...es of null and undefined. they don't have any. message type
error: unable to get property {x} of undefined or null reference (edge) type
error: null has no properties (firefox) type
error: undefined has no properties (firefox)
error type type
error. what went wrong? both, null and undefined, have no properties you could access. examples null and undefined have no properties null.foo; // type
error: null has no properties undefined.bar; // type
error: undefined has no properties ...
ReferenceError: "x" is not defined - JavaScript
the javascript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere. message reference
error: "x" is not defined
error type reference
error. what went wrong? there is a non-existent variable referenced somewhere. this variable needs to be declared, or you need to make sure it is available in your current script or scope. note: when loading a library (such as jquery), make sure it is loaded before you access library variables, such as "$". put the <script> tag that loads the library before your code that uses it. examples variable not declared foo.substring(1); // reference
error: foo is not defined the "foo" variable isn't defined anywhere. it needs to be some string, so that the string.prototype.substring() method will work. var fo...
...ork. var foo = 'bar'; foo.substring(1); // "ar" wrong scope a variable needs to be available in the current context of execution. variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function function numbers() { var num1 = 2, num2 = 3; return num1 + num2; } console.log(num1); // reference
error num1 is not defined. however, a function can access all variables and functions defined inside the scope in which it is defined. in other words, a function defined in the global scope can access all variables defined in the global scope. var num1 = 2, num2 = 3; function numbers() { return num1 + num2; } console.log(numbers()); // 5 ...
SyntaxError: unterminated string literal - JavaScript
the javascript
error "unterminated string literal" occurs when there is an unterminated string somewhere. string literals must be enclosed by single (') or double (") quotes. message syntax
error: unterminated string constant (edge) syntax
error: unterminated string literal (firefox)
error type syntax
error what went wrong? there is an unterminated string somewhere. string literals must be enclosed by single (') or double (") quotes. javascript makes no distinction between single-quoted strings and double-quoted strings. escape sequences work in strings created with either single or double quotes. to fix this
error, check if: you have opening and closing quotes (single or double) for your string literal, you have escaped your string literal correctly, your string literal isn't split a...
...ur string literal, you have escaped your string literal correctly, your string literal isn't split across multiple lines. examples multiple lines you can't split a string across multiple lines like this in javascript: var longstring = 'this is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable.'; // syntax
error: unterminated string literal instead, use the + operator, a backslash, or template literals. the + operator variant looks like this: var longstring = 'this is a very long string which needs ' + 'to wrap across multiple lines because ' + 'otherwise my code is unreadable.'; or you can use the backslash character ("\") at the end of each line to indicate that th...
Error() constructor - JavaScript
the
error constructor creates an
error object. syntax new
error([message[, filename[, linenumber]]]) parameters messageoptional a human-readable description of the
error. filename optional the value for the filename property on the created
error object. defaults to the name of the file containing the code that called the
error() constructor. linenumber optional the value for the linenumber property on the created
error object. defaults to the line number containing the
error() constructor invocation. examples function call or new construction when
error is used like a function -- without new, it will return an
error object. therefore, a mere call to
error will produce the same output that constructing an
error object via the new keyword would. // this... ...
...e linenumber property on the created
error object. defaults to the line number containing the
error() constructor invocation. examples function call or new construction when
error is used like a function -- without new, it will return an
error object. therefore, a mere call to
error will produce the same output that constructing an
error object via the new keyword would. // this... const x =
error('i was created using a function call!') // ...has the same functionality as this. const y = new
error('i was constructed via the "new" keyword!') specifications specification ecmascript (ecma-262)the definition of '
error constructor' in that specification. ...
Error.prototype.message - JavaScript
the message property is a human-readable description of the
error. description this property contains a brief description of the
error if one is available or has been set. spidermonkey makes extensive use of the message property for exceptions. the message property combined with the name property is used by the
error.prototype.tostring() method to create a string representation of the
error. by default, the message property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the
error constructor. ...
...se of the message property for exceptions. the message property combined with the name property is used by the
error.prototype.tostring() method to create a string representation of the
error. by default, the message property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the
error constructor. examples throwing a custom
error var e = new
error('could not parse input'); // e.message is 'could not parse input' throw e; specifications specification ecmascript (ecma-262)the definition of '
error.prototype.message' in that specification. ...
Error.prototype.toSource() - JavaScript
the tosource() method returns code that could eval to the same
error. syntax e.tosource() return value a string containing the source code of the
error. examples using tosource calling the tosource method of an
error instance (including native
errors) will return a string containing the source code of the
error. this string can be evaluated to create an (approximately) equal object. naturally, the string containing the source follows the structure of the
error constructor. for example: (newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the
error instance. note: be aware that the properties used by the tosource method in the creation of this string are mutable and may not accurately reflect the function used to create a...
...rally, the string containing the source follows the structure of the
error constructor. for example: (newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the
error instance. note: be aware that the properties used by the tosource method in the creation of this string are mutable and may not accurately reflect the function used to create an
error instance or the filename or line number where the actual
error occurred. specifications not part of any standard. ...
<merror> - MathML
the mathml <m
error> element is used to display contents as
error messages. in firefox this
error message is rendered similar to the typical xml
error message. note that this
error is not thrown when your mathml markup is wrong or not well-formed xml. you will still get an xml parsing
error (in case of the xhtml notation of mathml), which has nothing to do with <m
error>. attributes class, id, style provided for use with stylesheets. href used to set a hyperlink to a specified uri. mathbackground the background color. you can use #rgb, #rrggbb and html color names. mathcolor the text color and also the fraction line color. you can use #rgb, #rrggbb and html color names. ...
...ml notation of mathml), which has nothing to do with <m
error>. attributes class, id, style provided for use with stylesheets. href used to set a hyperlink to a specified uri. mathbackground the background color. you can use #rgb, #rrggbb and html color names. mathcolor the text color and also the fraction line color. you can use #rgb, #rrggbb and html color names. examples <math> <m
error> <mrow> <mtext> division by zero: </mtext> <mfrac> <mn> 1 </mn> <mn> 0 </mn> </mfrac> </mrow> </m
error> </math> specifications specification status comment mathml 3.0the definition of 'm
error' in that specification. recommendation current specification mathml 2.0the definition of 'm
error' in that specification. recommen...
Errors
this page lists the
errors that can be raised due to firefox's anti-tracking functionality, governed by the storage access policy. you can find further information about them by clicking on the links below: a request to access cookies or storage was blocked because of a custom cookie permission blocked because it came from a tracker and content blocking is enabled blocked because we are blocking all storage access requests blocked because we are blocking all third-party storage access requests and content blocking is enabled granted partitioned access because it came from a third-party and dynamic first-party isolation is enabled ...
DownloadError
a download
error object provides detailed information about a download failure. properties attribute type description result read only nsresult the result code associated with this
error. becausesourcefailed read only boolean indicates an
error occurred while reading from the remote location. becausetargetfailed read only boolean indicates an
error occurred while writing to the local target. inherits properties from
error. ...
PRErrorCode
type for
error codes that can be retrieved with pr_get
error. you can also set your own
errors using pr_set
error. syntax #include <pr
error.h> typedef print32 pr
errorcode description the service nspr offers in this area is the ability to associate a thread-specific condition with an
error number. the
error number namespace is not well managed. nspr assumes
error numbers starting at -6000 (decimal) and progressing towards zero. at present less than 100
error codes have been defined. if nspr's
error handling is adopted by calling clients, then some sort of partitioning of the namespace will have to be employed. nspr does not attempt to address this issue. for nspr
errors, see
error codes. ...
PR_GetError
returns the current thread's last set platform-independent
error code. syntax #include <pr
error.h> pr
errorcode pr_get
error(void) returns the value returned is a 32-bit number. nspr provides no direct interpretation of the number's value. nspr does use pr_set
error to set
error numbers defined in
error codes. ...
PR_GetErrorTextLength
gets the length of the
error text. syntax #include <pr
error.h> print32 pr_get
errortextlength(void) returns if a zero is returned, no
error text is currently set. otherwise, the value returned is sufficient to contain the
error text currently available. ...
PR_GetOSError
returns the current thread's last set os-specific
error code. syntax #include <pr
error.h> print32 pr_getos
error(void) returns the value returned is a 32-bit signed number. its interpretation is left to the caller. description used for platform-specific code that requires the underlying os
error. for portability, clients should not create dependencies on the values of os-specific
error codes. however, this information is preserved, along with a platform neutral
error code, on a per thread basis. it is most useful during development. ...
nsIDOMFileError
obsolete since gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10)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. the nsidomfile
error interface describes
errors that occur while using the dom file api. it implements the dom file
error object; for details, please read that article. ...
nsIDOMGeoPositionError
the nsidomgeoposition
error interface represents an
error that occurred while performing geolocation operations. dom/interfaces/geolocation/nsidomgeoposition
error.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 attributes attribute type description code short numerical
error code; see
error constants for a complete list. read only. message domstring human readable
error message. read only. gecko 1.9.2 note the message attribute was removed in gecko 1.9.2 (firefox 3.6).
error constants constant value description permission_denied 1 the user denied permission to retrieve location data. pos...
nsIDOMGeoPositionErrorCallback
the nsidomgeoposition
errorcallback interface is used to represent an object that receives callback notifications when geolocation
errors occur. dom/interfaces/geolocation/nsidomgeoposition
errorcallback.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void handleevent(in nsidomgeoposition
error position); methods handleevent() called to handle a geolocation
error. void handleevent( in nsidomgeoposition position ); parameters position the
error that occurred, as an nsidomgeoposition
error object. ...
AbstractWorker.onerror - Web APIs
the abstractworker.on
error property of the abstractworker interface represents an eventhandler, that is a function to be called when the
error event occurs and bubbles through the worker. syntax myworker.on
error = function() { ... }; example the following code snippet shows creation of a worker object using the worker() constructor and setting up of an on
error handler on the resulting object: var myworker = new worker('worker.js'); myworker.on
error = function() { console.log('there is an
error with your worker!'); } specifications specification status comment html living standardthe definition of 'abstractworker.on
error' in that specification. living standard ...
AddressErrors.city - Web APIs
an object based on address
errors includes a city property when validation of the address fails for the value given for the address's city property. the returned string explains the
error and should offer suggestions for how to correct it. syntax var city
error = address
errors.city; value if the value specified in the paymentaddress object's city property could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. if the city value was validated successfully, this property is not included in the address
errors object. specifications specification status comment payment request apithe definition of 'address
errors.city' in that specification. candidate recommendat...
AddressErrors.phone - Web APIs
an object based on address
errors includes a phone property when the address's phone property couldn't be validated. the returned string explains the
error and should offer suggestions for how to correct it. syntax var phone
error = address
errors.phone; value if the value specified in the paymentaddress object's phone property could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. if the phone value was validated successfully, this property is not included in the address
errors object. specifications specification status comment payment request apithe definition of 'address
errors.phone' in that specification. candidate recommendation initial definition. ...
AddressErrors.postalCode - Web APIs
an object based on address
errors includes a postalcode property when the address's postalcode property couldn't be validated. the returned string explains the
error and should offer suggestions for how to correct it. syntax var postcode
error = address
errors.postcode; value if the value specified in the paymentaddress object's postalcode property could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. if the postalcode value was validated successfully, this property is not included in the address
errors object. specifications specification status comment payment request apithe definition of 'address
errors.postalcode' in that specification. candidate recomme...
AddressErrors.recipient - Web APIs
an object based on address
errors includes a recipient property when the address's recipient property couldn't be validated. the returned string explains the
error and should offer suggestions for how to correct it. syntax var recipient
error = address
errors.recipient; value if the value specified in the paymentaddress object's recipient property could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. if the recipient value was validated successfully, this property is not included in the address
errors object. specifications specification status comment payment request apithe definition of 'address
errors.recipient' in that specification. candidate recommenda...
AddressErrors.region - Web APIs
an object based on address
errors includes a region property when the address's region property couldn't be validated. the returned string explains the
error and should offer suggestions for how to correct it. syntax var region
error = address
errors.region; value if the value specified in the paymentaddress object's region property could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. if the region value was validated successfully, this property is not included in the address
errors object. specifications specification status comment payment request apithe definition of 'address
errors.region' in that specification. candidate recommendation initial defin...
AddressErrors.sortingCode - Web APIs
an object based on address
errors includes a sortingcode property when the address's sortingcode property couldn't be validated. the returned string explains the
error and should offer suggestions for how to correct it. syntax var sortingcode
error = address
errors.sortingcode; value if the value specified in the paymentaddress object's sortingcode property could not be validated, this property contains a domstring offering a human-readable explanation of the validation
error and offers suggestions for correcting it. if the sortingcode value was validated successfully, this property is not included in the address
errors object. specifications specification status comment payment request apithe definition of 'address
errors.sortingcode' in that specification. candid...
AudioWorkletNode.onprocessorerror - Web APIs
the onprocessor
error property of the audioworkletnode interface defines an event handler function to be called when the processor
error 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.onprocessor
error = function() { ... }; examples // fill in example snippet specifications specification status comment web audio apithe definition of 'onprocessor
error' in that specification. working draft ...
BroadcastChannel.onmessageerror - Web APIs
the onmessage
error event handler of the broadcastchannel interface is an eventlistener, called whenever an messageevent of type message
error is fired on the broadcastchannel instance — that is, when it receives a message that cannot be deserialized. note: this feature is available in web workers. syntax bc.onmessage
error = function() { ... }; specifications specification status comment html living standardthe definition of 'onmessage
error' in that specification. living standard ...
DedicatedWorkerGlobalScope.onmessageerror - Web APIs
the onmessage
error event handler of the dedicatedworkerglobalscope interface is an eventlistener, called whenever an messageevent of type message
error is fired on the worker—that is, when it receives a message that cannot be deserialized. note: this feature is available in web workers. syntax onmessage
error = function() { ... }; specifications specification status comment html living standardthe definition of 'onmessage
error' in that specification. living standard ...
EventSource: error event - Web APIs
the
error event of the eventsource api is fired when a connection with an event source fails to be opened. bubbles no cancelable no interface event or
errorevent event handler property eventsource.on
error examples var evtsource = new eventsource('sse.php'); // addeventlistener version evtsource.addeventlistener('
error', (e) => { console.log("an
error occurred while attempting to connect."); }); // on
error version evtsource.on
error = (e) => { console.log("an
error occurred while attempting to connect."); }; specifications specification status html living standardthe definition of '
error event' in that specification. living standard ...
EventSource.onerror - Web APIs
the on
error property of the eventsource interface is an eventhandler called when an
error occurs and the
error event is dispatched on an eventsource object. syntax eventsource.on
error = function examples evtsource.on
error = function() { console.log("eventsource failed."); }; note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'on
error' in that specification. living standard 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 dom
error containing the relevant
error. in chrome 48+/firefox 58+ this property returns a domexception because dom
error has been removed from the dom standard. specifications specification status comment file apithe definition of 'filereader:
error' in that specification. working draft initial definition ...
onerror - Web APIs
the filereader on
error handler receives an event object, not an
error object, as a parameter, but an
error can be accessed from the filereader object, as instanceoffilereader.
error // callback from a <input type="file" onchange="onchange(event)"> function onchange(event) { var file = event.target.files[0]; var reader = new filereader(); reader.on
error = function(event) { alert("failed to read file!\n\n" + reader.
error); reader.abort(); // (...does this do anything useful in an on
error handler?) }; reader.readastext(file); } ...
GeolocationPositionError.message - Web APIs
the geolocationposition
error.message read-only property returns a human-readable domstring describing the details of the
error. syntax let msg = geolocationposition
errorinstance.message value a human-readable domstring describing the details of the
error. specifications specification status comment geolocation apithe definition of 'geolocationposition
error.message' in that specification. recommendation initial definition ...
HTMLMediaElement.onerror - Web APIs
the on
error property of the htmlmediaelement interface is the eventhandler for processing
error events. the
error event fires when some form of
error occurs while attempting to load or perform the media. syntax htmlmediaelement.on
error = eventlistener; value a function which serves as the event handler for the
error event. when an
error occurs, the specified function will be called. if null, no
error handler is in effect. specifications specification status comment html living standardthe definition of 'on
error' in that specification. living standard ...
FileHandle.onerror - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. summary specifies an event listener to receive
error events. these events occur when something goes wrong. syntax instanceoffilehandle.on
error = funcref; where funcref is a function to be called when the
error event occurs. specifications specification status comment filesystem api editor's draft draft proposal. ...
LockedFile.onerror - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. summary specifies an event listener to receive
error events. these events occur when something goes wrong. syntax instanceoflockedfile.on
error = funcref; where funcref is a function to be called when the
error event occurs. specifications specification status comment filesystem api editor's draft draft proposal. ...
MediaRecorderErrorEvent - Web APIs
the mediarecorder
errorevent interface represents
errors returned by the mediastream recording api. it is an event object that encapsulates a reference to a domexception describing the
error that occurred. properties inherits properties from its parent interface, event.
error read only a domexception containing information about the
error that occurred. read only. constructor mediastreamrecorderevent() creates and returns a new mediarecorder
errorevent event object with the given parameters. methods inherits methods from its parent interface, event. specifications specification status comment mediastream recordingthe definition of 'mediarecorder
errorevent' in that specification. working draft initial definition. ...
MessagePort.onmessageerror - Web APIs
the onmessage
error event handler of the messageport interface is an eventlistener, called whenever an messageevent of type message
error is fired on the port—that is, when it receives a message that cannot be deserialized. note: this feature is available in web workers. syntax port.onmessage
error = function() { ... }; specifications specification status comment html living standardthe definition of 'onmessage
error' in that specification. living standard ...
NDEFReader.onerror - Web APIs
the on
error property of ndefreader interface of the web nfc api is called whenever an
error occurs during reading of nfc tags, e.g. when tags leave the reader's magnetic induction field. specifications specification status comment web nfc, ndefreader.on
error draft initial definition. ...
Notification.onerror - Web APIs
note: this feature is available in web workers. the on
error property of the notification interface specifies an event listener to receive
error events. these events occur when something goes wrong with a notification (in many cases an
error preventing the notification from being displayed.) syntax notification.on
error = function() { ... }; specifications specification status comment notifications apithe definition of 'on
error' in that specification. living standard initial specification. ...
OverconstrainedError.constraint - Web APIs
the constraint read-only property of the overconstrained
error interface returns the constraint that was supplied in the constructor, meaning the contraint that was not satisfied. syntax var constraint = overconstrained
error.constraint; value a string specifications specification status comment media capture and streamsthe definition of 'constraint' in that specification. candidate recommendation initial definition. ...
OverconstrainedError.message - Web APIs
the message read-only property of the overconstrained
error interface returns the text supplied in the constructor. syntax var message = overconstrained
error.message; value a domstring. specifications specification status comment media capture and streamsthe definition of 'message' in that specification. candidate recommendation initial definition. ...
OverconstrainedError.name - Web APIs
the name read-only property of the overconstrained
error interface will always return 'overconstrained
error'. syntax var name = overconstrained
error.name; value a domstring. specifications specification status comment media capture and streamsthe definition of 'name' in that specification. candidate recommendation initial definition. ...
RTCPeerConnection: idpassertionerror event - Web APIs
an idpassertion
error event informs the target, a rtcpeerconnection object, that the identity provider (idp) encountered an
error when trying to generate an identity assertion. an event handler for this event can be added using the rtcpeerconnection.onidpassertion
error property. bubbles no cancelable no interface rtcidentity
errorevent event handler property onidpassertion
error warning: this event is no longer used; instead, you can detect an assertion
error by detecting when the promise returned by rtcpeerconnection.peeridentity is rejected. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'idpassertion
error' in that specification. candidate r...
Response.error() - Web APIs
the
error() method of the response interface returns a new response object associated with a network
error. note: this is mainly relevant to serviceworkers; the
error method is used to return an
error if you so wish it. an
error response has its type set to
error. note: an "
error" response never really gets exposed to script: such a response to a fetch() would reject the promise. syntax var
errorresponse = response.
error(); parameters none. return value a response object. example tbd (does not yet appear to be supported anywhere). specifications specification status comment fetchthe definition of '
error()' in that specification. living standard ...
SVGElement: error event - Web APIs
the
error event is fired when an svg element does not load properly or when an
error occurs during script execution. this basically implements the standard
error dom event. bubbles yes cancelable no interface svgevent event handler property on
error examples svgelem.addeventlistener('
error', () => { console.log('svg not loaded properly.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of '
error' in that specification. candidate recommendation initial definition ...
SensorErrorEvent - Web APIs
the sensor
errorevent interface of the sensor apis provides information about
errors thrown by a sensor or related interface. constructor sensor
errorevent.sensor
errorevent() creates a new sensor
errorevent object. properties sensor
errorevent.
error read only returns the domexception object passed in the event's contructor. specifications specification status comment generic sensor apithe definition of 'sensor
errorevent' in that specification. candidate recommendation initial definition. ...
SpeechRecognition.onerror - Web APIs
the on
error property of the speechrecognition interface represents an event handler that will run when a speech recognition
error occurs (when the
error event fires.) syntax myspeechrecognition.on
error = function() { ... }; examples var recognition = new speechrecognition(); recognition.on
error = function(event) { console.log('speech recognition
error detected: ' + event.
error); } specifications specification status comment web speech apithe definition of 'on
error' in that specification. draft ...
SpeechRecognitionErrorEvent.message - Web APIs
the message read-only property of the speechrecognition
errorevent interface returns a message describing the
error in more detail. syntax var my
errormsg = event.message; value a domstring containing more details about the
error that was raised. note that the spec does not define the exact wording of these messages — this is up to the implementors to decide upon. examples var recognition = new speechrecognition(); recognition.on
error = function(event) { console.log('speech recognition
error detected: ' + event.
error); console.log('additional information: ' + event.message); } specifications specification status comment web speech apithe definition of 'message' in that specification. draft ...
SpeechRecognitionErrorEvent - Web APIs
the speechrecognition
errorevent interface of the web speech api represents
error messages from the recognition service. properties speechrecognition
errorevent also inherits properties from its parent interface, event. speechrecognition
errorevent.
error read only returns the type of
error raised. speechrecognition
errorevent.message read only returns a message describing the
error in more detail. examples var recognition = new speechrecognition(); recognition.on
error = function(event) { console.log('speech recognition
error detected: ' + event.
error); console.log('additional information: ' + event.message); } specifications specification status comment web speech apithe definition of 'speechrecognition
errorevent' in that specification. draft ...
WebSocket: error event - Web APIs
the
error event is fired when a connection with a websocket has been closed due to an
error (some data couldn't be sent for example). bubbles no cancelable no interface event event handler property on
error examples // create websocket connection const socket = new websocket('ws://localhost:8080'); // listen for possible
errors socket.addeventlistener('
error', function (event) { console.log('websocket
error: ', event); }); specifications specification status html living standardthe definition of 'websocket
error' in that specification. living standard ...
WebSocket.onerror - Web APIs
the websocket interface's on
error event handler property is a function which gets called when an
error occurs on the websocket. you can also add an
error event handler using addeventlistener(). syntax websocket.on
error = eventhandler; value a function or eventhandler which is executed whenever an
error event occurs on the websocket connection. example websocket.on
error = function(event) { console.
error("websocket
error observed:", event); }; specifications specification status comment html living standardthe definition of 'websocket: on
error' in that specification. living standard initial definition ...
WindowEventHandlers.onmessageerror - Web APIs
the onmessage
error event handler of the windoweventhandlers interface is an eventlistener, called whenever an messageevent of type message
error is fired on a window—that is, when it receives a message that cannot be deserialized. note: this feature is available in web workers. syntax window.onmessage
error = function() { ... }; specifications specification status comment html living standardthe definition of 'onmessage
error' in that specification. living standard ...
Worker.onmessageerror - Web APIs
the onmessage
error event handler of the worker interface is an eventlistener, called whenever an messageevent of type message
error is fired on the worker instance — that is, when it receives a message that cannot be deserialized. note: this feature is available in web workers. syntax worker.onmessage
error = function() { ... }; specifications specification status comment html living standardthe definition of 'onmessage
error' in that specification. living standard ...
WorkerGlobalScope.onerror - Web APIs
the on
error property of the workerglobalscope interface represents an eventhandler to be called when the
error event occurs and bubbles through the worker. syntax self.on
error = function() { ... }; example the following code snippet shows an on
error handler set inside a worker: self.on
error = function() { console.log('there is an
error inside your worker!'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.on
error' in that specification. living standard ...
XDomainRequest.onerror - Web APIs
an event handler which is called when an xdomainrequest encounters an
error. note: there is no way to determine the cause of the
error from the xdomainrequest interface. syntax xdr.on
error = funcref; parameters funcref a function to call when an
error occurs. example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.on
error = function(){ //handle
error } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1¶m2=value2"); specification not part of any specification. ...
RangeError: radix must be an integer - JavaScript
the javascript exception "radix must be an integer at least 2 and no greater than 36" occurs when the optional radix parameter of the number.prototype.tostring() or the bigint.prototype.tostring() method was specified and is not between 2 and 36. message range
error: invalid argument (edge) range
error: radix must be an integer at least 2 and no greater than 36 (firefox) range
error: tostring() radix argument must be between 2 and 36 (chrome)
error type range
error what went wrong? the optional radix parameter of the number.prototype.tostring() or the bigint.prototype.tostring() method was specified. its value must be an integer (a number) between 2 and 36, specifying the base of the number system to be used for representing numeric values. for example, the decimal (base 10) number 169 is r...
TypeError: X.prototype.y called on incompatible type - JavaScript
the javascript exception "called on incompatible target (or object)" occurs when a function (on a given object), is called with a this not corresponding to the type expected by the function. message type
error: 'this' is not a set object (edge) type
error: function.prototype.tostring called on incompatible object (firefox) type
error: function.prototype.bind called on incompatible target (firefox) type
error: method set.prototype.add called on incompatible receiver undefined (chrome) type
error: bind must be called on a function (chrome)
error type type
error what went wrong? when this
error is thrown, a function (on a given object), is called with a this not corresponding to the type expected by the function. this issue can arise when using the function.prototype.call() or function.prototyp...
TypeError: can't access dead object - JavaScript
the javascript exception "can't access dead object" occurs when firefox disallows add-ons to keep strong references to dom objects after their parent document has been destroyed to improve in memory usage and to prevent memory leaks. message type
error: can't access dead object
error type type
error 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. to avoid these issues, references to dom nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unlo...
ReferenceError: invalid assignment left-hand side - JavaScript
the javascript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. for example, a single "=" sign was used instead of "==" or "===". message reference
error: invalid assignment left-hand side
error type reference
error. what went wrong? there was an unexpected assignment somewhere. this might be due to a mismatch of a assignment operator and a comparison operator, for example. while a single "=" sign assigns a value to a variable, the "==" or "===" operators compare a value. examples typical invalid assignments if (math.pi = 3 || math.pi = 4) { console.log('no way!'); } // reference
error: invalid assignment left-hand side var str = 'hello, ' += 'is it me ' += 'you\'re looking for?'; // reference
error: invalid assignment left-hand s...
RangeError: invalid date - JavaScript
the javascript exception "invalid date" occurs when a string leading to an invalid date has been provided to date or date.parse(). message range
error: invalid date (edge) range
error: invalid date (firefox) range
error: invalid time value (chrome) range
error: provided date is not in valid range (chrome)
error type range
error what went wrong? a string leading to an invalid date has been provided to date or date.parse(). examples invalid cases unrecognizable strings or dates containing illegal element values in iso formatted strings usually return nan. however, depending on the implementation, non–conforming iso format strings, may also throw range
error: invalid date, like the following cases in firefox: new date('foo-bar 2014'); new date('2014-25-23').toisostring(); new date('foo-bar...
RangeError: repeat count must be non-negative - JavaScript
the javascript exception "repeat count must be non-negative" occurs when the string.prototype.repeat() method is used with a count argument that is a negative number. message range
error: argument out of range range
error: repeat count must be non-negative (firefox) range
error: invalid count value (chrome)
error type range
error what went wrong? the string.prototype.repeat() method has been used. it has a count parameter indicating the number of times to repeat the string. it must be between 0 and less than positive infinity and cannot be a negative number. the range of allowed values can be described like this: [0, +∞). examples invalid cases 'abc'.repeat(-1); // range
error valid cases 'abc'.repeat(0); // '' 'abc'.repeat(1); // 'abc' 'abc'.repeat(2); // 'abcabc' 'abc'.rep...
Error: Permission denied to access property "x" - JavaScript
the javascript exception "permission denied to access property" occurs when there was an attempt to access an object for which you have no permission. message
error: permission denied to access property "x"
error type
error. what went wrong? there was attempt to access an object for which you have no permission. this is likely an <iframe> element loaded from a different domain for which you violated the same-origin policy. examples no permission to access document <!doctype html> <html> <head> <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe> <script> onload = function() { console.log(frames[0].document); //
error: permission denied to access property "document" } </script> </head> <body></body> </html> ...
TypeError: Reduce of empty array with no initial value - JavaScript
the javascript exception "reduce of empty array with no initial value" occurs when a reduce function is used. message type
error: reduce of empty array with no initial value
error type type
error what went wrong? in javascript, there are several reduce functions: array.prototype.reduce(), array.prototype.reduceright() and typedarray.prototype.reduce(), typedarray.prototype.reduceright()). these functions optionally take an initialvalue (which will be used as the first argument to the first call of the callback). however, if no initial value is provided, it will use the first element of the array or typedarray as the initial value. this
error is raised when an empty array is provided because no initial value can be returned in that case. examples invalid cases this problem appear...
TypeError: invalid arguments - JavaScript
the javascript exception "invalid arguments" occurs when typed array constructors are provided with a wrong argument. message type
error: invalid arguments (firefox)
error type type
error what went wrong? typed array constructors require either a length, another typed array, array-like objects, iterable objects or an arraybuffer object to create a new typed array. other constructor arguments will not create a valid typed array. examples no strings in typed arrays typed arrays, for example a uint8array, can't be constructed from a string. in fact, strings can't be in typed arrays at all. var ta = new uint8array("nope"); // type
error: invalid arguments different ways to create a valid uint8array: // from a length var uint8 = new uint8array(2); uint8[0] = 42; console.log(uint8...
ReferenceError: reference to undefined property "x" - JavaScript
the javascript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist. message reference
error: reference to undefined property "x" (firefox)
error type (firefox only) reference
error warning which is reported only if javascript.options.strict preference is set to true. what went wrong? the script attempted to access an object property which doesn't exist. there are two ways to access properties; see the property accessors reference page to learn more about them. examples invalid cases in this case, the property bar is an undefined property, so a reference
error will occur. var foo = {}; foo.bar; // reference
error: reference to undefined property "bar" valid cases to avoid the
error, you need to either add a definiti...
TypeError: variable "x" redeclares argument - JavaScript
the javascript strict mode-only exception "variable redeclares argument" occurs when the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again. message type
error: variable "x" redeclares argument (firefox)
error type type
error 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. 'use strict'; function f(arg) { var arg = 'foo'; } valid...
Error.prototype.columnNumber - JavaScript
the columnnumber property contains the column number in the line of the file that raised this
error. examples using columnnumber var e = new
error('could not parse input'); throw e; console.log(e.columnnumber) // 0 specifications not part of any standard. ...
Error.prototype.fileName - JavaScript
the filename property contains the path to the file that raised this
error. description this non-standard property contains the path to the file that raised this
error. if called from a debugger context, the firefox developer tools for example, "debugger eval code" is returned. examples using filename var e = new
error('could not parse input'); throw e; // e.filename could look like "file:///c:/example.html" specifications not part of any standard. ...
Error.prototype.lineNumber - JavaScript
the linenumber property contains the line number in the file that raised this
error. examples using linenumber var e = new
error('could not parse input'); throw e; console.log(e.linenumber) // 2 alternative example using
error event window.addeventlistener('
error', function(e) { console.log(e.linenumber); // 5 }); var e = new
error('could not parse input'); throw e; this is not a standard feature and lacks widespread support. see the browser compatability table below. specifications not part of any standard. ...
Error.prototype.name - JavaScript
the name property represents a name for the type of
error. the initial value is "
error". description by default,
error instances are given the name "
error". the name property, in addition to the message property, is used by the
error.prototype.tostring() method to create a string representation of the
error. examples throwing a custom
error var e = new
error('malformed input'); // e.name is '
error' e.name = 'parse
error'; throw e; // e.tostring() would return 'parse
error: malformed input' specifications specification ecmascript (ecma-262)the definition of '
error.prototype.name' in that specification. ...
InternalError() constructor - JavaScript
the internal
error() constructor creates an
error that indicates an
error that occurred internally in the javascript engine. for example: "internal
error: too much recursion". syntax new internal
error([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 internal
error new internal
error("engine failure"); specifications not part of any standard. ...
Index - Web APIs
22 abstractworker api, abstract, abstractworker, interface, reference, sharedworker, web workers, web workers api, worker the abstractworker interface of the web workers api is an abstract interface that defines properties and methods that are common to all types of worker, including not only the basic worker, but also serviceworker and sharedworker. 23 abstractworker.on
error api, abstractworker, eventhandler, property, reference, web workers, workers, on
error the abstractworker.on
error property of the abstractworker interface represents an eventhandler, that is a function to be called when the
error event occurs and bubbles through the worker. 24 accelerometer api, accelerometer, accelerometer api, generic sensor api, interface, reference, se...
...teger containing the acceleration of the device along the its y axis. 28 accelerometer.z api, accelerometer, accelerometer api, generic sensor api, property, reference, sensor, sensor apis, sensors, z the z read-only property of the accelerometer interface returns a double precision integer containing the acceleration of the device along the its z axis. ...
...n of the device along the its y axis. 28 accelerometer.z api, accelerometer, accelerometer api, generic sensor api, property, reference, sensor, sensor apis, sensors, z the z read-only property of the accelerometer interface returns a double precision integer containing the acceleration of the device along the its z axis. ...
...And 209 more matches
sslerr.html
this page is part of the ssl reference that we are migrating into the format described in the mdn style guide. if you are inclined to help with this migration, your help would be very much appreciated. upgraded documentation may be found in the current nss reference nss and ssl
error codes chapter 8 nss and ssl
error codes nss
error codes are retrieved using the nspr function pr_get
error. in addition to the
error codes defined by nspr, pr_get
error retrieves the
error codes described in this chapter. ssl
error codes sec
error codes ssl
error codes table 8.1
error codes defined in sslerr.h constant value description ssl_
error_export_only_server -12288 "unable to communicate securely. peer does not support high-grade encryption." ...
...fined in sslerr.h constant value description ssl_
error_export_only_server -12288 "unable to communicate securely. peer does not support high-grade encryption." the local system was configured to support the cipher suites permitted for domestic use. the remote system was configured to support only the cipher suites permitted for export use. ssl_
error_us_only_server -12287 "unable to communicate securely. peer requires high-grade encryption which is not supported." the remote system was configured to support the cipher suites permitted for domestic use. the local system was configured to support only the cipher suites permitted for export use. ...
... the cipher suites permitted for export use. ssl_
error_us_only_server -12287 "unable to communicate securely. peer requires high-grade encryption which is not supported." the remote system was configured to support the cipher suites permitted for domestic use. the local system was configured to support only the cipher suites permitted for export use. ssl_
error_no_cypher_overlap -12286 "cannot communicate securely with peer: no common encryption algorithm(s)." the local and remote systems share no cipher suites in common. this can be due to a misconfiguration at either end. ...
...And 145 more matches
HTTP Index - HTTP
sharing (cors) ajax, cors, cross-origin resource sharing, fetch, fetch api, http, http access controls, same-origin policy, security, xmlhttprequest, l10n:priority cross-origin resource sharing (cors) is a mechanism that uses additional http headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. 21 cors
errors cors,
errors, http, https, messages, same-origin, security, console, troubleshooting cross-origin resource sharing (cors) is a standard that allows a server to relax the same-origin policy. this is used to explicitly allow some cross-origin requests while rejecting others. 22 reason: cors disabled authentication, authentication article, cors, cross-origin, disabled, erro...
...rce, same origin, same-origin, security, sharing, validation, secure, troubleshooting a request that needs to use cors was attempted, but cors is disabled in the user's browser. when this happens, the user needs to turn cors back on in their browser. ...
...match 'xyz' cors, corsalloworiginnotmatchingorigin, cross-origin,
error, http, https, messages, reasons, security, console, troubleshooting simply put, the origin making the request does not match any of the origins permitted by the access-control-allow-origin header. 24 reason: cors header 'access-control-allow-origin' missing cors, corsmissingalloworigin, cross-origin,
error, http, https, messages, reasons, security, console, troubleshooting the response to the cors request is missing the required access-control-allow-origin header, which is used to determine whether or not the resource can be accessed by content operating within the current origin. 25 reason: cors header ‘origin’ cannot be added cors, corsoriginheadernotadded, cross-origin, ...
...And 58 more matches
Client-side form validation - Learn web development
lidation done in the browser is called client-side validation, while validation done on the server is called server-side validation. in this chapter we are focusing on client-side validation. if the information is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn't correctly formatted, it gives the user an
error message explaining what needs to be corrected, and lets them try again. we want to make filling out web forms as easy as possible. so why do we insist on validating our forms? there are three main reasons: we want to get the right data, in the right format. our applications won't work properly if our users' data is stored in the wrong format, is incorrect, or is omitted altogether. we want t...
...s, which lets you apply a specific style to valid elements. if the user tries to send the data, the browser will submit the form, provided there is nothing else stopping it from doing so (e.g., javascript). when an element is invalid, the following things are true: the element matches the :invalid css pseudo-class, and sometimes other ui pseudo-classes (e.g., :out-of-range) depending on the
error, which lets you apply a specific style to invalid elements. if the user tries to send the data, the browser will block the form and display an
error message. note: there are several
errors that will prevent the form from being submitted, including a badinput, patternmismatch, rangeoverflow or rangeunderflow, stepmismatch, toolong or tooshort, typemismatch, valuemissing, or a custom
error. bu...
... input:valid { border: 2px solid black; } to begin, make a copy of fruit-start.html in a new directory on your hard drive. the required attribute the simplest html5 validation feature is the required attribute. to make an input mandatory, add this attribute to the element. when this attribute is set, the element matches the :required ui pseudo-class and the form won't submit, displaying an
error message on submission when the input is empty. while empty, the input will also be considered invalid, matching the :invalid ui pseudo-class. add a required attribute to your input, as shown below. <form> <label for="choose">would you prefer a banana or cherry? (required)</label> <input id="choose" name="i_like" required> <button>submit</button> </form> note the css that is included in t...
...And 43 more matches
WebIDL bindings
t refcounted then the return value of functions that return it should return an nsautoptr. c++ reflections of webidl constructs c++ reflections of webidl operations (methods) a webidl operation is turned into a method call on the underlying c++ object. the return type and argument types are determined as described below. in addition to those, all methods that are allowed to throw will get an
errorresult& argument appended to their argument list. non-static methods that use certain webidl types like any or object will get a jscontext* argument prepended to the argument list. static methods will be passed a const globalobject& for the relevant global and can get a jscontext* by calling context() on it. the name of the c++ method is simply the name of the webidl operation with the first lett...
...r(any something); void doyetanotherthing(optional boolean actuallydoit = false); static void staticoperation(any arg); }; will require these method declarations: class myclass { void dosomething(int32_t anumber); double dosomething(myclass* aotherinstance); already_addrefed<myinterface> dosomethingelse(optional<int32_t> amaybenumber,
errorresult& rv); void dosomethingelse(myclass& aotherinstance,
errorresult& rv); void dotheother(jscontext* cx, js::value asomething); void doyetanotherthing(bool aactuallydoit); static void staticoperation(const globalobject& aglobal, js::value asomething); } c++ reflections of webidl attributes a webidl attribute is turned into a pair of method calls for the getter and setter on the un...
...ance of myinterface. constructors are always allowed to throw. ...
...And 40 more matches
sslfnc.html
cstatus nss_init(char *configdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_get
error to retrieve the
error code. description nss_init opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) in the specified directory. nss_init isnot idempotent, so call it only once. nss_init opens the database files read-only. if you are performing operations that require write permission, for example s/mime operations such as adding a certificate, use nss_initreadw...
...ss_initreadwrite(char *configdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_get
error to retrieve the
error code. description nss_initreadwrite opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) with both read and write permission in the specified directory. nss_initreadwrite isnot idempotent, so call it only once. use nss_initreadwrite rather than nss_init if you are performing operations that require write permission, such as some s/mime operat...
...ssl, which requires that the certificate and key database files be opened. syntax #include "nss.h" secstatus nss_nodb_init(char *reserved); parameter this function has the following parameter: reserved should be null.. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_get
error to retrieve the
error code. description nss_nodb_init opens only the temporary database and the internal pkcs #112 module. unlike nss_init, nss_nodb_init allows applications that do not have access to storage for databases to run raw crypto, hashing, and certificate functions. nss_nodb_init isnot idempotent, so call it only once. before calling nss_nodb_init, your program must call pr...
...And 39 more matches
Using IndexedDB - Web APIs
base we start the whole process like this: // let us open our database var request = window.indexeddb.open("mytestdatabase", 3); see that? opening a database is just like any other operation — you have to "request" it. the open request doesn't open the database or start the transaction right away. the call to the open() function returns an idbopendbrequest object with a result (success) or
error value that you handle as an event. most other asynchronous functions in indexeddb do the same thing - return an idbrequest object with the result or
error. the result for the open function is an instance of an idbdatabase. the second parameter to the open method is the version of the database. the version of the database determines the database schema — the object stores in the database and th...
...ll be converted to the closest lower integer and the transaction may not start, nor the upgradeneeded event trigger. so for example, don't use 2.4 as a version number: var request = indexeddb.open("mytestdatabase", 2.4); // don't do this, as the version will be rounded to 2 generating handlers the first thing you'll want to do with almost all of the requests you generate is to add success and
error handlers: request.on
error = function(event) { // do something with request.
errorcode! }; request.onsuccess = function(event) { // do something with request.result! }; which of the two functions, onsuccess() or on
error(), gets called? if everything succeeds, a success event (that is, a dom event whose type property is set to "success") is fired with request as its target. once it is fired, t...
... { // do something with request.result! }; which of the two functions, onsuccess() or on
error(), gets called? if everything succeeds, a success event (that is, a dom event whose type property is set to "success") is fired with request as its target. once it is fired, the onsuccess() function on request is triggered with the success event as its argument. otherwise, if there was any problem, an
error event (that is, a dom event whose type property is set to "
error") is fired at request. this triggers the on
error() function with the
error event as its argument. the indexeddb api is designed to minimize the need for
error handling, so you're not likely to see many
error events (at least, not once you're used to the api!). in the case of opening a database, however, there are some common condit...
...And 37 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
previous overview: first steps next when you built up the "guess the number" game in the previous article, you may have found that it didn't work. never fear — this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix
errors in javascript programs. prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is. ...
...e aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix
errors in javascript programs. prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is. objective: to gain the ability and confidence to start fixing problems in your own code. types of
error generally speaking, when you do something wrong in code, there are two main types of
error that you'll come across: syntax
errors: these are spelling
errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some
error messages too. these are usually okay to fix, as long as you are familiar with the right tool...
..., when you do something wrong in code, there are two main types of
error that you'll come across: syntax
errors: these are spelling
errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some
error messages too. these are usually okay to fix, as long as you are familiar with the right tools and know what the
error messages mean! logic
errors: these are
errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. these are often harder to fix than syntax
errors, as there usually isn't an
error message to direct you to the source of the
error. okay, so it's not quite that simple — there are some other diff...
...And 36 more matches
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
vailable 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. ...
...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). ...
...rt dialog to handle ssl exceptions in your firefox extension or xulrunner application. // adapted from the patch for moztcpsocket
error reporting (bug 861196). ...
...And 35 more matches
Index
n. 34 js::compileoptions jsapi reference, reference, référence(2), spidermonkey some methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow method chain. 35 js::construct jsapi reference, reference, référence(2), spidermonkey js::construct calls a specified function as a constructor, fun. 36 js::create
error jsapi reference, reference, référence(2), spidermonkey js::create
error creates an
error object with specified properties. 37 js::currentglobalornull jsapi reference, reference, référence(2), spidermonkey js::currentglobalornull() returns the global object for whatever function is currently running on the context. in other words, it returns the global object on t...
...llocation fails when calling pod_{calloc,realloc}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 c...
...kes the 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 referen...
...And 29 more matches
OS.File for the main thread
note that this snippet is useful as a demonstration of complex asynchronous programming with os.file – in most cases, function os.file.writeatomic is a better ...
...note that this snippet is useful as a demonstration of complex asynchronous programming with os.file – in most cases, function os.file.writeatomic is a better choice. let writestream = function writestream(data, outfile, chunksize) { let view = new uint8array...
...ata| return promise.then(function onsuccess(bytes) { return loop(pos + bytes); // ... and loop. }); }; let promise = loop(0); // enter the loop. promise = promise.then(function onsuccess() { // once loop is complete, finalize. ...
...And 28 more matches
Bytecode Descriptions
) the typeof operator. infallible. the result is always a string that depends on the type of val. jsop::typeof and jsop::typeofexpr are the same except that--amazingly--jsop::typeof affects the behavior of an immediately preceding jsop::getname or jsop::getgname instruction! this is how we implement typeof step 2, making typeof nonexistingvariable return "undefined" instead of throwing a reference
error. in a global scope: typeof x compiles to getgname "x"; typeof. typeof (0, x) compiles to getgname "x"; typeofexpr. emitting the same bytecode for these two expressions would be a bug. per spec, the latter throws a reference
error if x doesn't exist. format: jof_ic pos stack: val ⇒ (+val) the unary + operator. +val doesn't do any actual math. it just calls tonumber(val). the conversion can c...
... ge stack: lval, rval ⇒ (lval op rval) relative operators (<, >, <=, >=). pop two values, compare them, and push the boolean result. the comparison may perform conversions that call .tostring()/.valueof() methods and can throw. implements: relational operators: evaluation. format: jof_ic instanceof stack: value, target ⇒ (value instanceof target) the instanceof operator. this throws a type
error if target is not an object. it calls target[symbol.hasinstance](value) if the method exists. on success, the result is always a boolean value. format: jof_ic in stack: id, obj ⇒ (id in obj) the in operator. push true if obj has a property with the key id. otherwise push false. this throws a type
error if obj is not an object. this can fire proxy hooks and can throw. on success, the result is ...
...n can call .tostring()/.valueof() methods and can throw. on success, the result is always numeric. format: jof_ic pow stack: lval, rval ⇒ (lval ** rval) the exponentiation operator (**). pop two values, convert them to numeric values, do exponentiation, and push the result. the top value is the exponent. the conversion can call .tostring()/.valueof() methods and can throw. this throws a range
error if both values are bigints and the exponent is negative. format: jof_ic conversions topropertykey stack: propertynamevalue ⇒ propertykey convert a value to a property key. implements: topropertykey, except that if the result would be the string representation of some integer in the range 0..2^31, we push the corresponding int32 value instead. this is because the spec insists that array ind...
...And 27 more matches
Index
firefox 3, including a description of the steps involved in modifying an existing c++ class to participate in xpcom cycle collection. if you have a class that you think is involved in a cyclical-ownership leak, this page is for you. 14 introduction to xpcom for the dom developing mozilla warning: this document has not yet been reviewed by the dom gurus, it might contain some
errors. 15 language bindings embedding, landing, mozilla, xpcom, xpcom:language bindings an xpcom language binding is a bridge between a particular language and xpcom to provide access to xpcom objects from that language, and to let modules written in that language be used as xpcom objects by all other languages for which there are xpcom bindings. 16 components object ...
...es 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 nsixpcexception 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, xpconnect components.id is a constructor that creates native objects that conform to the nsijsid interface. 20 components.classes xpcom:language bindings, xpconnect components.classes is a read-only object whose properties are classes indexed by ...
... reflection of the global native component manager service. the scriptable methods on the nsicomponentmanager interface can be called directly on this object. 27 components.results xpcom:language bindings, xpconnect components.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at table of
errors), with the value of each corresponding to that constant's value. 28 components.returncode xpcom:language bindings, xpconnect no summary! 29 components.stack xpcom:language bindings, xpconnect components.stack is a read only property of type nsistackframe (idl definition) that represents a snapshot of the current javascript callstack. this can be used for...
...And 26 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
all.js because it is reserved. ref: bug 690370 available functions are (see prefcalls.js file for details): function getprefbranch() function pref(prefname, value) function defaultpref(prefname, value) function lockpref(prefname, value) function unlockpref(prefname) function getpref(prefname) function getldapattributes(host, base, filter, attribs) function getldapvalue(str, key) function display
error(funcname, message) function getenv(name) configure autoconfig two directives ask thunderbird to use autoconfig at startup: # cat /usr/lib/thunderbird/defaults/pref/tb-autoconf.js // 20100526 - modification autoconfig jehan. // pref("general.config.obscure_value", 0); // for mcd .cfg files pref('general.config.filename', 'thunderbird.cfg'); // for mcd .cfg files it used to be in previous ...
...pvalue(values, "cn"); var mail = getldapvalue(values, "mail"); var url = getldapvalue(values, "labeleduri"); // those ldap variables are only available in this processldapvalues context! // so we set the preferences that need them here. lockpref("mail.identity.id1.useremail", mail); lockpref("mail.server.server2.name", mail); lockpref("mail.identity.id1.fullname", cn); //debug with popup
error messages doesn't work anymore :-( !! var env_mozdebug= getenv("mozilla_debug"); if (env_mozdebug) {display
error("no
error, just a debug, cn =" + cn + " and mail = " + mail); } } } // 4) call ldap servers to get ldap attributes (mail & cn), this will finally call processldapvalues, "3)" just above. getldapattributes("ldap2.int-evry.fr","ou=people,dc=int-evry,dc=fr","uid=" + env_user,"uid,c...
...here's my own version. //note: for accessing the active directory of windows server later than 2000 //it is necessary to allow anonymous read access. ...
...And 24 more matches
Examples
how to throw reject if you have a function that is a promise, and want to end it and throw a reject, you can throw an
error. components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); let promise = os.file.exists(path); let newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directory."); } else { throw new
error("you don't have file.txt in your temporary directory."); } }); // unexpected
errors should always be reported at the end of a promise chain. let lastpromise = newpromise.then(function onfulfill(){ }) .catch(function onreject(arejectreason) { console.warn('newpromise failed with reason: ', arejectreason); }); using a prom...
...when the callback finishes execution, newpromise will be fulfilled with an undefined fulfillment value, because the callback does not return any value. when newpromise is fulfilled,...
...s.file.exists(path); let newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directory."); } else { console.log("you don't have file.txt in your temporary directory."); } }); // unexpected
errors should always be reported at the end of a promise chain. let lastpromise = newpromise.then(null, components.utils.report
error); in this case, if the file existence check succeeds, the onfulfill callback is invoked. when the callback finishes execution, newpromise will be fulfilled with an undefined fulfillment value, because the callback does not return any value. when newpromise is fulfilled, nothing happens, because no fulfillment callback is specified and the return value of the last then method is ignored. if the...
...And 24 more matches
NSS_3.12_release_notes.html
kcs11t.h for details): ckk: keys ckk_camellia ckm: mechanisms ckm_sha224_rsa_pkcs ckm_sha224_rsa_pkcs_pss ckm_sha224 ckm_sha224_hmac ckm_sha224_hmac_general ckm_sha224_key_derivation ckm_camellia_key_gen ckm_camellia_ecb ckm_camellia_cbc ckm_camellia_mac ckm_camellia_mac_general ckm_camellia_cbc_pad ckm_camellia_ecb_encrypt_data ckm_camellia_cbc_encrypt_data ckg: mfgs ckg_mgf1_sha224 new
error codes (see secerr.h): sec_
error_not_initialized sec_
error_token_not_logged_in sec_
error_ocsp_responder_cert_invalid sec_
error_ocsp_bad_signature sec_
error_out_of_search_limits sec_
error_invalid_policy_mapping sec_
error_policy_validation_failed sec_
error_unknown_aia_location_type sec_
error_bad_http_response sec_
error_bad_ldap_response sec_
error_failed_to_encode_data sec_
error_bad_info_access_loca...
...ee secerr.h): sec_
error_not_initialized sec_
error_token_not_logged_in sec_
error_ocsp_responder_cert_invalid sec_
error_ocsp_bad_signature sec_
error_out_of_search_limits sec_
error_invalid_policy_mapping sec_
error_policy_validation_failed sec_
error_unknown_aia_location_type sec_
error_bad_http_response sec_
error_bad_ldap_response sec_
error_failed_to_encode_data sec_
error_bad_info_access_location sec_
error_libpkix_internal new mechanism flags (see secmod.h) public_mech_aes_flag public_mech_sha256_flag public_mech_sha512_flag public_mech_camellia_flag new oids (see secoidt.h) new ec signature oids sec_oid_ansix962_ecdsa_signature_recommended_digest sec_oid_ansix962_ecdsa_signature_specified_digest sec_oid_ansix962_ecdsa_sha224_signature sec_oid_ansix962_ecdsa_sha256_signature sec_oid_ansix962...
...sa_signature changed oids (see secoidt.h) sec_oid_pkcs12_key_usage changed to sec_oid_bogus_key_usage sec_oid_ansix962_ecdsa_signature_with_sha1_digest changed to sec_oid_ansix962_ecdsa_sha1_signature note: sec_oid_ansix962_ecdsa_signature_with_sha1_digest is also kept for compatibility reasons. ...
...And 22 more matches
Using Promises - JavaScript
ned promises before explaining how to create them. essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. ...
... function, createaudiofileasync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an
error occurs. ...
...diofileasync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an
error occurs. ...
...And 21 more matches
Install script template - Archive of obsolete content
suffix = "my"; var suffix_description = "my plugin files"; var company_name = "mypluginco"; var plugin_description = "my exemplary plugin mine all mine"; // registry constant paths // these will be used when the win32 registry keys are written var hkey_local_machine = "hkey_local_machine"; var hkey_current_user = "hkey_current_user"; var reg_moz_path = "software\\mozillaplugins"; // my own
error code in case secondary installation fails var nosecondaryinstall = 1; //
error return codes 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 value...
...emory 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 exceptionoccured
error = -4711; var winregisnull
error = -4712; var invalidrootkey
error = -4713; var registrykeynotwritable
error = -4714; //initinstall block //the installation is initialized here -- if we fail here, cancel the installation // initinstall is quite an overloaded method, but i have invoked it here with three strings // which are globally defined err = initinstall(software_name,...
...); if (err != 0) { // call initinstall again in case illegal characters in plid err = initinstall(software_name, software_name, version); if (err != 0) cancelinstall(err); } //addfiles to current browser block var pluginsfolder = getfolder("plugins"); //verify disk space if(verifydiskspace(pluginsfolder, plugin_size+component_size)) { // start installing plugin shared library reset
error(); // install the plugin shared library to the current browser's plugin directory errblock1 = addfile (plid, version, plugin_file, pluginsfolder, null); if (errblock1!=0) { logcomment("could not add " + plugin_file + " to " + pluginsfolder + ":" + errblock1); cancelinstall(errblock1); } // start installing xpt file if this is a scriptable plugin // install to the plugins directory...
...And 20 more matches
Graceful asynchronous programming with Promises - Learn web development
ed, sets up a video element to show the stream coming from the camera as a "self view," then takes each of the stream's tracks and adds them to the webrtc rtcpeerconnection representing a connection to another user. after that, the status display is updated to say "connected". if getusermedia() fails, the catch block runs. this uses setstatusmessage() to update the status box to indicate that an
error occurred. the important thing here is that the getusermedia() call returns almost immediately, even if the camera stream hasn't been obtained yet. even if the handlecallbutton() function has already returned to the code that called it, when getusermedia() has finished working, it calls the handler you provide. as long as the app doesn't assume that streaming has begun, it can just keep on runnin...
...we're able to chain multiple asynchronous actions to occur one after another this way because each .then() block returns a new promise that resolves when the .then() block is done ru...
...s response to ensure that the response body is fully downloaded, and when it is available transform it into a blob object that we can do something with. the result of this is returned like so: response => response.blob() which is shorthand for function(response) { return response.blob(); } unfortunately, we need to do slightly more than this. fetch promises do not fail on 404 or 500
errors — only on something catasrophic like a network failure. instead, they succeed, but with the response.ok property set to false. to produce an
error on a 404, for example, we need to check the value of response.ok, and if false, throw an
error, only returning the blob if it is true. this can be done like so — add the following lines below your first line of javascript. let promise2 = promis...
...And 20 more matches
JSAPI User Guide
mere nicety if the process is about to exit anyway. but as that is not always the case, calling js_shutdown is a good habit to get into.) the context: use js_newcontext and js_destroycontext. for maximum ecmascript standard compliance, applications should also use js_setoptions to enable jsoption_varobjfix. to get the latest javascript language features, applications may use js_setversion.
error reporting is also per-context and is enabled using js_set
errorreporter. the global object: to create this object, you first need a jsclass with the jsclass_global_flags option. the example below defines a very basic jsclass (named global_class) with no methods or properties of its own. use js_newglobalobject to create a global object. use js_initstandardclasses to populate it with the stand...
...cribed above. #include "jsapi.h" using namespace js; // the class of the global object. static jsclass globalclass = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratestub, js_resolvestub, js_convertstub, nullptr, nullptr, nullptr, nullptr, js_globalobjecttracehook }; // the
error reporter callback. void report
error(jscontext *cx, const char *message, js
errorreport *report) { fprintf(stderr, "%s:%u:%s\n", report->filename ? report->filename : "[no filename]", (unsigned int) report->lineno, message); } int run(jscontext *cx) { // enter a request before running anything in the context. jsautorequest ar(cx); // create ...
... // own custom js objects and run scripts. return 0; } int main(int argc, const char *argv[]) { // initialize the js engine. if (!js_init()) return 1; // create a js runtime. jsruntime *rt = js_newruntime(8l * 1024l * 1024l); if (!rt) return 1; // create a context. jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; js_set
errorreporter(rt, report
error); int status = run(cx); // shut everything down. js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); return status; } each jsnative has the same signature, regardless of what arguments it expects to receive from javascript. the javascript arguments to the function are given in argc and vp. argc tells how many actual arguments the call...
...And 20 more matches
Web Console remoting - Firefox Developer Tools
nt can request further network event details - like response body or request headers. to attach to the webconsoleactor, follow these steps: connecttoserver() // the usual listtabs() pickthetabyouwant() debuggerclient.attachconsole(tab.consoleactor, listeners, onattachconsole) the listeners argument is an array which specifies listeners you want to start in the web console. these can be: page
errors, window.console api messages, network activity, and file activity. for example: ["page
error", "consoleapi", "networkactivity", "fileactivity"] the web console actor does not start any listeners by default. the client has the option to start each listener when needed. this approach allows for lower resource usage on the server - this is a potential issue if the server runs on devices with fewe...
...: "root", "consoleactor": "conn0.console9", "selected": 2, "tabs": [ { "actor": "conn0.tab2", "consoleactor": "conn0.console7", "title": "", "url": "https://tbpl.mozilla.org/?tree=fx-team" }, // ... ] } notice that the consoleactor is also available as a global actor. ...
... "actor": "conn0.tab2", "consoleactor": "conn0.console7", "title": "", "url": "https://tbpl.mozilla.org/?tree=fx-team" }, // ... ] } notice that the consoleactor is also available as a global actor. when you attach to the global consoleactor you receive all of the network requests, page
errors, and the other events from all of the tabs and windows, including chrome
errors and network events. ...
...And 19 more matches
Using Web Workers - Web APIs
using web workers. web workers api a worker is an object created using a constructor (e.g. worker()) that runs a named javascript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. thus, using the window shortcut to get the current global scope (instead of self) within a worker will return an
error. the worker context is represented by a dedicatedworkerglobalscope object in the case of dedicated workers (standard workers that 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 re...
...you to enter two numbers to be multiplied together. the numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed. this example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. more advanced details are covered later on in the article. worker feature detection for slightly more controlled
error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js): if (window.worker) { ... } spawning a dedicated worker creating a new worker is simple. all you need to do is call the worker() constructor, specifying the uri of a script to execute in the worker thread (main.js): var myworker = new worker('worker.js'); sending messa...
...n thread and worker, it is copied or "transferred" (moved), not shared. read transferring data to and from workers: further details for a much more thorough explanation. terminating a worker if you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's terminate method: myworker.terminate(); the worker thread is killed immediately. ...
...And 19 more matches
TypeScript support in Svelte - Learn web development
typescript: optional static typing for javascript typescript is a superset of javascript that provides features such as optional static typing, classes, interfaces, and generics. the goal of typescript is to help catch mistakes early through its type system and make javascript development more efficient. one of the big benefits is enabling ides to provide a richer environment for spotting common
errors as you type the code. best of all, javascript code is valid typescript code; typescript is a superset of javascript. you can rename most of your .js files to .ts files and they will just work. our typescript code will be able to run everywhere javascript can run. how is that possible? typescript "transpiles" our code to vainilla javascript. that means that it parses typescript code and produce...
...verse report we can see that typescript is the 7th most used and 5th fastest growing language used on github. according to stackoverflow's 2019 developer survey it is the third most loved language, right behind rust and python. so typescript is going through a great phase of adoption. typescript's main advantages are: early spotted bugs: the compiler checks types at compile time and provides
error reporting. readability: static typing gives the code more structure, making it self-documenting and more readable. rich ide support: type information allows code editors and ides to offer features like code navigation, autocompletion, and smarter hints. safer refactoring: types allows ides to know more about your code, and assist you while refactoring large portions of your code base. type in...
... developer experience with typescript typescript provides code editors and ides with lots of information to allow them to deliver a friendlier development experience. we'll use visual studio code to do a quick test and see how we can get autocompletion hints and type-checking as we're writing components. note: if you don't wish to use vs code, we also provide instructions for using typescript
error checking from the terminal instead, slightly later on. there is work in progress to support typescript in svelte projects in several code editors; the most complete support so far is available in the svelte for vs code extension, which is developed and maintained by the svelte team. this extension offers type checking, inspecting, refactoring, intellisense, hover-information, auto-completion, a...
...And 18 more matches
nsIDOMWindowUtils
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 unsigned long long th...
...(not content-accessible) read only. elementsrestyled read only unsigned long long the number of elements which have been restyled for the current document. keep in mind that during a restyle operation, an element may be restyled multiple times (for example, when an inline element contains blocks). this number also counts restyling of pseudo-elements and anonymous boxes. throws ns_
error_not_available if the count can't be provided. focusedinputtype string the type of the currently-focused html <input> element, if one is focused. imageanimationmode unsigned short returns the image animation mode of the window. the attribute's value must be one of the animationmode values from imgicontainer. imeisopen boolean returns the ime open state...
... ime status. values correspond to the ime_status_* constants defined below. read only. ismozafterpaintpending boolean returns true if a mozafterpaint event has been queued but not yet fired. read only. layermanagertype astring what type of layer manager the widget associated with this window is using. "basic" is unaccelerated; other types are accelerated. throws an
error if there is no widget associated with this window. read only. outerwindowid unsigned long long the id of the window's outer window. read only. paintingsuppressed boolean true if painting is currently suppressed for this window; otherwise false. read only. this is used on mobile, for example, to prevent attempts to render content until enough of the page ...
...And 18 more matches
Using Fetch - Web APIs
previously achieved using xmlhttprequest. fetch provides a better alternative that can be easily used by other technologies such as service workers. fetch also provides a single logical place to define other http-related concepts such as cors and extensions to http. the fetch specification differs from jquery.ajax() in three main ways: the promise returned from fetch() won’t reject on http
error status even if the response is an http 404 or 500. instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites are silently ignored. fetch won’t send c...
...t', // *get, post, put, delete, etc. ...
...://example.com', { credentials: 'omit' }) uploading json data use fetch() to post json-encoded data. const data = { username: 'example' }; fetch('https://example.com/profile', { method: 'post', // or 'put' headers: { 'content-type': 'application/json', }, body: json.stringify(data), }) .then(response => response.json()) .then(data => { console.log('success:', data); }) .catch((
error) => { console.
error('
error:',
error); }); uploading a file files can be uploaded using an html <input type="file" /> input element, formdata() and fetch(). const formdata = new formdata(); const filefield = document.queryselector('input[type="file"]'); formdata.append('username', 'abc123'); formdata.append('avatar', filefield.files[0]); fetch('https://example.com/profile/avatar', { meth...
...And 18 more matches
Strict mode - JavaScript
trict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. strict mode makes several changes to normal javascript semantics: eliminates some javascript silent
errors by changing them to throw
errors. fixes mistakes that make it difficult for javascript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. prohibits some syntax likely to be defined in future versions of ecmascript. see transitioning to strict mode, if you want to change your code to work in the restricted variant...
...to enter strict mode. the entire contents of javascript modules are automatically in strict mode, with no statement needed to initiate it. function strict() { // because this is a module, i'm strict by default } export default strict; changes in strict mode strict mode changes both syntax and runtime behavior. changes generally fall into these categories: changes converting mistakes into
errors (as syntax
errors or at runtime), changes simplifying how the particular variable for a given use of a name is computed, changes simplifying eval and arguments, changes making it easier to write "secure" javascript, and changes anticipating future ecmascript evolution. converting mistakes into
errors strict mode changes some previously-accepted mistakes into
errors. javascript was designed to ...
...le for a given use of a name is computed, changes simplifying eval and arguments, changes making it easier to write "secure" javascript, and changes anticipating future ecmascript evolution. converting mistakes into
errors strict mode changes some previously-accepted mistakes into
errors. javascript was designed to be easy for novice developers, and sometimes it gives operations which should be
errors non-
error semantics. sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future. strict mode treats these mistakes as
errors so that they're discovered and promptly fixed. first, strict mode makes it impossible to accidentally create global variables. in normal javascript mistyping a variable in an assignment creates a new property on the global object a...
...And 18 more matches
Index - Archive of obsolete content
ng older hardware, for example, and can't upgrade to the latest and greatest browsers. or for "reasons," your company is required to use very old software and you need to build web content that runs on that software. or perhaps you're just curious about the history of an obsolete feature or api, and how it worked. 2 .htaccess ( hypertext access ) 301 redirect, cache control, custom
error pages, htaccess, permanent redirect, redirect file accessing : htaccess files can be opened using any text editor, like windows notepad, vin, sublime text editor or any other. syntax highliting support for .htaccess files less. 3 2015 mdn fellowship program 2015, archive, fellowship no summary! 4 api api, archive archived documentation about obsolet...
... cfx add-on sdk, cfx enables you to test, run, and package add-ons. cfx is is no longer supported as of firefox 44 and no longer accepted for add-on submission, jpm should now be used instead. 135 cfx to jpm cfx, jpm, sdk, add-on a guide to working with jpm if you're already familiar with cfx. 136 console add-on sdk enables your add-on to log
error, warning or informational messages. 137 jpm add-on sdk, jpm jpm is a command-line tool that enables you to test, run, and package add-ons. 138 jpm-mobile adb, add-ons, jpm, mobile, testing, travis-ci the node-based replacement for cfx --force-mobile. enables you to run and test add-ons for firefox mobile (aka fennec). 139 jpmignore jpm ...
...gsession->makewindoweditable(domwindow, editortype, pr_true). the first parameter is the nsidomwindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. ...
...And 17 more matches
sample2
/* this source code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...ficate for signature verification-----" #define ns_cert_vfy_trailer "-----end certificate for signature verification-----" #define ns_sig_header "-----begin signature-----" #define ns_sig_trailer "-----end signature-----" #define ns_cert_header "-----begin certificate-----" #define ns_cert_trailer "-----end certificate-----" /* missing publically from nss versions earlier than 3.13 */ #ifndef sec_
error_base #define sec_
error_base (-0x2000) typedef enum { sec_
error_io = sec_
error_base + 0, sec_
error_token_not_logged_in = (sec_
error_base + 155), sec_
error_end_of_list } sec
errorcodes; #endif /* port_
errortostring introduced in nss 3.13. on earlier versions of nss that * don't support
error tables, pr_
errortostring will return "unknown code". */ #ifndef port_
errortostring #define port_
errortostring...
...fine sec_
error_base (-0x2000) typedef enum { sec_
error_io = sec_
error_base + 0, sec_
error_token_not_logged_in = (sec_
error_base + 155), sec_
error_end_of_list } sec
errorcodes; #endif /* port_
errortostring introduced in nss 3.13. on earlier versions of nss that * don't support
error tables, pr_
errortostring will return "unknown code". ...
...And 17 more matches
JSAPI Cookbook
(if your constructor doesn't take any arguments, you can skip the second step and call js_new(cx, constructor, 0, null) in step 3.) /* jsapi */ /* step 1 - get the value of |person| and check that it is an object. */ js::rootedvalue constructor_val(cx); if (!js_getproperty(cx, js_getglobalobject(cx), "person", &constructor_val)) return false; if (!constructor_val.isobject()) { js_report
error(cx, "person is not a constructor"); return false; } js::rootedobject constructor(cx, &constructor_val.toobject()); /* step 2 - set up the arguments. */ js::rootedstring name_str(cx, js_newstringcopyz(cx, "dave")); if (!name_str) return false; js::autovaluearray<2> args(cx); args[0].setstring(name_str); args[1].setint32(24); /* step 3 - call |new person(...args)|, passing the arguments.
...* otherwise, convert the number to floating point (see the next example). ...
...ating 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_report
error does this. ...
...And 17 more matches
nsIFile
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 file. on the mac, getting...
...ss 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() this function is used for cons...
...or 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. this string must not c...
...And 17 more matches
WebGL best practices - Web APIs
api, and it's often not obvious what the recommended ways to use it are. this page tackles recommendations across the spectrum of expertise, and not only highlights dos and don'ts, but also details why. you can rely on this document to guide your choice of approach, and ensure you're on the right track no matter what browser or hardware your users run. general topics address and eliminate webgl
errors your application should run without generating any webgl
errors (as returned by get
error). every webgl
error is reported in the web console as a javascript warning with a descriptive message. after too many
errors (32 in firefox), webgl stops generating descriptive messages, which really hinders debugging. the only
errors a well-formed page generates are out_of_memory and context_lost. know y...
...by default, so a flush can help fill the gap, as well. use webgl.flush() when not using requestanimationframe when not using raf, (such as when using rpaf; see below) use webgl.flush() to encourage eager execution of enqueued commands. because raf is directly followed by the frame boundary, an explicit webgl.flush() isn't really needed with raf. avoid blocking api calls in production (e.g. get
error, getparameter) certain webgl entry points cause synchronous stalls on the calling thread. even basic requests can take as long as 1ms, but they can take even longer if they need to wait for all graphics work to be completed (with an effect similar to glfinish() in native opengl). in production code, avoid such entry points, especially on the browser main thread where they can cause the entire p...
...calling thread. even basic requests can take as long as 1ms, but they can take even longer if they need to wait for all graphics work to be completed (with an effect similar to glfinish() in native opengl). in production code, avoid such entry points, especially on the browser main thread where they can cause the entire page to jank (often including scrolling or even the whole browser). get
error(): causes a flush + round-trip to fetch
errors from the gpu process). for example, within firefox, the only time glget
error is checked is after allocations (bufferdata, *teximage*, texstorage*) to pick up any gl_out_of_memory
errors. getshader/programparameter(), getshader/programinfolog(), other gets on shaders/programs: flush + shader compile + round-trip, if not done after shader comp...
...And 17 more matches
Event reference
the rendering model. this article offers a list of events that can be sent; some are standard events defined in official specifications, while others are events used internally by specific browsers; for example, mozilla-specific events are listed so that add-ons can use them to interact with the browser. most common categories resource events event name fired when
error a resource failed to load. abort the loading of a resource has been aborted. load a resource and its dependent resources have finished loading. beforeunload the window, the document and its resources are about to be unloaded. unload the document or a dependent resource is being unloaded. network events event name fired whe...
... blur an element has lost focus (does not bubble). focusin an element is about to receive focus (does bubble). focusout an element is about to lose focus (does bubble). websocket events event name fired when open a websocket connection has been established. message a message is received through a websocket.
error a websocket connection has been closed with prejudice (some data couldn't be sent for example). close a websocket connection has been closed. session history events event name fired when pagehide a session history entry is being traversed from. pageshow a session history entry is being traversed to. popstate a session ...
...t works with other inputs such as speech recognition). compositionupdate a character is added to a passage of text being composed. compositionend the composition of a passage of text has been completed or canceled. view events event name fired when fullscreenchange an element was toggled to or from fullscreen mode. fullscreen
error it was impossible to switch to fullscreen mode for technical reasons or because the permission was denied. resize the document view has been resized. scroll the document view or an element has been scrolled. clipboard events event name fired when cut the selection has been cut and copied to the clipboard copy the selec...
...And 17 more matches
Debugging HTML - Learn web development
previous overview: introduction to html next writing html is fine, but what if something goes wrong, and you can't work out where the
error in the code is? ...
... previous overview: introduction to html next writing html is fine, but what if something goes wrong, and you can't work out where the
error in the code is? ...
...p you find and fix
errors in html. prerequisites: html familiarity, as covered in, for example, getting started with html, html text fundamentals, and creating hyperlinks. objective: learn the basics of using debugging tools to find problems in html. debugging isn't scary when writing code of some kind, everything is usually fine, until that dreaded moment when an
error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. for example, the following shows an
error reported when trying to compile a simple program written in the rust language. here, the
error message is relatively easy to understand — "unterminated double quote string". if you look at the listing, you can probably see how pri...
...And 16 more matches
Index
ased network security services (nss) 3.56 on 21 august 2020, which is a minor release. 159 nss api guidelines newsgroup: mozilla.dev.tech.crypto 160 nss certverify log nss all the nss verify functions except, the *verifynow() functions, take a parameter called 'certverifylog'. if you supply the log parameter, nss will continue chain validation after each
error . the log tells you what the problem was with the chain and what certificate in the chain failed. 161 nss certificate download specification nss this document describes the data formats used by nss 3.x for installing certificates. this document is currently being revised and has not yet been reviewed for accuracy. 162 nss code coverage nss no summary! ...
...s mode. true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode. -create create new certificate, key, and module databases. use the -dbdir directory argument to specify a directory. if any of these databases already exist in a specified directory, modutil returns an
error message. -default modulename specify the security mechanisms for which the named module will be a default provider. the security mechanisms are specified with the -mechanisms argument. -delete modulename delete the named module. the default nss pkcs #11 module cannot be deleted. -disable modulename disable all slots ...
...symmetric key to be used to encrypt the certificates and other meta-data. -r dumps all of the data in raw (binary) form. this must be saved as a der file. the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. ...
...And 16 more matches
nsIHttpChannel
nderlying 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. if the new channel supports...
...ibute 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; getter returns an uppercase string. this attribute may only be set before the c...
...e; 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. use this attribute to disting...
...And 15 more matches
nsIZipWriter
on the archive can be performed one by one, or queued for later execution. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) once all the operations you wish to perform are added to the queue, a call to processqueue() will perform the operations in the order they were added to the queue. 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 ut...
...en(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 compression_none 0 do not compr...
...ath. 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 entries in order to ad...
...And 15 more matches
DOMException - Web APIs
this field is used for historical reasons. ...
...this field is used for historical reasons. ...
...ssing 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 domexception() returns a domexception object with a specified message and name. properties domexception.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 domexception.name attribute. domexception.message read only returns a domstring representing a message or description associated with the given
error name. domexception.name read only returns a domstring that contains one of the strings associat...
...And 15 more matches
Template Logging - Archive of obsolete content
« previous debugging problems with a template can be difficult as many problems are logic
errors that are often not possible to determine automatically. for example, if you spell a value wrong, no data may be returned, but the template system won't know that that this was because of a spelling
error, or simply that there shouldn't be any data anyway. fortunately, some debugging and logging support is provided with templates that may help. logging template results there are two main ways in which template
errors may be detected. the first debugging method involves logging all new results that apply to the template due to the data changing as well as logging results that are changed or removed. in addition, each result generated when the template is first created and initialized i...
...sult generated when the template is first created and initialized is logged. this logging of result changes is not done by default; it must be enabled with a flag. <vbox datasources="..." flags="logging"/> the flags attribute on the root element of the template should include the logging flag. if other flags are used as well, separate them with spaces. enabling logging will output details to the
error console for each result. the
error console can be found on the firefox tools menu. this logging of results can be very useful for debugging, but remember to remove this flag when you have finished and the template works correctly, as the logging can take up extra time that is not necessary when the template is working. each result is logged in a form much like the following: in template with id r...
...removed inactive result for query 2 (active query is 1) a result no longer matches, but it is inactive and doesn't have any content. this is because the first query overrides it. removed inactive result for query 2 (no new active query) a result no longer matches, but it is inactive and doesn't have any content. however, no other query overrides it. no changes to the content will occur. template
errors the second type of template
error is a syntax
error is the template rules, for example, a missing attribute or a tag out of place. these types of
errors are also logged to the console, however, these types of
errors are logged whether the logging flag is set or not. the following lists the
errors that can occur and an explanation of what the problem is. querytype attribute doesn't specify a val...
...And 14 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
as a pkcs 11 csr. generates encryption/mac keys and outputs public key as pkcs11 certificate signing request /* this source code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...e, secupwdata *pwdata) { ck_mechanism_type mechanism; secoidtag algtag; pk11rsagenparams rsaparams; void *params; seckeyprivatekey *privkey = null; secstatus rv; unsigned char randbuf[blocksize + 1]; rv = generaterandom(randbuf, blocksize); if (rv != secsuccess) { fprintf(stderr, "
error while generating the random numbers : %s\n", port_
errortostring(rv)); goto cleanup; } pk11_randomupdate(randbuf, blocksize); switch (keytype) { case rsakey: rsaparams.keysizeinbits = size; rsaparams.pe = publicexponent; mechanism = ckm_rsa_pkcs_key_pair_gen; algtag ...
...getsignaturealgorithmoidtag(privkey->keytype, hashalgtag); if (algid == sec_oid_unknown) { pr_fprintf(pr_stderr, "unknown key or hash type for issuer.\n"); goto cleanup; } rv = secoid_setalgorithmid(arena, &cert->signature, algid, 0); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not set signature algorithm id.\n%s\n", port_
errortostring(rv)); goto cleanup; } /* we only deal with cert v3 here */ *(cert->version.data) = 2; cert->version.len = 1; der.len = 0; der.data = null; dummy = sec_asn1encodeitem (arena, &der, cert, sec_asn1_get(cert_certificatetemplate)); if (!dummy) { pr_fprintf(pr_stderr, "could not encode certificate.\n"); ...
...And 14 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
"okay, never mind, drop my offer and i'll consider yours instead." an impolite peer, which always ignores incoming offers that collide with its own offers. it never apologizes or gives up anything to the polite peer. any time a collision occurs, the impolite peer wins. this way, both peers know exactly what should happen if there are collisions between offers that have been sent. responses to
error conditions become far more predictable. how you determine which peer is polite and which is impolite is generally up to you. it could be as simple as assigning the polite role to the first peer to connect to the signaling server, or you could do something more elaborate like having the peers exchange random numbers and assigning the polite role to the winner. however you make the determination, ...
...alled by either of the two end-points that want to talk to one another. it doesn't matter who does it first; the negotiation will just work. async function start() { try { const stream = await navigator.mediadevices.getusermedia(constraints); for (const track of stream.gettracks()) { pc.addtrack(track, stream); } selfvideo.srcobject = stream; } catch(err) { console.
error(err); } } this isn't appreciably different from older webrtc connection establishment code. the user's camera and microphone are obtained by calling getusermedia(). the resulting media tracks are then added to the rtcpeerconnection by passing them into addtrack(). then, finally, the media source for the self-view <video> element indicated by the selfvideo constant is set to the camera and mic...
...ionneeded event first, we implement the rtcpeerconnection event handler onnegotiationneeded to get a local description and send it using the signaling channel to the remote peer. let makingoffer = false; pc.onnegotiationneeded = async () => { try { makingoffer = true; await pc.setlocaldescription(); signaler.send({ description: pc.localdescription }); } catch(err) { console.
error(err); } finally { makingoffer = false; } }; note that setlocaldescription() without arguments automatically creates and sets the appropriate description based on the current signalingstate. the set description is either an answer to the most recent offer from the remote peer or a freshly-created offer if there's no negotiation underway. here, it will be always be an offer, because the n...
...And 14 more matches
core/promise - Archive of obsolete content
complementing its non-blocking nature. while this has a good reason and many advantages, it comes with a price. ...
...n-blocking nature. while this has a good reason and many advantages, it comes with a price. ...
...e. while this has a good reason and many advantages, it comes with a price. ...
...And 13 more matches
Making asynchronous programming easier with async and await - Learn web development
g = await promise.resolve("hello"); }; hello().then(alert); of course, the above example is not very useful, although it does serve to illustrate the syntax. let's move on and look at a real example. ...
...omise.resolve("hello"); }; hello().then(alert); of course, the above example is not very useful, although it does serve to illustrate the syntax. let's move on and look at a real example. ...
...status: ${response.status}`); } else { let myblob = await response.blob(); let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); } } myfetch() .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); it makes code much simpl...
...And 13 more matches
NSS Tools pk12util
t should be noted that the the crypto provider may be the softtoken module or an external hardware module. it may be the case that the cryptographic module does not support the requested algorithm and a best fit will be selected, likely to be the default. ...
...that the the crypto provider may be the softtoken module or an external hardware module. it may be the case that the cryptographic module does not support the requested algorithm and a best fit will be selected, likely to be the default. if no suitable replacement for the desired algorithm can be found a "no security module can perform the requested operation" will appear on the
error message. ...
...xternal hardware module. it may be the case that the cryptographic module does not support the requested algorithm and a best fit will be selected, likely to be the default. if no suitable replacement for the desired algorithm can be found a "no security module can perform the requested operation" will appear on the
error message. ...
...And 13 more matches
Starting WebLock
vice manager. you can then use the service manager to add the component to the category: nsresult rv; nscomptr<nsiservicemanager> servman = do_queryinterface((nsisupports*)acompmgr, &rv); if (ns_failed(rv)) return rv; do_queryinterface the previous code uses the special nscomptr function do_queryinterface that lets you queryinterface without having to worry about reference counting,
error handling, and other overhead. the do_queryinterface knows what interface to qi to based on the nscomptr that is being assigned into. we could have just as easily have used the raw queryinterface() method, but using nscomptr is much more economical (see smart pointers). once you have a nsiservicemanager reference, you can ask it for the service you are interested in. this process is similar to u...
...nother interface that takes a contract id. here we'll use the latter. the first parameter to the getservicebycontractid is of course the contract id, which is defined in the nsxpcom.h header file. the next parameter is a nifty macro that returns the iid for the interface name that you pass in. the last parameter assigns an out interface pointer to a nscomptr. assuming there weren't any unexpected
errors, the variable catman holds the nsicategorymanager interface pointer, which you can use to add the component as a startup observer by calling a method on the nsicategorymanager. the next step is to figure out which parameters to pass to the method. there is a category name and a name-value pair, but since the name-value pair meaning is category-specific, you need to figure out which category to ...
... * element is the first element upon the first call. must be * preceded by a call to hasmoreelements() which returns pr_true. * this method is generally called within a loop to iterate over * the elements in the enumerator. * * @see hasmoreelements() * @return ns_ok if the call succeeded in returning a non-null * value through the out parameter. * ns_
error_failure if there are no more elements * to enumerate. * @return the next element in the enumeration. */ nsisupports getnext(); }; implementing weblock once you have defined the interfaces that the component will implement, you can begin to write the implementation code that will actually carry out the web locking functionality. the weblock component impleme...
...And 13 more matches
MediaDevices.getUserMedia() - Web APIs
a camera, video recording device, screen sharing service, and so forth), an audio track (similarly, produced by a physical or virtual audio source like a microphone, a/d converter, or the like), and possibly other track types. it returns a promise that resolves to a mediastream object. if the user denies permission, or matching media is not available, then the promise is rejected with notallowed
error or notfound
error respectively. note: it's possible for the returned promise to neither resolve nor reject, as the user is not required to make a choice at all and may simply ignore the request. generally, you will access the mediadevices singleton object using navigator.mediadevices, like this: async function getmedia(constraints) { let stream = null; try { stream = await navigator.
...r reject, as the user is not required to make a choice at all and may simply ignore the request. generally, you will access the mediadevices singleton object using navigator.mediadevices, like this: async function getmedia(constraints) { let stream = null; try { stream = await navigator.mediadevices.getusermedia(constraints); /* use the stream */ } catch(err) { /* handle the
error */ } } similarly, using the raw promises directly, the code looks like this: navigator.mediadevices.getusermedia(constraints) .then(function(stream) { /* use the stream */ }) .catch(function(err) { /* handle the
error */ }); note: if the current document isn't loaded securely, navigator.mediadevices will be undefined, and you cannot use getusermedia(). see security for more information...
...ng the types of media to request, along with any requirements for each type. the constraints parameter is a mediastreamconstraints object with two members: video and audio, describing the media types requested. either or both must be specified. if the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with notfound
error. the following requests both audio and video without any specific requirements: { audio: true, video: true } if true is specified for a media type, the resulting stream is required to have that type of track in it. if one cannot be included for any reason, the call to getusermedia() will result in an
error. while information about a user's cameras and microphones are inaccessible for priv...
...And 13 more matches
Space Manager Detailed Design - Archive of obsolete content
ayoffset the y-offset of where the band begins. the coordinate is * relative to the upper-left corner of the local coordinate space * @param amaxsize the size to use to constrain the band data * @param abanddata [in,out] used to return the list of trapezoids that * describe the available space and the unavailable space * @return ns_ok if successful and ns_
error_failure if the band data is not * not large enough. the 'count' member of the band data struct * indicates how large the array of trapezoids needs to be */ nsresult getbanddata(nscoord ayoffset, const nssize& amaxsize, nsbanddata& abanddata) const; /** * add a rectangular region of unavailable space. the ...
...banddata& abanddata) const; /** * add a rectangular region of unavailable space. the space is * relative to the local coordinate system. * * the region is tagged with a frame * * @param aframe the frame used to identify the region. must not be null * @param aunavailablespace the bounding rect of the unavailable space * @return ns_ok if successful * ns_
error_failure if there is already a region tagged with aframe */ nsresult addrectregion(nsiframe* aframe, const nsrect& aunavailablespace); /** * resize the rectangular region associated with aframe by the specified * deltas. the height change always applies to the bottom edge or the existing * rect. you specify whether the width change applies to the left ...
... */ nsresult addrectregion(nsiframe* aframe, const nsrect& aunavailablespace); /** * resize the rectangular region associated with aframe by the specified * deltas. the height change always applies to the bottom edge or the existing * rect. ...
...And 12 more matches
Handling common JavaScript problems - Learn web development
se has been returned before trying to use the response for anything. this kind of operation has been made easier to handle by the introduction of promises to the javascript language. note: buggy javascript code: the 10 most common mistakes javascript developers make has some nice discussions of these common mistakes and more. linters as with html and css, you can ensure better quality, less
error-prone javascript code using a linter, which points out
errors and can also flag up warnings about bad practices, etc., and be customized to be stricter or more relaxed in their
error/warning reporting. the javascript/ecmascript linters we'd recommend are jshint and eslint; these can be used in a variety of ways, some of which we'll detail below. online the jshint homepage provides an online lin...
... code editor plugins it is not very convenient to have to copy and paste your code over to a web page to check its validity several times. what you really want is a linter that will fit into your standard workflow with the minimum of hassle. many code editors have linter plugins, for example github's atom code editor has a jshint plugin available. ...
...s enter/return to search for linting-related packages. you should see a package called lint at the top of the list. install this first (using the install button), as other linters rely on it to work. after that, install the linter-jshint plugin. after the packages have finished installing, try loading up a javascript file: you'll see any issues highlighted with green (for warnings) and red (for
errors) circles next to the line numbers, and a separate panel at the bottom provides line numbers,
error messages, and sometimes suggested values or other fixes. other popular editors have similar linting packages available. for example, see the "plugins for text editors and ides" section of the jshint install page. other uses there are other ways to use such linters; you can read about them on t...
...And 12 more matches
NSS tools : pk12util
is must be saved as a der file. the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. -v enable debug logging when importing. -w p12filepasswordfile specify the text file containing the pkcs #12 file password. -w p12filepassword specify the pkcs #12 file password. ...
...ult is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. -v enable debug logging when importing. -w p12filepasswordfile specify the text file containing the pkcs #12 file password. -w p12filepassword specify the pkcs #12 file password. ...
...mation in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. -v enable debug logging when importing. -w p12filepasswordfile specify the text file containing the pkcs #12 file password. -w p12filepassword specify the pkcs #12 file password. ...
...And 12 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
if the format is invalid. in addition to using css to style inputs based on the :valid or :invalid ui states based on the current state of each input, as noted in the ui pseudo-classes section above, the browser provides for client-side validation on (attempted) form submission. ...
...r :invalid ui states based on the current state of each input, as noted in the ui pseudo-classes section above, the browser provides for client-side validation on (attempted) form submission. on form submission, if there is a form control that fails constraint validation, supporting browsers will display an
error message on the first invalid form control; displaying a default message based on the
error type, or a message set by you. ...
...straint validation, supporting browsers will display an
error message on the first invalid form control; displaying a default message based on the
error type, or a message set by you. some input types and other attributes place limits on what values are valid for a given input. for example, <input type="number" min="2" max="10" step="2"> means only the number 2, 4, 6, 8, or 10 are valid. several
errors could occur, including a rangeunderflow
error if the value is less than 2, rangeoverflow if greater than 10, stepmismatch if the value is a number between 2 and 10, but not an even integer (does not match the requirements of the step attribute), or typemismatch if the value is not a number. for the input types whose domain of possible values is periodic (that is, at the highest possible value, ...
...And 12 more matches
Modularization techniques - Archive of obsolete content
const nsiid &aiid, void **aresult); ns_imethod_(void) lockfactory(prbool alock); }; /* * nssample implementation */ nssample::nssample() { mrefcnt = 0; } nssample::~nssample() { assert(mrefcnt == 0); } ns_imethod nssample::queryinterface(const nsiid &aiid, void **aresult) { if (aresult == null) { return ns_
error_null_pointer; } // always null result, in case of failure *aresult = null; if (aiid.equals(kisupportsiid)) { *aresult = (void *) this; } else if (aiid.equals(kisampleiid)) { *aresult = (void *) this; } if (aresult != null) { return ns_
error_no_interface; } addref(); return ns_ok; } nsrefcount nssample::addref() { return ++mrefcnt; } nsrefcount nssample::rel...
...return 0; // don't access mrefcnt after deleting! ...
... } return mrefcnt; } ns_imethodimp nssamplefactory::createinstance(nsisupports ...
...And 11 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
allers are allowed to call this object's scritable methods. ...
...*aflags) {*aflags = nsiclassinfo::plugin_object | nsiclassinfo::dom_object; return ns_ok;} ns_imethod getimplementationlanguage(pruint32 *aimplementationlanguage) {*aimplementationlanguage = nsiprogramminglanguage::cplusplus; return ns_ok;} // the rest of the methods can safely return
error codes... ...
...timplementationlanguage(pruint32 *aimplementationlanguage) {*aimplementationlanguage = nsiprogramminglanguage::cplusplus; return ns_ok;} // the rest of the methods can safely return
error codes... ...
...And 11 more matches
NSS tools : pk12util
symmetric key to be used to encrypt the certificates and other meta-data. -r dumps all of the data in raw (binary) form. this must be saved as a der file. the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. ...
...certificates and other meta-data. -r dumps all of the data in raw (binary) form. this must be saved as a der file. the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. ...
...-data. -r dumps all of the data in raw (binary) form. this must be saved as a der file. the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. ...
...And 11 more matches
HTMLScriptElement - Web APIs
hods for manipulating the behavior and execution of <script> elements (beyond the inherited htmlelement interface). javascript files should be served with the application/javascript mime type, but browsers are lenient and block them only if the script is served with an image type (image/*), video type (video/*), audio type (audio/*), or text/csv. if the script is blocked, its element receives an
error event; otherwise, it receives a load event. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x...
...he specification. these algorithms describe the core ideas, but they rely on the parsing rules for <script> start and end tags in html, in foreign content, and in xml; the rules for the document.write() method; the handling of scripting; and so on. htmlscriptelement.crossorigin is a domstring reflecting the cors setting for the script element. for scripts from other origins, this controls if
error information will be exposed. htmlscriptelement.text is a domstring that joins and returns the contents of all text nodes inside the <script> element (ignoring other nodes like comments) in tree order. on setting, it acts the same way as the textcontent idl attribute. note: when inserted using the document.write() method, <script> elements execute (typically synchronously), but when inser...
...ethods; inherits methods from its parent, htmlelement. examples dynamically importing scripts let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript). these scripts will be asynchronously executed. for more details, see the defer and async properties. ...
...And 11 more matches
Promise - JavaScript
the final value, the asynchronous method returns a promise to supply the value at some point in the future. a promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation completed successfully. rejected: meaning that the operation failed. a pending promise can either be fulfilled with a value, or rejected with a reason (
error). when either of these options happens, the associated handlers queued up by a promise's then method are called. if the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. as the promise.prototype.then() and promise.prototype...
....then(handlefulfilledb,handlerejectedb) .then(handlefulfilledc,handlerejectedc); // or, perhaps better ... const mypromise = (new promise(myexecutorfunc)) .then(handlefulfilleda) .then(handlefulfilledb) .then(handlefulfilledc) .catch(handlerejectedany); handling a rejected promise too early has consequences further down the promise chain. sometimes there is no choice, because an
error must be handled immediately. (see throw -999 in the example, below, for a technique to handle the consequences.) on the other hand, in the absence of an immediate need, it is simpler to leave out
error handling until a final .catch() statement. the signatures of these two functions are simple, they accept a single parameter of any type. these functions are written by you, the programmer. the ter...
...promise generator will utilize reject() while setting up an asynchronous call, or within the call-back, or both. the function promisegetword() illustrates how an api function might generate and return a promise in a self contained manner. note that function troublewithgetnumber() ends with a throw(). that is forced because an es6 promise chain goes through all the .then() promises, even after an
error, and without the "throw()", the
error would seem "fixed". this is a hassle, and for this reason, it is common to omit rejectionfunc throughout the chain of .then() promises, and just have a single rejectionfunc in the final catch(). the alternative is to throw a special value (in this case "-999", but a custom
error type would be more appropriate). this code can be run under nodejs. comprehensio...
...And 11 more matches
JavaScript Debugger Service - Archive of obsolete content
s.jsdidebuggerservice); jsd.on(); // enables the service till firefox 3.6, for 4.x use asyncon if (jsd.ison) jsd.off(); // disables the service hooks jsd operates using the events hook mechanism. next, we add code to the various hooks. ...
...vice); jsd.on(); // enables the service till firefox 3.6, for 4.x use asyncon if (jsd.ison) jsd.off(); // disables the service hooks jsd operates using the events hook mechanism. next, we add code to the various hooks. ...
...ce hooks jsd operates using the events hook mechanism. next, we add code to the various hooks. jsd.scripthook = { onscriptcreated: function(script) { // your function here }, onscriptdestroyed: function(script) { // your function here } }; jsd.
errorhook = { on
error: function(message, filename, lineno, colno, flags, errnum, exc) { // your function here } }; // triggered when jsd.
errorhook[on
error] returns false jsd.debughook = { onexecute: function(frame, type, rv) { // your function here } }; jsd.enumeratescripts({ // the enumeratescript method will be called once for every script jsd knows about enumeratescript: function(script) { // your function here } }); a simple stack trace here, we will show how to implement a simple javascript stack trace using the jsd. ...
...And 10 more matches
Eclipse CDT
fig", and set it to the path of your .mozconfig file relative to the top source directory. set any other environment variables you want to set for the build, then close the project properties window. now when you hit the build button (the little hammer icon), you should see the source build in the console tab at the bottom of the window. the benefit of building from inside eclipse is that build
errors will appear in the problems tab at the bottom of the window, and from there you can double click on the build
error and it will take you straight to the source file and line where the problem occurred. for this to work reliably though, you still need to build using slow -j1 -w builds, so that make outputs non-interleaved "entering"/"leaving" lines. it also used to be necessary to add the followi...
...click "new", then select "c/c++ application". ...
...ipse is open source, of course so if anyone feels like doing a bit of java hacking to fix these issues that'd be great. headers are only parsed once for performance reasons, eclipse only processes header files that have include guards once, using the compiler options for the first source file it encounters that includes that header (eclipse bug 380511). ...
...And 10 more matches
nsISmsRequestManager
.createinstance(components.interfaces.nsismsrequestmanager); method overview long addrequest(in nsidommozsmsrequest arequest); long createrequest(in nsidommozsmsmanager amanager, out nsidommozsmsrequest arequest); void notifycreatemessagelist(in long arequestid, in long alistid, in nsidommozsmsmessage amessage); void notifygetsmsfailed(in long arequestid, in long a
error); void notifygotnextmessage(in long arequestid, in nsidommozsmsmessage amessage); void notifygotsms(in long arequestid, in nsidommozsmsmessage amessage); void notifymarkedmessageread(in long arequestid, in bool aread); void notifymarkmessagereadfailed(in long arequestid, in long a
error); void notifynomessageinlist(in long arequestid); void notifyreadmessagelistfailed(in long arequesti...
...tifygotnextmessage(in long arequestid, in nsidommozsmsmessage amessage); void notifygotsms(in long arequestid, in nsidommozsmsmessage amessage); void notifymarkedmessageread(in long arequestid, in bool aread); void notifymarkmessagereadfailed(in long arequestid, in long a
error); void notifynomessageinlist(in long arequestid); void notifyreadmessagelistfailed(in long arequestid, in long a
error); void notifysmsdeleted(in long arequestid, in bool adeleted); void notifysmsdeletefailed(in long arequestid, in long a
error); void notifysmssendfailed(in long arequestid, in long a
error); void notifysmssent(in long arequestid, in nsidommozsmsmessage amessage); constants all sms related
errors that could apply to smsrequest objects. constant value description success_no_
error 0 ...
...long addrequest( in nsidommozsmsrequest arequest ); parameters arequest an smsrequest. return value the request id. ...
...And 10 more matches
Grammar and types - JavaScript
is converted into a sequence of input elements which are tokens, control characters, line terminators, comments, or whitespace. (spaces, tabs, and newline characters are considered whitespace.) comments the syntax of comments is the same as in c++ and in many other languages: // a one line comment /* this is a longer, * multi-line comment */ /* you can't, however, /* nest comments */ syntax
error */ comments behave like whitespace, and are discarded during script execution. note: you might also see a third type of comment syntax at the start of some javascript files, which looks something like this: #!/usr/bin/env node. this is called hashbang comment syntax, and is a special comment used to specify the path to a particular javascript engine that should execute the script. see hashba...
...clared 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. ...
...lue of undefined. an attempt to access an undeclared variable results in a reference
error exception being thrown: var a; console.log('the value of a is ' + a); // the value of a is undefined console.log('the value of b is ' + b); // the value of b is undefined var b; // this one may puzzle you until you read 'variable hoisting' below console.log('the value of c is ' + c); // uncaught reference
error: c is not defined let x; console.log('the value of x is ' + x); // the value of x is undefined console.log('the value of y is ' + y); // uncaught reference
error: y is not defined let y; you can use undefined to determine whether a variable has a value. in the following code, the variable input is not assigned a value, and the if statement evaluates to true. var input; if (input === undefined...
...And 10 more matches
try...catch - JavaScript
ore information on javascript exceptions. unconditional catch-block when a catch-block is used, the catch-block is executed when any exception is thrown from within the try-block. for example, when the exception occurs in the following code, control transfers to the catch-block. try { throw 'myexception'; // generates an exception } catch (e) { // statements to handle any exceptions logmy
errors(e); // pass exception object to
error handler } the catch-block specifies an identifier (e in the example above) that holds the value of the exception; this value is only available in the scope of the catch-block. conditional catch-blocks you can create "conditional catch-blocks" by combining try...catch blocks with if...else if...else structures, like this: try { myroutine(); // may thro...
...ck specifies an identifier (e in the example above) that holds the value of the exception; this value is only available in the scope of the catch-block. ...
...ple above) that holds the value of the exception; this value is only available in the scope of the catch-block. ...
...And 10 more matches
LiveConnect Overview - Archive of obsolete content
e information about javascript exceptions. java to javascript communication if you want to use javascript objects in java, you must import the netscape.javascript package into your java file. this package defines the following classes: netscape.javascript.jsobject allows java code to access javascript methods and properties. netscape.javascript.jsexception allows java code to handle javascript
errors. see the javascript reference for more information about these classes. locating the liveconnect classes in older versions of the netscape browser, these classes were distributed along with the browser. starting with javascript 1.2, these classes are delivered in a .jar file; in previous versions of javascript, these classes are delivered in a .zip file. for example, with netscape navigator 4 f...
... can pass it a javascript object as one of its argument. to do so, you must define the corresponding formal parameter of the method to be of type jsobject. also, any time you use javascript objects in your java code, you should put the call to the javascript object inside a try...catch statement which handles exceptions of type netscape.javascript.jsexception. this allows your java code to handle
errors in javascript code execution which appear in java as exceptions of type jsexception. accessing javascript with jsobject for example, suppose you are working with the java class called javadog. as shown in the following code, the javadog constructor takes the javascript object jsdog, which is defined as type jsobject, as an argument: import netscape.javascript.*; public class javadog{ public...
...is.dogsex = (string)jsdog.getmember("sex"); } } notice that the getmember method of jsobject is used to access the properties of the javascript object. the previous example uses getmember to assign the value of the javascript property jsdog.breed to the java data member javadog.dogbreed. note: a more realistic example would place the call to getmember inside a try...catch statement to handle
errors of type jsexception. see handling javascript exceptions in java for more information. to get a better sense of how getmember works, look at the definition of the custom javascript object dog: function dog(breed,color,sex){ this.breed = breed; this.color = color; this.sex = sex; } you can create a javascript instance of dog called gabby as follows: var gabby = new dog("lab", "chocolate"...
...And 9 more matches
L20n Javascript API
ring) and linkresource(string) might be better suited for adding resources. ctx.addeventlistener(event: string, callback: function) register an event handler on the context instance. currently available event types: ready - fired when all resources are available and the context instance is ready to be used. this event is also fired after each change to locale order (retranslation). ...
...(string) might be better suited for adding resources. ctx.addeventlistener(event: string, callback: function) register an event handler on the context instance. currently available event types: ready - fired when all resources are available and the context instance is ready to be used. this event is also fired after each change to locale order (retranslation). ...
...an event handler on the context instance. currently available event types: ready - fired when all resources are available and the context instance is ready to be used. this event is also fired after each change to locale order (retranslation).
error - fired when an
error occurs which prevents the context instance from working correctly or when the existing translations are buggy. the
error object is passed as the first argument to callback. ...
...And 9 more matches
Enc Dec MAC Output Public Key as CSR
#define ns_certreq_header "-----begin new certificate request-----" #define ns_certreq_trailer "-----end new certificate request-----" typedef enum { gen_csr, encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6 } headertype; /* this is conditionalized because port_
errortostring was introduced with nss 3.13. * though pr_
errortostring was available, support for it in nss wasn't. * fixme: samples should determine the version of nss that's available and refuse * to run if not 3.13 or higher. */ #ifndef port_
errortostring #ifndef sec_
error_base #define sec_
error_base (-0x2000) #define port_
errortostring(err) pr_
errortostring((err), pr_lan...
... switch (*c) { case 'g': return gen_csr; case 'e': return encrypt; case 'd': return decrypt; default: return unknown; } } /* * wrap the symkey using public key */ secstatus wrapkey(pk11symkey* key, seckeypublickey *pubkey, secitem **wrappedkey) { secstatus rv; secitem *data = (secitem *)port_zalloc(sizeof(secitem)); if (!data) { pr_fprintf(pr_stderr, "
error while allocating memory\n"); rv = secfailure; goto cleanup; } data->len = seckey_publickeystrength(pubkey); data->data = (unsigned char*)port_zalloc((data->len)*sizeof(unsigned int)); if (!data->data) { pr_fprintf(pr_stderr, "
error while allocating memory\n"); rv = secfailure; goto cleanup; } rv = pk11_pubwrapsymkey(ckm_rsa_pkcs, ...
...har *pqgfile, secupwdata *pwdata) { ck_mechanism_type mechanism; secoidtag algtag; pk11rsagenparams rsaparams; void *params; seckeyprivatekey *privkey = null; secstatus rv; unsigned char randbuf[blocksize + 1]; rv = generaterandom(randbuf, blocksize); if (rv != secsuccess) { fprintf(stderr, "
error while generating the random numbers : %s\n", port_
errortostring(rv)); goto cleanup; } pk11_randomupdate(randbuf, blocksize); switch (keytype) { case rsakey: rsaparams.keysizeinbits = size; rsaparams.pe = publicexponent; mechanism = ckm_rsa_pkcs_key_pair_gen; algtag ...
...And 9 more matches
A Web PKI x509 certificate primer
rfc 3766 2358 200 --- bsi 1976 256 256 in other words, sha1 is now deprecated for new uses. we should use at least 3072 key sizes and at least a 256 ecc curve. thus the recommendation here is for the root to be 4096 if using rsa and p384 for the root key. (p384 also chosen for compatibility as most ssl/tls implementations support this part of suite b). ...
... bsi 1976 256 256 in other words, sha1 is now deprecated for new uses. we should use at least 3072 key sizes and at least a 256 ecc curve. thus the recommendation here is for the root to be 4096 if using rsa and p384 for the root key. (p384 also chosen for compatibility as most ssl/tls implementations support this part of suite b). ...
...ses. we should use at least 3072 key sizes and at least a 256 ecc curve. thus the recommendation here is for the root to be 4096 if using rsa and p384 for the root key. (p384 also chosen for compatibility as most ssl/tls implementations support this part of suite b).
error codes in firefox here are some common
errors that might be encountered when working with certificates in firefox. ...
...And 9 more matches
An Overview of XPCOM
elow. see a reference implementation of queryinterface for detailed information. ...
...ence count to 0 sample::sample() : mrefcnt(0) { } sample::~sample() { } // typical, generic implementation of qi ns_imethodimp sample::queryinterface(const nsiid &aiid, void **aresult) { if (!aresult) { return ns_
error_null_pointer; } *aresult = null; if (aiid.equals(kisupportsiid)) { *aresult = (void *) this; } if (!*aresult) { return ns_
error_no_interface; } // add a reference addref(); return ns_ok; } ns_imethodimp_(nsrefcnt) sample::addref() { return ++mrefcnt; } ns_imethodimp_(nsrefcnt) sample::release() { if (--mrefcnt == 0) { delete this; return 0; } // optional: return the reference count return mrefcnt; } object interface discovery inheritance is another very important topic in object oriented pro...
...ircle. 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, all interface methods should return an nsresult
error value (see the xpcom api reference for a listing of these
error codes). these
error code results become the "exceptions" that xpcom handles. 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". t...
...And 9 more matches
nsIAnnotationService
aname the annotation name. adata binary contents of the item to save. adatalen length of binary data. amimetype mime type of the data to store. must be supplied. aflags should be "0" for now, some flags will be defined in the future. aexpiration one of the expire_* constant value defined above. getpageannotation() this method retrieves the value of a given uri annotation. throws an
error if the annotation does not exist. throws for binary annotations, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if the given annotation is set in a different type. nsivariant getpageannotation( in nsiuri auri, in autf8string aname ); parameters auri the uri on which the an...
...cific methods. the type-specific methods throw if the given annotation is set in a different type. nsivariant getpageannotation( in nsiuri auri, in autf8string aname ); parameters auri the uri on which the annotation is set. aname the annotation name. return value returns a page annotation. getitemannotation() this method retrieves the value of a given item annotation. throws an
error if the annotation does not exist. throws for binary annotations, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if the given annotation is set in a different type. nsivariant getitemannotation( in long long aitemid, in autf8string aname ); parameters aitemid the item on wh...
...methods throw if the given annotation is set in a different type. nsivariant getitemannotation( in long long aitemid, in autf8string aname ); parameters aitemid the item on which the annotation is set. aname the annotation name. return value returns an item annotation. getpageannotationstring() this method retrieves the value of a given uri annotation in string format. throws an
error if the annotation does not exist. throws for binary annotations, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if the given annotation is set in a different type. astring getpageannotationstring( in nsiuri auri, in autf8string aname ); parameters auri the uri on which the...
...And 9 more matches
nsIHttpServer
} } } reference : mozilla-release/netwerk/test/httpserver/nsihttpserver.idl [scriptable, uuid(cea8812e-faa6-4013-9396-f9936cbb74ec)] interface nsihttpserver : nsisupports { /** * starts up this server, listening upon the given port. ...
...ttpserver.idl [scriptable, uuid(cea8812e-faa6-4013-9396-f9936cbb74ec)] interface nsihttpserver : nsisupports { /** * starts up this server, listening upon the given port. * * @param port * the port upon which listening should happen, or -1 if no specific port is * desired * @throws ns_
error_already_initialized * if this server is already started * @throws ns_
error_not_available * if the server is not started and cannot be started on the desired port * (perhaps because the port is already in use or because the process does * not have privileges to do so) * @note * behavior is undefined if this method is called after stop() has been * called on this but before the provided callback function has been * called. */ void sta...
...en * called. */ void start(in long port); /** * shuts down this server if it is running (including the period of time after * stop() has been called but before the provided callback has been called). * * @param callback * an asynchronous callback used to notify the user when this server is * stopped and all pending requests have been fully served * @throws ns_
error_null_pointer * if callback is null * @throws ns_
error_unexpected * if this server is not running */ void stop(in nsihttpserverstoppedcallback callback); /** * associates the local file represented by the string file with all requests * which match request. * * @param path * the path which is to be mapped to the given file; must begin with "/" and * be a ...
...And 9 more matches
Signaling and video calling - Web APIs
then the name of the user that was clicked upon is obtained from the event target's textcontent property, and we check to be sure that it's not the same user that's trying to start the call. then we copy the name of the user we're calling into t...
...that for native apps, such as a phone application, you should not begin sending until the connection has been accepted at both ends, at a minimum, to avoid inadvertently sending video and/or audio data when the user isn't prepared for it. as soon as media is attached to the rtcpeerconnection, a negotiationneeded event is triggered at the connection, so that ice negotiation can be started. ...
...on has been accepted at both ends, at a minimum, to avoid inadvertently sending video and/or audio data when the user isn't prepared for it. as soon as media is attached to the rtcpeerconnection, a negotiationneeded event is triggered at the connection, so that ice negotiation can be started. if an
error occurs while trying to get the local media stream, our catch clause calls handlegetusermedia
error(), which displays an appropriate
error to the user as required. ...
...And 9 more matches
Object.create() - JavaScript
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. ...
...wrapper objects. if proto is neither of these a type
error is thrown. custom and null objects a new object created from a completely custom object (especially one created from the null object, which is basically a custom object with no members) can behave in unexpected ways. this is especially true when debugging, since common object-property converting/detecting utility functions may generate
errors, or simply lose information (especially if using silent
error-traps that ignore
errors). for example, here are two objects: oco = object.create( {} ); // create a normal object ocn = object.create( null ); // create a "null" object > console.log(oco) // {} -- seems normal > console.log(ocn) // {} -- seems normal here too, so far oco.p = 1; // create a simple property on normal obj ocn.p = 0...
... = 0; // create a simple property on "null" obj > console.log(oco) // {p: 1} -- still seems normal > console.log(ocn) // {p: 0} -- still seems normal here too. but wait... as shown above, all seems normal so far. ...
...And 9 more matches
Handling common HTML and CSS problems - Learn web development
stently across browsers, which can make some features and styles not work for some users. responsive design problems are also common — a site that looks good in a desktop browser might provide a terrible experience on a mobile device, because the content is too small to read, or perhaps the site is slow because of expensive animations. let's go forth and look at how we can reduce cross browser
errors that result from html/css. first things first: fixing general problems we said in the first article of this series that a good strategy to begin with is to test in a couple of modern browsers on desktop/mobile, to make sure your code is working generally, before going on to concentrate on the cross browser issues. in our debugging html and debugging css articles, we provided some really basic...
...ly, before going on to concentrate on the cross browser issues. in our debugging html and debugging css articles, we provided some really basic guidance on debugging html/css — if you are not familiar with the basics, you should definitely study these articles before carrying on. basically, it is a matter of checking whether your html and css code is well formed and doesn't contain any syntax
errors. note: one common problem with css and html arises when different css rules begin to conflict with one another. this can be especially problematic when you are using third party code. for example, you might use a css framework and find that one of the class names it uses clashes with one you've already used for a different purpose. or you might find that html generated by some kind of third pa...
...s likely. for example .audio-player ul a. validation for html, validation involves making sure all your tags are properly closed and nested, you are using a doctype, and you are using tags for their correct purpose. a good strategy is to validate your code regularly. one service that can do this is the w3c markup validation service, which allows you to point to your code, and returns a list of
errors: css has a similar story — you need to check that your property names are spelled correctly, property values are spelled correctly and are valid for the properties they are used on, you are not missing any curly braces, and so on. the w3c has a css validator available too, for this purpose. linters another good option to choose is a so-called linter application, which not only points out ...
...And 8 more matches
Extending a Protocol
vigator.echo() in your favorite editor, open dom/webidl/navigator.webidl at the end of the file, add: partial interface navigator { [throws] promise<domstring> echo(domstring astring); }; now we need to implement the echo() method in c++, so open up ./dom/base/navigator.h and let's add the method definition, so under public:: already_addrefed<promise> echo(const nsastring& astring,
errorresult& arv); we use nsastring& as the domstring comes in from js as utf-16. this will matter later, as we will need to convert it to utf-8 (using nscstring) to send it to the parent process. now let's implement the method in ./dom/base/navigator.cpp - we add a little bit of
error boilerplate stuff, as is customary: already_addrefed<promise> navigator::echo(const nsastring& astring, erro...
...6. this will matter later, as we will need to convert it to utf-8 (using nscstring) to send it to the parent process. now let's implement the method in ./dom/base/navigator.cpp - we add a little bit of
error boilerplate stuff, as is customary: already_addrefed<promise> navigator::echo(const nsastring& astring,
errorresult& arv) { if (!mwindow || !mwindow->getdocshell()) { arv.throw(ns_
error_unexpected); return nullptr; } refptr<promise> echopromise = promise::create(mwindow->asglobal(), arv); if (ns_warn_if(arv.failed())) { return nullptr; } // message passing magic will happen here! return echopromise.forget(); } ok, let's ./mach build and make sure everything is compiling ok. once it's compiled, ./mach run and you should be able to spin up the developer co...
...otocol level. we've told gecko who manages who, and what messages we want to send. now we actually need to implement the "echochild" and "echoparent" actors to handle sending and receiving messages. and we also need to implement the actual management of these objects by dom/ipc/windowglobalchild.{h|cpp} and dom/ipc/windowglobalparent.{h|cpp}. if we now do ./mach build, it complains that "fatal
error: 'mozilla/dom/echochild.h' file not found". that gives us a good place to start. defining echochild.h create ./dom/ipc/echochild.h, and define it as follows - the inline comments describe what's going on: #ifndef mozilla_dom_echochild_h #define mozilla_dom_echochild_h // we include the protocol, which is automatically generated for us. #include "mozilla/dom/pechochild.h" namespace mozilla {...
...And 8 more matches
PromiseWorker.jsm
have to be return wrapped in this meta object like so: return new promiseworker.meta({ thebuf: abuf, othernontrans: 'this string is not transfered but copied' }, {transfers: [abuf]}); a simple demo showing this in live action can be found here: github :: promiseworker transfer arraybuffer - worker side rejecting the promise to reject the promise from the worker, simply throw. various
error objects are supported; each one has its specific meaning; they're described below. supported built-in javascript
error are following: eval
error internal
error range
error reference
error syntax
error type
error uri
error in addition to them, stopiteration is also supported (note that stopiteration is deprecated). you can also construct and throw your own custom
error objects as needed. wh...
...re supported; each one has its specific meaning; they're described below. supported built-in javascript
error are following: eval
error internal
error range
error reference
error syntax
error type
error uri
error in addition to them, stopiteration is also supported (note that stopiteration is deprecated). you can also construct and throw your own custom
error objects as needed. when custom
error is caught by abstractworker, tomsg method will be called to convert it into message. the tomsg function should return an object which has exn property, that is the property key for the frommsg function in main thread side. // worker // define a custom
error prototype. ...
...ion is deprecated). you can also construct and throw your own custom
error objects as needed. when custom
error is caught by abstractworker, tomsg method will be called to convert it into message. the tomsg function should return an object which has exn property, that is the property key for the frommsg function in main thread side. // worker // define a custom
error prototype. function custom
error(message) { this.message = message; } custom
error.prototype.tomsg = function() { return { exn: 'custom
error', message: this.message, }; }; // a function called by message. function func() { ... // throw a custom
error. ...
...And 8 more matches
Python binding for NSS
ead. also, any "global" values which are set in python-nss are actually thread-local. examples 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...
... to the nss temporary database when they are loaded, but earlier code failed to to that. it's is not likely that an previous code was failing to pass initialization data or the der_is_signed flag so this change should be backwards compatible. fix bug #922247, pkcs12decoder.database_import() method. importing into a nss database would sometimes fail or segfault.
error codes and descriptions were updated from upstream nspr & nss. the password callback did not allow for breaking out of a password prompting loop, now if none is returned from the password callback the password prompting is terminated. nss.nss_shutdown_context now called from initcontext destructor, this assures the context is shutdown even if the programmer forg...
... still best to explicitly shut it down, this is just failsafe. support was added for shutdown callbacks. ...
...And 8 more matches
Shell global objects
..]) load files named by string arguments. filename is relative to the calling script. evaluate(code[, options]) evaluate code as though it were the contents of a file. ...
...e calling script. evaluate(code[, options]) evaluate code as though it were the contents of a file. ...
...ere the contents of a file. ...
...And 8 more matches
Creating the Component Code
code, is expected to return an nsifactory object for a given cid/iid pair. to prepare your component code, you need to create a factory object for each object that you have registered with xpcom. the main function that must be implemented in the nsifactory interface is createinstance. the implementation follows a simple algorithm: create the raw object. if that fails, return an out of memory
error code. call queryinterface on the new object. if that fails, null the out param and free the new object. return the nsresult value from queryinterface. often, you don't have to create the object first because the factory implicitly knows what iids are supported. when this is not the case, however, doing it this way further abstracts the factories from their concrete classes. if you have a fac...
...pported by the concrete base class, for example, then when you go to add a new supported interface you add this iid comparison in both the factory and the queryinterface implementation in the concrete class. ...
...ported interface you add this iid comparison in both the factory and the queryinterface implementation in the concrete class. ns_imethodimp samplefactory::createinstance(nsisupports *aouter, const nsiid & iid, void * *result) { if (!result) return ns_
error_invalid_arg; sample* sample = new sample(); if (!sample) return ns_
error_out_of_memory; nsresult rv = sample->queryinterface(iid, result); if (ns_failed(rv)) { *result = nsnull; delete sample; } return rv; } weblock1.cpp before any of the improvements and xpcom tools we describe in the following chapter are brought in, the source code for the weblock component that implements all the necessary interfaces looks like this. #include <stdio.h> #def...
...And 8 more matches
Debugger.Object - Firefox Developer Tools
this is that function’s script, as a debugger.script instance. if the referent is a function proxy or not debuggee code, this is undefined. environment if the referent is a function that is debuggee code, a debugger.environment instance representing the lexical environment enclosing the function when it was created. if the referent is a function proxy or not debuggee code, this is undefined. ...
...ebugger.script instance. if the referent is a function proxy or not debuggee code, this is undefined. environment if the referent is a function that is debuggee code, a debugger.environment instance representing the lexical environment enclosing the function when it was created. if the referent is a function proxy or not debuggee code, this is undefined.
errormessagename if the referent is an
error created with an engine internal message template this is a string which is the name of the template; undefined otherwise.
errorlinenumber if the referent is an
error object, this is the line number at which the referent was created; undefined otherwise.
errorcolumnnumber if the referent is an
error object, this is the column number at which the referent was created; undefined otherwise. isbo...
... promisestate if the referent is a promise, return a string indicating whether the promise is pending, or has been fulfilled or rejected. this string takes one of the following values: "pending", if the promise is pending. "fulfilled", if the promise has been fulfilled. "rejected", if the promise has been rejected. if the referent is not a promise, throw a type
error. promisevalue return a debuggee value representing the value the promise has been fulfilled with. if the referent is not a promise, or the promise has not been fulfilled, throw a type
error. promisereason return a debuggee value representing the value the promise has been rejected with. if the referent is not a promise, or the promise has not been rejected, throw a type
error. pr...
...And 8 more matches
Debugger - Firefox Developer Tools
n in the debugger are not propagated to debuggee code; instead, spidermonkey calls this function, passingdebugger-exception as its sole argument and the debugger instance as the this value. this function should return a resumption value, which determines how the debuggee should continue. if the uncaught exception hook itself throws an exception,uncaught-hook-exception, spidermonkey throws a new
error object,confess-to-debuggee-exception, to the debuggee whose message blames the debugger, and includes textual descriptions ofuncaught-hook-exception and the originaldebugger-exception. if uncaughtexceptionhook’s value is null, spidermonkey throws an exception to the debuggee whose message blames the debugger, and includes a textual description ofdebugger-exception. assigning anything other ...
... message blames the debugger, and includes textual descriptions ofuncaught-hook-exception and the originaldebugger-exception. if uncaughtexceptionhook’s value is null, spidermonkey throws an exception to the debuggee whose message blames the debugger, and includes a textual description ofdebugger-exception. ...
...is property throws a type
error exception. (this is not an ideal way to handle debugger bugs, but the hope here is that some sort of backstop, even if imperfect, will make life easier for debugger developers. for example, an uncaught exception hook may have access to browser-level features like the alert function, which this api’s implementation does not, making it possible to present debugger
errors to the developer in a way suited to the context.) debugger handler functions each debugger instance inherits accessor properties with which you can store handler functions for spidermonkey to call when given events occur in debuggee code. when one of the events described below occurs in debuggee code, the engine pauses the debuggee and calls the corresponding debugging handler on each debu...
...And 8 more matches
PaymentResponse.retry() - Web APIs
the paymentresponse interface's retry() method makes it possible to ask the user to retry a payment after an
error occurs during processing. this lets your app gracefully deal with situations such as invalid shipping addresses or declined credit cards. syntax retrypromise = paymentrequest.retry(
errorfields); parameters
errorfields a paymentvalidation
errors object, with the following properties:
error optional a general description of a payment
error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. ...
...invalid shipping addresses or declined credit cards. syntax retrypromise = paymentrequest.retry(
errorfields); parameters
errorfields a paymentvalidation
errors object, with the following properties:
error optional a general description of a payment
error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information.
error can be provided all by itself to provide only a generic
error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to
errors in specific fields in the payment form. payer optional a payer
errors compliant object which provides appropriate
error messages for any of the fields describing the payer which failed validation. paymentmet...
...only a generic
error message, or in concert with the other properties to serve as an overview while other properties' values gude the user to
errors in specific fields in the payment form. payer optional a payer
errors compliant object which provides appropriate
error messages for any of the fields describing the payer which failed validation. paymentmethod optional any payment method specific
errors which may have occurred. this object's contents will vary depending on the payment used. for example, if the user chose to pay by credit card using the basic-card payment method, this is a basiccard
errors object. shippingaddress optional an address
errors object which contains
error messages for any of the fields in the shipping address that failed validation. return value a promise w...
...And 8 more matches
constructor - JavaScript
ovide your own constructor, then a default constructor will be supplied for you. ...
... constructor, then a default constructor will be supplied for you. ...
...nstructor() {} if your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided: constructor(...args) { super(...args); } that enables code like this to work: class validation
error extends
error { printcustomermessage() { return `validation failed :-( (details: ${this.message})`; } } try { throw new validation
error("not a valid phone number"); } catch (
error) { if (
error instanceof validation
error) { console.log(
error.name); // this is
error instead of validation
error! console.log(
error.printcustomermessage()); } else { console.log('unknown
error',
error); throw
error; } } the validation
error class doesn't need an explicit constructor, because it doesn't need to do any custom initial...
...And 8 more matches
test/assert - Archive of obsolete content
ween 1 and '1'"); } // this test will pass, because the types are 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. 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. to check that the exception thrown contains a specific message, pass a regular expression here: the...
...wn is of the expected type, pass a constructor function: the exception thrown must be an instance of the object returned by that function. ...
... constructor function: the exception thrown must be an instance of the object returned by that function. ...
...And 7 more matches
Return Codes - Archive of obsolete content
e files were installed, but one or more components were in use. restart the computer and the application to complete the installation process. on windows nt, you may only need to restart the application as long as you did not replace operating system files. ...
... components were in use. restart the computer and the application to complete the installation process. on windows nt, you may only need to restart the application as long as you did not replace operating system files. bad_package_name -200 a problem occurred with the package name supplied to initinstall unexpected_
error -201 an unrecognized
error occurred. ...
...cation as long as you did not replace operating system files. bad_package_name -200 a problem occurred with the package name supplied to initinstall unexpected_
error -201 an unrecognized
error occurred. access_denied -202 the user (or the os) did not grant the required security privilege. execution_
error -203 an
error occurred executing the script no_install_script -204 installation script was not signed no_certificate -205 extracted file is not signed or the file (and, therefore, its certificate) could not be found. no_matching_certificate -206 extracted file was not signed by the certificate used to ...
...And 7 more matches
CSS and JavaScript accessibility best practices - Learn web development
be used to access it if javascript is not available (the default <video> browser controls aren't keyboard accessible in most browsers). as an example, we've written a quick and dirty client-side form validation example — see form-validation.html (also see the demo live). here you'll see a simple form; when you try to submit the form with one or both fields left empty, the submit fails, and an
error message box appears to tell you what is wrong. this kind of form validation is unobtrusive — you can still use the form absolutely fine without the javascript being available, and any sensible form implementation will have server-side validation active as well, because it is too easy for malicious users to bypass client-side validation (for example, by turning javascript off in the browser). t...
...orm validation is unobtrusive — you can still use the form absolutely fine without the javascript being available, and any sensible form implementation will have server-side validation active as well, because it is too easy for malicious users to bypass client-side validation (for example, by turning javascript off in the browser). the client-side validation is still really useful for reporting
errors — users can know about mistakes they make instantly, rather than having to wait for a round trip to the server and a page reload. this is a definite usability advantage. note: server-side validation has not been implemented in this simple demo. we've made this form validation pretty accessible too. we've used <label> elements to make sure the form labels are unambiguously linked to their i...
...re unambiguously linked to their inputs, so screen readers can read them out alongside: <label for="name">enter your name:</label> <input type="text" name="name" id="name"> we only do the validation when the form is submitted — this is so that we don't update the ui too often and potentially confuse screen reader (and possibly other) users: form.onsubmit = validate; function validate(e) {
errorlist.innerhtml = ''; for(let i = 0; i < formitems.length; i++) { const testitem = formitems[i]; if(testitem.input.value === '') {
errorfield.style.left = '360px'; createlink(testitem); } } if(
errorlist.innerhtml !== '') { e.preventdefault(); } } note: in this example, we are hiding and showing the
error message box using absolute positioning rather than anoth...
...And 7 more matches
Introduction to automated testing - Learn web development
f node and npm: node -v npm -v if you've got node/npm already installed, you should update them to their latest versions. to update node, the most reliable way is to download and install an updated installer package from their website (see link above). to update npm, use the following command in your terminal: npm install npm@latest -g note: if the above command fails with permissions
errors, fixing npm permissions should sort you out. to start using node/npm-based packages on your projects, you need to set up your project directories as npm projects. this is easy to do. for example, let's first create a test directory to allow us to play without fear of breaking anything. create a new directory somewhere sensible using your file manager ui, or, on a command line, by navigatin...
...ning the actual code to run to complete the task. you can run your gulp task with the following commands — try this now: gulp adding some real tasks to gulp to add some real tasks to gulp, we need to think about what we want to do. a reasonable set of basic functionalities to run on our project is as follows: html-tidy, css-lint, and js-hint to lint and report/fix common html/css/js
errors (see gulp-htmltidy, gulp-csslint, gulp-jshint). autoprefixer to scan our css and add vendor prefixes only where needed (see gulp-autoprefixer). babel to transpile any new javascript syntax features to traditional syntax that works in older browsers (see gulp-babel). see the links above for full instructions on the different gulp packages we are using. to use each plugin, you need to first i...
... .pipe(gulp.dest('build')); cb(); } here we are grabbing our development index.html file with gulp.src(), which allows us to grab a source file to do something with. we next use the pipe() function to pass that source to another command to do something else with. we can chain as many of these together as we want. we first run htmltidy() on the source, which goes through and fixes
errors in our file. the second pipe() function writes the output html file to the build directory. in the input version of the file, you may have noticed that we put an empty <p> element; htmltidy has removed this by the time the output file has been created. autoprefixer and css-lint install using the following lines: npm install --save-dev gulp-autoprefixer npm install --save-dev gulp-csslint ...
...And 7 more matches
Promise
promises may also be created using the new promise() constructor. ...
... already have a reference. internally, a promise can be in one of three states: pending, when the final value is not available yet. this is the only state that may transition to one of the other two states. fulfilled, 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 ...
... documentation conventions in documentation, the type of the fulfillment value is usually specified between angular brackets. ...
...And 7 more matches
Sqlite.jsm
many milliseconds of connection idle. the connection is idle when no statements are executing. there is no default value which means no automatic memory minimization will occur. please note that this is not a timer on the idle service and this could fire while the application is active. ...
...} working with opened connections opened connections are what you will interface most with in sqlite.jsm. the following sections detail the api of an opened connection instance. ...
...} working with opened connections opened connections are what you will interface most with in sqlite.jsm. the following sections detail the api of an opened connection instance. connection management these apis are used to manage and inspect the state of the connection. close() close this database connection. ...
...And 7 more matches
nsILocalFile
h 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 security reasons, this can...
...rator 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 which the descripto...
... 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, full path to a file or ...
...And 7 more matches
Streams - Plugins
owser calls the npp_newstream method. this method also determines which mode it should use to send data to the plug-in. the browser can create a stream for several different types of data: for the file specified in the data attribute of the object element or the src attribute of the embed element for a data file for a full-page instance the npp_newstream method has the following syntax: np
error npp_newstream(npp instance, npmimetype type, npstream *stream, npbool seekable, uint16* stype); the instance parameter refers to the plug-in instance receiving the stream; the type parameter represents the stream's mime type. the stream parameter is a pointer to the new stream, which is valid until the stream is destroyed. the seekable parameter specifies whether the stream is seekable (true...
...wser deletes the npstream object. the plug-in can terminate the stream itself by calling npn_destroystream. you should delete any private data allocated in the plug-in's stream->pdata field when you destroy a stream. the plug-in can store private data associated with the stream in stream->pdata. the browser stores private data in stream->ndata; this value should not be changed by the plug-in. np
error npp_destroystream(npp instance, npstream *stream, np
error reason); the instance parameter is the current plug-in instance; the stream parameter specifies the stream to be deleted. the reason parameter specifies why the stream was destroyed. it can have one of these values: npres_done (most common): normal completion; all data was sent to the instance. npres_user_break: the user canceled t...
... it can have one of these values: npres_done (most common): normal completion; all data was sent to the instance. npres_user_break: the user canceled the stream directly by clicking the stop button or indirectly by some action, such as by deleting the instance or initiating higher-priority network operations. npres_network_err: the stream failed because of problems with the network, disk i/o
error, lack of memory, or some other problem. finding out how much data the plug-in can accept after a call to npp_newstream and before writing data to the plug-in, the browser calls npp_writeready to determine the maximum number of bytes that the plug-in can consume. this function allows the browser to send only as much data to the instance as it can handle at one time, and it helps both the browse...
...And 7 more matches
Debugger.Script - Firefox Developer Tools
able or property. thus, we use a/b to refer to theb defined withina, and a< to refer to a function that occurs somewhere within an expression that is assigned toa. for example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< if the instance refers to webassembly code, throw a type
error. url if the instance refers to a jsscript, the filename or url from which this script’s code was loaded. for scripts created by eval or the function constructor, this may be a synthesized filename, starting with a valid url and followed by information tracking how the code was introduced into the system; the entire string is not a valid url. for function.prototype’s script, this is null...
...nction constructor, this may be a synthesized filename, starting with a valid url and followed by information tracking how the code was introduced into the system; the entire string is not a valid url. for function.prototype’s script, this is null. if this debugger.script’s source property is non-null, then this is equal to source.url. if the instance refers to webassembly code, throw a type
error. startline if the instance refers to a jsscript, the number of the line at which this script’s code starts, within the file or document named by url. linecount if the instance refers to a jsscript, the number of lines this script’s code occupies, within the file or document named by url. source if the instance refers to a jsscript, the debugger.source instance representing the sourc...
...presenting the serialized text format of the webassembly code. sourcestart if the instance refers to a jsscript, the character within the debugger.source instance given by source at which this script’s code starts; zero-based. if this is a function’s script, this is the index of the start of the function token in the source code. if the instance refers to webassembly code, throw a type
error. sourcelength if the instance refers to a jsscript, the length, in characters, of this script’s code within the debugger.source instance given by source. if the instance refers to webassembly code, throw a type
error. global if the instance refers to a jsscript, a debugger.object instance referring to the global object in whose scope this script runs. the result refers to the globa...
...And 7 more matches
Console messages - Firefox Developer Tools
h message is displayed as a separate row: time the time the message was recorded. this is not shown by default: you can opt to see timestamps by selecting show timestamps in the console settings menu (gear icon in the console toolbar). icon not all console messages contain icons. ...
... filename and line number for javascript, css and console api messages, the message can be traced to a specific line of code. ...
...ying the url into the clipboard open in network panel switches context to the network tab, selects the request and shows you the details resend request sends the network request again. open url in new tab opens the url in a new browser tab. if the resource is an image, the image will be opened in a new tab. if the resource is a stylesheet, you will see the css rules, etc. ...
...And 7 more matches
FileSystemDirectoryEntry.getDirectory() - Web APIs
the filesystemdirectoryentry interface's method getdirectory() returns a filesystemdirectoryentry object corresponding to a directory contained somewhere within the directory subtree rooted at the directory on which it's called. syntax filesystemdirectoryentry.getdirectory([path][, options][, successcallback][,
errorcallback]); parameters path optional a usvstring representing an absolute path or a path relative to the directory on which the method is called, describing which directory entry to return. absolute paths may not be able to be used, for security reasons. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an
error if the file already exists. these options are curren...
...ich allows you to specify whether or not to create the entry if it's missing and if it's an
error if the file already exists. these options are currently not useful in web contexts. successcallback optional a method to be called once the filesystemdirectoryentry has been created. the method receives a single parameter: the filesystemdirectoryentry object representing the directory in question.
errorcallback optional a method to be called if an
error occurs. receives as its sole input parameter a file
error object describing the
error which occurred. return value undefined. ...
...esscallback optional a method to be called once the filesystemdirectoryentry has been created. the method receives a single parameter: the filesystemdirectoryentry object representing the directory in question.
errorcallback optional a method to be called if an
error occurs. receives as its sole input parameter a file
error object describing the
error which occurred. return value undefined.
errors if an
error occurs and an
errorcallback was specified, it gets called with a single parameter: a file
error object describing the
error. ...
...And 7 more matches
FileSystemDirectoryEntry.getFile() - Web APIs
} the filesystemdirectoryentry interface's method getfile() returns a filesystemfileentry object corresponding to a file contained somewhere within the directory subtree rooted at the directory on which it's called. syntax filesystemdirectoryentry.getfile([path][, options][, successcallback][,
errorcallback]); parameters path optional a usvstring specifying the path, relative to the directory on which the method is called, describing which file's entry to return. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an
error if the file already exists. these options are currently not useful in web contexts. successcallback optional a method to be called once the filesystemfileen...
... dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an
error if the file already exists. these options are currently not useful in web contexts. successcallback optional a method to be called once the filesystemfileentry has been created. the method receives a single parameter: the filesystemfileentry object representing the file in question.
errorcallback optional a method to be called if an
error occurs. receives as its sole input parameter a file
error object describing the
error which occurred. return value undefined. ...
...contexts. successcallback optional a method to be called once the filesystemfileentry has been created. the method receives a single parameter: the filesystemfileentry object representing the file in question.
errorcallback optional a method to be called if an
error occurs. receives as its sole input parameter a file
error object describing the
error which occurred. return value undefined.
errors if an
error occurs and an
errorcallback was specified, it gets called with a single parameter: a file
error object describing the
error. ...
...And 7 more matches
FileSystemDirectoryEntry.removeRecursively() - Web APIs
the filesystemdirectoryentry interface's method removerecursively() removes the directory as well as all of its content, hierarchically iterating over its entire subtree of descendant files and directories. to remove a single file, or an empty directory, you can also use filesystementry.remove(). ...
... hierarchically iterating over its entire subtree of descendant files and directories. to remove a single file, or an empty directory, you can also use filesystementry.remove(). syntax filesystemdirectoryentry.removerecursively(successcallback[,
errorcallback]); parameters successcallback a function to call once the directory removal process has completed. the callback has no parameters.
errorcallback optional a function to be called if an
error occurs while attempting to remove the directory subtree. ...
...ry, you can also use filesystementry.remove(). syntax filesystemdirectoryentry.removerecursively(successcallback[,
errorcallback]); parameters successcallback a function to call once the directory removal process has completed. the callback has no parameters.
errorcallback optional a function to be called if an
error occurs while attempting to remove the directory subtree. receives a file
error describing the
error which occurred as input. return value undefined.
errors if an
error occurs and an
errorcallback was specified, it gets called with a single parameter: a file
error object describing the
error. ...
...And 7 more matches
Capabilities, constraints, and settings - Web APIs
code needs to know whether or not an api exists and if so, what its limitations are on the user agent it's running on. figuring this out has often been difficult, and has usually involved looking at some combination of which user agent (or browser) you're running on, which version it is, looking to see if certain objects exist, trying to see whether various things work or not and determining what
errors occur, and so forth. the result has been a lot of very fragile code, or a reliance on libraries which figure this stuff out for you, then implement polyfills to patch the holes in the implementation on your behalf. the twin concepts of constraints and capabilities let the browser and web site or app exchange information about what constrainable properties the browser's implementation supports a...
...e within the range, if you choose. if you provide an ideal value, the browser will try to get as close as possible to matching that value, given the other constraints specified. let supports = navigator.mediadevices.getsupportedconstraints(); if (!supports["width"] || !supports["height"] || !supports["framerate"] || !supports["facingmode"]) { // we're missing needed properties, so handle that
error. } else { let constraints = { width: { min: 640, ideal: 1920, max: 1920 }, height: { min: 400, ideal: 1080 }, aspectratio: 1.777777778, framerate: { max: 30 }, facingmode: { exact: "user" } }; mytrack.applyconstraints(constraints).then(function() => { /* do stuff if constraints applied successfully */ }).catch(function(reason) { /* failed to apply constraints;...
... you can specify one or more media input device ids to establish restrictions on which input sources are allowed. to collect a list of the available devices, you can call navigator.mediadevices.enumeratedevices(), then for each device which meets the desired crite...
...And 7 more matches
PaymentRequest.show() - Web APIs
reasons, the paymentrequest.show() method can't just be initiated at any time. it may only be called while handling events that represent user interactions, such as click, keyup, or the like. only one payment request can be in the process of being handled at once, across all documents. once one paymentrequest's show() method has been called, any other call to show() will by rejected with an abort
error until the returned promise has been concluded, either by being fulfilled with a paymentresponse indicating the results of the payment request, or by being rejected with an
error. note: in reality, despite the fact that the specification says this can't be done, some browsers, including firefox, support multiple active payment requests at a time. if your architecture doesn't necessarily have a...
...ating 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). ...
...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). ...
...And 7 more matches
Sensor APIs - Web APIs
in window) { // watch out! } if (window.ambientlightsensor) { // go dark... } defensive programming as stated in feature detection, checking for a particular sensor api is insufficient for feature detection. the existence of an actual sensor must be confirmed as well. this is where defensive programming is needed. defensive programming requires three strategies. checking for thrown
errors when instantiating a sensor object. listening for
errors thrown during its use. handling the
errors gracefully so that the user experience is enhanced rather than degraded. the code example below illustrates these principles. the try...catch block catches
errors thrown during sensor instantiation. it implements a handler for sensor.on
error to catch
errors thrown during use. the only time any...
...t supported by the device. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
...icy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. let accelerometer = null; try { accelerometer = new accelerometer({ referenceframe: 'device' }); accelerometer.addeventlistener('
error', event => { // handle runtime
errors. ...
...And 7 more matches
Web APIs
wport wweb animationsweb audio apiweb authentication apiweb crypto apiweb notificationsweb storage apiweb workers apiwebglwebrtcwebvttwebxr device apiwebsockets api interfaces this is a list of all the interfaces (that is, types of objects) that are available. ...
...e client 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 dom
error domexception 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 deprecationreportbo...
...dynamicscompressornode e ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_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 file
error fileexception filelist filereader filereadersync filerequest filesystem filesystemdirectoryentry filesystemdirectoryreader filesystementry filesystementrysync filesystemfileentry filesystemflags filesystems...
...And 7 more matches
HTTP response status codes - HTTP
the below status codes are defined by section 10 of rfc 2616. you can find an updated specification in rfc 7231. if you receive a response that is not in this list, it is a non-standard response, possibly custom to the server's software. ...
... the below status codes are defined by section 10 of rfc 2616. you can find an updated specification in rfc 7231. if you receive a response that is not in this list, it is a non-standard response, possibly custom to the server's software. ...
...quest. 308 permanent redirect this means that the resource is now permanently located at another uri, specified by the location: http response header. this has the same semantics as the 301 moved permanently http response code, with the exception that the user agent must not change the http method used: if a post was used in the first request, a post must be used in the second 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". that is, the client must authenticate itself to get the requested response. 402 payment required this response code is reserved for future use. the initial aim for creating t...
...And 7 more matches
Promise.prototype.then() - JavaScript
success and failure cases of the promise. the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. if one or both arguments are omitted or are provided non-functions, then then will be missing the handler(s), but will not generate any
errors. if the promise that then is called on adopts a state (fulfillment or rejection) for which then has no handler, the returned promise simply adopts the final state of the original promise on which then was called. syntax p.then(onfulfilled[, onrejected]); p.then(value => { // fulfillment }, reason => { // rejection }); parameters onfulfilled optional a function called if the promise...
...se is fulfilled. this function has one argument, the fulfillment value. if it is not a function, it is internally replaced with an "identity" function (it returns the received argument). onrejected optional a function called if the promise is rejected. this function has one argument, the rejection reason. if it is not a function, it is internally replaced with a "thrower" function (it throws an
error it received as argument). return value once a promise is fulfilled or rejected, the respective handler function (onfulfilled or onrejected) will be called asynchronously (scheduled in the current thread loop). the behavior of the handler function follows a specific set of rules. if a handler function: returns a value, the promise returned by then gets resolved with the returned value as its...
...on (onfulfilled or onrejected) will be called asynchronously (scheduled in the current thread loop). the behavior of the handler function follows a specific set of rules. if a handler function: returns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an undefined value. throws an
error, the promise returned by then gets rejected with the thrown
error as its value. returns an already fulfilled promise, the promise returned by then gets fulfilled with that promise's value as its value. returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value. returns another pending promise object, the resolution/rejection of the pr...
...And 7 more matches
Optional chaining (?.) - JavaScript
the optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. the ?. operator functions similarly to the . chaining operator, except that instead of causing an
error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. when used with function calls, it returns undefined if the given function does not exist. this results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. it can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required. the source for...
...undefined or null. for example, consider an object obj which has a nested structure. without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as: let nestedprop = obj.first && obj.first.second; the value of obj.first is confirmed to be non-null (and non-undefined) before then accessing the value of obj.first.second. this prevents the
error that would occur if you simply accessed obj.first.second directly without testing obj.first. with the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second: let nestedprop = obj.first?.second; by using the ?. operator instead of just ., javascript knows to implicitly check to be sur...
... 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 type
error exception (someinterface.custommethod is not a function). note: if someinterface itself is null or undefined, a type
error exception will still be raised (someinterface is null). if you expect that someinterface itself may be null or undefined, you have to use ?. at this position as well: someinterface?.custommethod?.() dealing with optional callbacks or event handlers if you use callbacks o...
...And 7 more matches
Exception logging in JavaScript - Archive of obsolete content
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. ...
...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. ...
...ptions were dutifully logged nonetheless. ...
...And 6 more matches
Twitter - Archive of obsolete content
to define this object. the first is simple: define properties on the object corresponding to the parameters of the twitter method. for instance, some twitter methods have an id parameter, so you would define an id property and set its value to a user's id. (you can read about the parameters of the various methods at twitter's api reference.) there are two special, optional properties: success and
error. ...
...g to the parameters of the twitter method. for instance, some twitter methods have an id parameter, so you would define an id property and set its value to a user's id. (you can read about the parameters of the various methods at twitter's api reference.) there are two special, optional properties: success and
error. success is a function that's called when the request successfully completes, and
error is a function called when it fails to complete. the library simply passes them to jquery.ajax(), and so they are called like so: success(data, textstatus) data is twitter's decoded json response. 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 o...
... the examples below all use this first, simpler style. ...
...And 6 more matches
How to implement a custom autocomplete search component
'); const class_id = components.id('x753d830-ba1e-11e0-962b-0800200c9a66'); // ← change this const class_name = "basic autocomplete"; const contract_id = '@mozilla.org/autocomplete/search;1?name=basic-autocomplete'; /** * @constructor * * @implements {nsiautocompleteresult} * * @param {string} searchstring * @param {number} searchresult * @param {number} defaultindex * @param {string}
errordescription * @param {array.<string>} results * @param {array.<string>|null=} comments */ function providerautocompleteresult(searchstring, searchresult, defaultindex,
errordescription, results, comments) { this._searchstring = searchstring; this._searchresult = searchresult; this._defaultindex = defaultindex; this._
errordescription =
errordescription; this._results = results; thi...
...rchstring, searchresult, defaultindex,
errordescription, results, comments) { this._searchstring = searchstring; this._searchresult = searchresult; this._defaultindex = defaultindex; this._
errordescription =
errordescription; this._results = results; this._comments = comments; } providerautocompleteresult.prototype = { _searchstring: "", _searchresult: 0, _defaultindex: 0, _
errordescription: "", _results: [], _comments: [], /** * @return {string} the original search string */ get searchstring() { return this._searchstring; }, /** * @return {number} the result code of this result object, either: * result_ignored (invalid searchstring) * result_failure (failure) * result_nomatch (no matches found) * result_success (matc...
...esult_nomatch (no matches found) * result_success (matches found) */ get searchresult() { return this._searchresult; }, /** * @return {number} the index of the default item that should be entered if * none is selected */ get defaultindex() { return this._defaultindex; }, /** * @return {string} description of the cause of a search failure */ get
errordescription() { return this._
errordescription; }, /** * @return {number} the number of matches */ get matchcount() { return this._results.length; }, /** * @return {string} the value of the result at the given index */ getvalueat: function(index) { return this._results[index]; }, /** * @return {string} the comment of the result at the given index */ ...
...And 6 more matches
FxAccountsProfileClient.jsm
server url. token - firefox accounts oauth bearer token. return value a newly created fxaccountsprofileclient object implementing the methods described in this article. methods fetchprofile() fetches firefox accounts profile information. parameters none return value promise resolves: object - successful response from the '/profile' endpoint. ...
...irefox accounts oauth bearer token. return value a newly created fxaccountsprofileclient object implementing the methods described in this article. methods fetchprofile() fetches firefox accounts profile information. parameters none return value promise resolves: object - successful response from the '/profile' endpoint. rejects: fxaccountsprofileclient
error - profile client
error. examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile));
error handling the fxaccountsprofileclient.jsm normalizes request and client
errors into fxaccountsprofileclient
error object. fxaccountsprofi...
...les using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile));
error handling the fxaccountsprofileclient.jsm normalizes request and client
errors into fxaccountsprofileclient
error object. ...
...And 6 more matches
NSS 3.12.4 release notes
ed. expressions inside unions may not include unions or exclusions. inside a union, to be matched and not treated as a special character, these characters must be escaped: \ ( | ) [ ~ except when they occur inside a bracketed expression, where only \ and ] require escaping. new functions in the nss shared library: pk11_isinternalkeyslot (see pk11pub.h) secmod_opennewslot (see pk11pub.h) new
error codes (see secerr.h): sec_
error_bad_info_access_method sec_
error_crl_import_failed new oids (see secoidt.h) sec_oid_x509_any_policy the nssckbi pkcs #11 module's version changed to 1.75. obsolete code for win16 has been removed. support for openvms has been removed. bugs fixed the following bugs have been fixed in nss 3.12.4. bug 321755: implement crldistributionpoint extension in li...
...5. obsolete code for win16 has been removed. support for openvms has been removed. bugs fixed the following bugs have been fixed in nss 3.12.4. ...
...bug 470500: firefox 3.1b2 crash report [[@ nssutil3.dll@0x34c0 ] bug 482742: enable building util independently of the rest of nss bug 483653: unable to build certutil.exe...
...And 6 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
nss sample code 3: basic encryption and macing this example program demonstrates how to encrypt and mac a file. ...
...tderr, "%-7s as input files and produces <opfilename> as a final output file.\n\n", ""); exit(-1); } /* this source code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
... "could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { pr_fprintf(pr_stderr, "pk11_findfixedkey failed (err %d)\n", pr_get
error()); pk11_freeslot(slot); return null; } return key; } /* * decrypt and verify mac */ secstatus decryptandverifymac( const char* outfilename, char *encryptedfilename, secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsi...
...And 6 more matches
The Publicity Stream API
doable?] the javascript library should be included from: https://myapps.mozillalabs.com/jsapi/publicity.js all apis related to open web applications are accessed under the navigator.apps object. publicity stream api (navigator.apps.publicity.*) the publicity api is exposed as properties on the navigator.apps.publicity object. publicizeactivity( <activity>, [ { [ onsuccess: <function> ], [ on
error: <function> ] } ]): applications should call this method when an user-initiated activity deemed attractive to potential consumers occurs. this spawns a doorhanger which allows the user to specify which users can view the activity, and (following successful login and authorization with the stream server) registers the activity in a stream at [address]. this stream can be pulled down by getpublic...
...blicitystream() and helps determine the results for getuserrecommendedapps(). example use cases: 'adam got a high score in mafia wars', 'bethany bought a plane ticket to the caribbean', etc. activity is an object, formatted as per the fixme: deadlinkactivity streams open specification. onsuccess is a callback that will be invoked with no arguments if the activity is successfully posted. ...
...m() and helps determine the results for getuserrecommendedapps(). example use cases: 'adam got a high score in mafia wars', 'bethany bought a plane ticket to the caribbean', etc. activity is an object, formatted as per the fixme: deadlinkactivity streams open specification. onsuccess is a callback that will be invoked with no arguments if the activity is successfully posted. ...
...And 6 more matches
nsIConsoleService
xpcom/base/nsiconsoleservice.idlscriptable the console service is the back-end for the
error console, bundled with every mozilla application, and for firefox's web console and browser console. it is used to log various messages, warnings, and
errors and to obtain the logged messages. inherits from: nsisupports last changed in gecko 19 (firefox 19 / thunderbird 19 / seamonkey 2.16) implemented by: @mozilla.org/consoleservice;1 as a service: var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); method overview void getmessagearray([array, size_is(count)] out nsiconsolemessage messages, out uint32_t count);obsolete since gecko 19 void getmessagearray([optional] out uint32...
...e code samples below for how to call getmessagearray. logmessage() void logmessage( in nsiconsolemessage message ); parameters message the nsiconsolemessage to log. logstringmessage() a convenient method for logging simple messages. void logstringmessage( in wstring message ); parameters message the string to log. registerlistener() registers a listener, to notify when an
error is logged. note: to guard against stack overflows from listeners which could log messages (this could be done inadvertently through listeners implemented in javascript), we do not call any listeners when another
error is already being logged. void registerlistener( in nsiconsolelistener listener ); parameters listener the nsiconsolelistener to add. reset() to clear the message buffer...
... function mylogtoconsole(amessage, asourcename, asourceline, alinenumber, acolumnnumber, afla...
...And 6 more matches
Using the Geolocation API - Web APIs
ing the current position to obtain the user's current location, you can call the getcurrentposition() method. this initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. when the position is determined, the defined callback function is executed. you can optionally provide a second callback function to be executed if an
error occurs. a third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position. note: by default, getcurrentposition() tries to answer as fast as possible with a low accuracy result. it is useful if you need a quick answer regardless of the accuracy. devices with a gps, for exam...
...can set up a callback function that is called with that updated position information. this is done using the watchposition() function, which has the same input parameters as getcurrentposition(). the callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. the
error callback function, which is optional just as it is for getcurrentposition(), can be called repeatedly. note: you can use watchposition() without an initial getcurrentposition() call. const watchid = navigator.geolocation.watchposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the watchposition() method returns an id number that can be used to uni...
...tion.coords.longitude); }); the watchposition() method returns an id number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the clearwatch() method to stop watching the user's location. navigator.geolocation.clearwatch(watchid); fine tuning the response both getcurrentposition() and watchposition() accept a success callback, an optional
error callback, and an optional positionoptions object. this object allows you to specify whether to enable high accuracy, a maximum age for the returned position value (up until this age it will be cached and reused if the same position is requested again; after this the browser will request fresh position data), and a timeout value that dictates how long the browser should attempt to get the positio...
...And 6 more matches
IDBTransaction - Web APIs
de is executed the object store should contain the value "2", since trans2 should run after trans1. transaction failures transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback: abort due to bad requests, e.g. 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 agen...
... reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction. properties idbtransaction.db read only the database connection with which this transaction is associated. idbtransaction.
error read only returns a domexception 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 tran...
...n. the default value is readonly. idbtransaction.objectstorenames read only returns a domstringlist of the names of idbobjectstore objects associated with the transaction. methods inherits from: eventtarget idbtransaction.abort() rolls back all the changes to objects in the database associated with this transaction. if this transaction has been aborted or completed, this method fires an
error event. idbtransaction.objectstore() returns an idbobjectstore object representing an object store that is part of the scope of this transaction. idbtransaction.commit() for an active transaction, commits the transaction. note that this doesn't normally have to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been ...
...And 6 more matches
LocalFileSystem - Web APIs
punged by the browser at any time. to use persistent storage with the file system api, chrome exposes a requestquota api. so to request storage, you need to do something like the following: var requestedbytes = 1024*1024*10; // 10mb navigator.webkitpersistentstorage.requestquota ( requestedbytes, function(grantedbytes) { window.requestfilesystem(persistent, grantedbytes, oninitfs,
errorhandler); }, function(e) { console.log('
error', e); } ); your user must grant your app permission to store data locally before your app can use persistent storage. once your user grants it, you don't need to call requestquota() again. subsequent calls are a noop. another api, the quota management api, lets you query an origin's current quota usage and allocation using window.webkitpersiste...
...lowing is a code snippet that shows how you can request a file system storage. ...
...equest a file system storage. //taking care of the browser-specific prefix window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success callback // and the last one is the
error callback // for denial of access and other
errors. ...
...And 6 more matches
RTCPeerConnection - Web APIs
vely gathering candidates—changes.onidentityresult the rtcpeerconnection.onidentityresult event handler is a property containing the code to execute when the identityresult event, of type rtcidentityevent, is received by this rtcpeerconnection. ...
...ityresult the rtcpeerconnection.onidentityresult event handler is a property containing the code to execute when the identityresult event, of type rtcidentityevent, is received by this rtcpeerconnection. ...
...g the code to execute when the identityresult event, of type rtcidentityevent, is received by this rtcpeerconnection. such an event is sent when an identity assertion is generated, via getidentityassertion() or during the creation of an offer or an answer.onidpassertion
error the rtcpeerconnection.onidpassertion
error event handler is a property containing the code to execute whent the idpassertion
error event, of type rtcidentity
errorevent, is received by this rtcpeerconnection. ...
...And 6 more matches
Using the Web Speech API - Web APIs
string, set the background color to that color, and report the color recognised as a diagnostic message in the ui. we also use a speechrecognition.onspeechend handler to stop the speech recognition service from running (using speechrecognition.stop()) once a single word has been recognised and it has finished being spoken: recognition.onspeechend = function() { recognition.stop(); } handling
errors and unrecognised speech the last two handlers are there to handle cases where speech was recognised that wasn't in the defined grammar, or an
error occured. speechrecognition.onnomatch seems to be supposed to handle the first case mentioned, although note that at the moment it doesn't seem to fire correctly; it just returns whatever was recognised anyway: recognition.onnomatch = function(event...
... was recognised that wasn't in the defined grammar, or an
error occured. ...
...ammar, or an
error occured. ...
...And 6 more matches
Synchronous and asynchronous requests - Web APIs
he browser continue to work as normal while your request is being handled. example: send a file to the console log this is the simplest usage of asynchronous xmlhttprequest. var xhr = new xmlhttprequest(); xhr.open("get", "/bar/foo.txt", true); xhr.onload = function (e) { if (xhr.readystate === 4) { if (xhr.status === 200) { console.log(xhr.responsetext); } else { console.
error(xhr.statustext); } } }; xhr.on
error = function (e) { console.
error(xhr.statustext); }; xhr.send(null); line 2 specifies true for its third parameter to indicate that the request should be handled asynchronously. line 3 creates an event handler function object and assigns it to the request's onload attribute. this handler looks at the request's readystate to see if the transaction is co...
...nd(null); line 2 specifies true for its third parameter to indicate that the request should be handled asynchronously. line 3 creates an event handler function object and assigns it to the request's onload attribute. this handler looks at the request's readystate to see if the transaction is complete in line 4; if it is, and the http status is 200, the handler dumps the received content. if an
error occurred, an
error message is displayed. line 15 actually initiates the request. the callback routine is called whenever the state of the request changes. example: writing a function to read an external file in some cases, you must read many external files. this is a standard function which uses the xmlhttprequest object asynchronously in order to switch the content of the read file to a speci...
...e is called whenever the state of the request changes. example: writing a function to read an external file in some cases, you must read many external files. this is a standard function which uses the xmlhttprequest object asynchronously in order to switch the content of the read file to a specified listener. ...
...And 6 more matches
Comparing Reflect and Object methods - JavaScript
vior, there are often subtle differences between them. the table below details the differences between the methods available on the object and reflect apis. please note that if a method does not exist in an api, it is marked as n/a. method name object reflect defineproperty() object.defineproperty() returns the object that was passed to the function. returns a type
error if the property was not successfully defined on the object. reflect.defineproperty() returns true if the property was defined on the object and false if it was not. defineproperties() object.defineproperties() returns the objects that were passed to the function. returns a type
error if any properties were not successfully defined on the object. n/a set() n/a refle...
...operty was defined on the object and false if it was not. defineproperties() object.defineproperties() returns the objects that were passed to the function. returns a type
error if any properties were not successfully defined on the object. n/a set() n/a reflect.set() returns true if the property was set successfully on the object and false if it was not. throws a type
error if the target was not an object. get() n/a reflect.get() returns the value of the property. throws a type
error if the target was not an object. deleteproperty() n/a reflect.deleteproperty() returns true if the property was deleted from the object and false if it was not. getownpropertydescriptor() object.getownpropertydescriptor() returns a property descr...
...a property descriptor of the given property if it exists on the object argument passed in, and returns undefined if it does not exist. however, if an object is not passed in as the first argument, it will be coerced into an object. reflect.getownpropertydescriptor() returns a property descriptor of the given property if it exists on the object. returns undefined if it does not exist, and a type
error if anything other than an object (a primitive) is passed in as the first argument. getownpropertydescriptors() object.getownpropertydescriptors() returns an object containing a property descriptor of each passed-in object. returns an empty object if the passed-in object has no owned property descriptors. n/a getprototypeof() object.getprototypeof() returns the prototype...
...And 6 more matches
Trailing commas - JavaScript
definitions for classes or objects: class c { one(a,) {} two(a, b,) {} } var obj = { one(a,) {}, two(a, b,) {}, }; function calls the following function invocation pairs are legal and equivalent to each other. f(p); f(p,); math.max(10, 20); math.max(10, 20,); illegal trailing commas function parameter definitions or function invocations only containing a comma will throw a syntax
error. ...
...(a, b,) {}, }; function calls the following function invocation pairs are legal and equivalent to each other. f(p); f(p,); math.max(10, 20); math.max(10, 20,); illegal trailing commas function parameter definitions or function invocations only containing a comma will throw a syntax
error. ...
...vocation pairs are legal and equivalent to each other. f(p); f(p,); math.max(10, 20); math.max(10, 20,); illegal trailing commas function parameter definitions or function invocations only containing a comma will throw a syntax
error. ...
...And 6 more matches
JavaScript reference - JavaScript
eference. built-ins javascript standard built-in objects, along with their methods and properties. ...
...-ins javascript standard built-in objects, along with their methods and properties. ...
...tandard built-in objects, along with their methods and properties. ...
...And 6 more matches
indexed-db - Archive of obsolete content
experimental exposes the indexeddb api to add-ons. usage scripts running in web pages can access indexeddb via the window object. ...
...w.indexeddb.open("mydatabase"); request.on
error = function(event) { console.log("failure"); }; request.onsuccess = function(event) { console.log("success"); }; because your main add-on code can't access the dom, you can't do this. so you can use the indexed-db module to access the same api: var { indexeddb } = require('sdk/indexed-db'); var request = indexeddb.open('mydatabase'); request.on
error = function(event) { console.log("failure"); }; request.onsuccess = function(event) { console.log("success"); }; most of the objects that implement the indexeddb api, such as idbtransaction, idbopendbrequest, and idbobjectstore, are accessible through the indexeddb object itself. the api exposed by indexed-db is almost identical to the dom indexeddb api, so we haven't repeated its documentat...
... the button labeled "add" adds the title of the current tab to a database, while the button labeled "list" lists all the titles in the database. the add-on implements helper functions open(), additem() and getitems() to open the database, add a new item to the database, and get all items in the database. ...
...And 5 more matches
Using Dependent Libraries In Extension Components - Archive of obsolete content
nent, then the component itself, and call nsgetmodule on // the component. ...
...'t care if this failed! // 2) we are going to leak this library. we don't care about that either. } library->setnativeleafname(ns_literal_cstring(krealcomponent)); prlibrary *lib; rv = library->load(&lib); if (ns_failed(rv)) return rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_
error_failure; return getmoduleproc(acompmgr, alocation, aresult); } extensions/stub/bdsstubloader.cpp (for mac os x) the code as written above won't work for mac os x. dependant libraries on the mac must be loaded with a special system function nsaddimage() with the flag nsaddimage_option_match_filename_by_installname. the following are the necessary modifications you will need in order to write ...
...eal component, then the component itself, and call nsgetmodule on // the component. ...
...And 5 more matches
generateCRMFRequest() - Archive of obsolete content
ity to cancel the operation. the method generatecrmfrequest() will return an instance of a crmf request object. the javascript passed in as the "crmf generation done code" parameter should look at the attribute request of the returned object to get the result of the crmf generation. ...
.... the method generatecrmfrequest() will return an instance of a crmf request object. the javascript passed in as the "crmf generation done code" parameter should look at the attribute request of the returned object to get the result of the crmf generation. the string found by accessing crmfobject.request is the base-64 encoded crmf message to be sent to the ca/ra, or an
error string. ...
...uest() will return an instance of a crmf request object. the javascript passed in as the "crmf generation done code" parameter should look at the attribute request of the returned object to get the result of the crmf generation. the string found by accessing crmfobject.request is the base-64 encoded crmf message to be sent to the ca/ra, or an
error string. ...
...And 5 more matches
importUserCertificates - Archive of obsolete content
thod is used to import newly issued certificates for the user. the private key for the certificates must already reside in the user's personal private key database. the request id in the response being imported must match the request id in the associated certification request or recovery request. if the import operation succeeds, an empty string will be returned. ...
...ficates for the user. the private key for the certificates must already reside in the user's personal private key database. the request id in the response being imported must match the request id in the associated certification request or recovery request. if the import operation succeeds, an empty string will be returned. ...
...for the certificates must already reside in the user's personal private key database. the request id in the response being imported must match the request id in the associated certification request or recovery request. if the import operation succeeds, an empty string will be returned. ...
...And 5 more matches
Debugging a XULRunner Application - Archive of obsolete content
dll's and the exe to wherever you want. then run console redirector.exe /? javascript console to enable the js console, start xulrunner with the -jsconsole argument. note: if you are not using the stub executable to launch the application, the -jsconsole argument is after the application.ini argument: e.g. xulrunner.exe /path/to/application.ini -jsconsole by default the js console only shows
errors from web content. to show
errors in chrome javascript, the pref pref("javascript.options.showinconsole", true) must be set. to log js
errors to disk, set the environment variable xre_console_log to the path to the filename. i.e. export xre_console_log=/path/to/logfile or set xre_console_log=c:\path\to\logfile. to output messages to the javascript console there are two ways to output messages ...
...with the red stop icon next to it). ...
...ipt.options.showinconsole", true) must be set. to log js
errors to disk, set the environment variable xre_console_log to the path to the filename. i.e. export xre_console_log=/path/to/logfile or set xre_console_log=c:\path\to\logfile. to output messages to the javascript console there are two ways to output messages to the js console: components.utils.report
error(str) will output str as an "
error" (i.e. with the red stop icon next to it). ...
...And 5 more matches
2006-11-10 - Archive of obsolete content
ember 10th 2006 browser buttons november 4th: mojr wants to know if firefox has a similar feature that the new ie 6 has built in. this feature consists of creating buttons using a small program, that allows you to create shortcuts to a particular address. the button gets added to the toolbar, separate from the links. reflow branch build failed with vc 7.1 sp1 november 8th: roy received an
error when he tried to reflow a branch build using vc 7.1 sp1. on the same day he posted the answer to his posting that he found in last weeks posting. click here to see the answer to the problem. building xulrunner application with mozilla november 8th: kirans is trying to build mozilla with xulrunner option on a windows machine. when he ran this "make -f client.mk build" command he receive a...
...hen he tried to reflow a branch build using vc 7.1 sp1. on the same day he posted the answer to his posting that he found in last weeks posting. click here to see the answer to the problem. building xulrunner application with mozilla november 8th: kirans is trying to build mozilla with xulrunner option on a windows machine. when he ran this "make -f client.mk build" command he receive an
error saying "no such file or directory". he stated that he set is home variable to c:\mozilla, and is not sure what he is doing wrong. november 9th: jonathan watt responded to his posting stating that he must have the wrong line endings in his mozconfig or some other script fill that he is probably using to run. build problem firefox 2.0 on fc3 november 10th: vin downloaded the latest firefox ...
... endings in his mozconfig or some other script fill that he is probably using to run. ...
...And 5 more matches
nsICrashReporter
tioninfotoappnotes(in voidptr aexception); native code only! void writeminidumpforexception(in voidptr aexceptioninfo); 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. ...
... submitreports boolean user preference for submitting crash reports. ...
... submitreports boolean user preference for submitting crash reports. methods annotatecrashreport() add some extra data to be submitted with a crash report. ...
...And 5 more matches
Type conversion
if src == 1: true var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v = true; console.log(mystruct.v.tostring()); // 'true' mystruct.v = false; console.log(mystruct.v.tostring()); // 'false' mystruct.v = 1; console.log(mystruct.v.tostring()); // 'true' mystruct.v = 0; console.log(mystruct.v.tostring()); // 'false' mystruct.v = 10; // throws
error mystruct.v = "a"; // throws
error integer types target type source converted value ctypes.char16_t js string (only if its length == 1) src.charcodeat(0) any integer types js number (only if fits to the size) src js boolean if src == true: 1 if src == false: 0 var mystruct = ctypes.structtype("mystructtype", [ ...
... note that the follo...
... note that the following table does not contain environment dependent types (ctypes.long, etc.). ...
...And 5 more matches
DirectoryEntrySync - Web APIs
and follows the w3c specifications (working draft) drafted on april 19, 2011. this specification is pretty much abandoned, having failed to reach any substantial traction. basic concepts if you want to create subdirectories, you have to create each child directory in sequence. if you try to create a directory using a full path that includes parent directories that do not exist yet, you get an
error. so create the hierarchy by recursively adding a new path after creating the parent directory. example the getfile() method returns a fileentrysync, which represents a file in the file system. the following creates an empty file called seekrits.txt in the root directory. var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method returns a directoryentrysync, ...
...elative path from the directory to the file to be looked up or created. you cannot create a file whose immediate parent does not exist. create the parent directory first. options an object literal describing the behavior of the method. if the file does not exist, it is created. object literal condition result create: true exclusive: true path already exists an
error is thrown. create: true exclusive: false path doesn't exist and no other
error occurs a file is created. if a file already exists, no
error is thrown. create: false (exclusive is ignored) path exists the file is returned. create: false (exclusive is ignored) path doesn't exist an
error is thrown. create: false (exclusive is ign...
... returns fileentrysync represents a file in a file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the path supplied is invalid. not_found_err the path was structurally correct, but refers to a resource that does not exist. ...
...And 5 more matches
FileSystemDirectoryEntry - Web APIs
methods which make it possible to access and manipulate the files in a directory, as well as to access the entries within the directory. basic concepts you can create a new directory by calling getdirectory(). if you want to create subdirectories, create each child directory in sequence. if you try creating a directory using a full path that includes parent directories that do not exist yet, an
error is returned. so create the hierarchy by recursively adding a new path after creating the parent directory. example in the following code snippet, we create a directory called "documents." // taking care of the browser-specific prefixes. window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; window.directoryentry = window.directoryentry || window.webkitdirectorye...
...ystem || window.webkitrequestfilesystem; window.directoryentry = window.directoryentry || window.webkitdirectoryentry; ... function onfs(fs){ fs.root.getdirectory('documents', {create:true}, function(directoryentry){ //directoryentry.isfile === false //directoryentry.isdirectory === true //directoryentry.name === 'documents' //directoryentry.fullpath === '/documents' }, on
error); } // opening a file system with temporary storage window.requestfilesystem(temporary, 1024*1024 /*1mb*/, onfs, on
error); properties this interface has no properties of its own, but inherits properties from its parent interface, filesystementry. methods this interface inherits methods from its parent interface, filesystementry. createreader() creates a filesystemdirectoryreader objec...
...ng internet android full 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 domexception rather than a file
error object.ie no support noopera no support nosafari full support 11.1webview android full support ≤37chrome android full support ...
...And 5 more matches
IDBRequest - Web APIs
lable, an event is fired on the request, and the information becomes available through the properties of the idbrequest instance. all asynchronous 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 invalidstate
error exception. in plain words, all asynchronous methods return a request object. if the request has been completed successfully, the result is made available through the result property and an event indicating success is fired at the request (idbrequest.onsucc...
... the interface idbopendbrequest is derived from idbrequest. note: this feature is available in web workers. ...
... the interface idbopendbrequest is derived from idbrequest. note: this feature is available in web workers. ...
...And 5 more matches
Using the Media Capabilities API - Web APIs
se to the console: navigator.mediacapabilities.decodinginfo(videoconfiguration).then(result => { console.log('this configuration is ' + (result.supported ? '' : 'not ') + 'supported, ' + (result.smooth ? '' : 'not ') + 'smooth, and ' + (result.powerefficient ? '' : 'not ') + 'power efficient.') }); the response provided is defined by the mediacapabilitiesinfo interface. ...
...es.decodinginfo(videoconfiguration).then(result => { console.log('this configuration is ' + (result.supported ? '' : 'not ') + 'supported, ' + (result.smooth ? '' : 'not ') + 'smooth, and ' + (result.powerefficient ? '' : 'not ') + 'power efficient.') }); the response provided is defined by the mediacapabilitiesinfo interface. ...
...) + 'supported, ' + (result.smooth ? '' : 'not ') + 'smooth, and ' + (result.powerefficient ? '' : 'not ') + 'power efficient.') }); the response provided is defined by the mediacapabilitiesinfo interface. handling
errors in our video decoding example, a type
error would be raised if the media configuration passed to the decodinginfo() method was invalid. there are a few reasons why an
error might occur, including: the specified type isn't one of the two permtited values: file or media-source the contenttype given is the
error can be due to the type not being one of the two possible values, the contenttype not being a valid codec mime type, or invalid or omitted definitions required in the videoconfiguration. navigator.mediacapabilities.decodinginfo(videoconfiguration).then( ...
...And 5 more matches
RTCPeerConnection.setRemoteDescription() - Web APIs
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(): invalidaccess
error the content of the description is invalid. invalidstate
error 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 establish...
...or 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. operation
error any
errors that occur which don't match the others specifeid here are reported as operation
error. this includes identity validation
errors. rtc
error an rtc
error with the
errordetail set to sdp-syntax-
error is reported if the sdp specified by rtcsessiondescription.sdp. the
error object's sdplinenumber property indicates the line number within the sdp on which the syntax
error was detected. typ...
... usage notes when you call setremotedescription(), the ice agent checks to make sure the rtcpeerconnection is in either the stable or have-remote-offer signalingstate. ...
...And 5 more matches
Understandable - Accessibility
the wcag description for guideline 3.2 predictable: make web pages appear and operate in predictable ways. guideline 3.3 — input assistance: help users avoid and correct mistakes this guideline centers around helping users enter correct information when required with the minimum of mistakes. ...
... ways. guideline 3.3 — input assistance: help users avoid and correct mistakes this guideline centers around helping users enter correct information when required with the minimum of mistakes. ...
...enters around helping users enter correct information when required with the minimum of mistakes. success criteria how to conform to the criteria practical resource 3.3.1
error identification (a) when a user is filling out a form or choosing between options, any
error that is detected should be clearly reported to the user, along with the form control that the
error relates to. it is advisable to implement client-side
error detection and handling, via html5 form validation features, and/or javascript, whatever is best for your situation. when an
error is detected, an intuitive
error message should be shown next to the form input that is at fault to help the user correct their inputs. for screenreader users, you can use aria live regions to alert the use...
...And 5 more matches
JavaScript modules - JavaScript
les are parsed as a module by runtimes such as node.js, and build tools such as babel. however, we decided to keep to using .js, at least for the moment. to get modules to work correctly in a browser, you need to make sure that your server is serving them with a content-type header that contains a javascript mime type such as text/javascript. if you don't, you'll get a strict mime type checking
error along the lines of "the server responded with a non-javascript mime type" and the browser won't run your javascript. most servers already set the correct type for .js files, but not yet for .mjs files. servers that already serve .mjs files correctly include github pages and http-server for node.js. this is ok if you are using such an environment already, or if you aren't but you know what you ar...
... <script type="module" src="main.js"></script> you can also embed the module's script directly into the html file by placing the javascript code within the body of the <script> element: <script type="module"> /* javascript module code here */ </script> the script into which you import the module features basically acts as the top-level module. ...
...odule" src="main.js"></script> you can also embed the module's script directly into the html file by placing the javascript code within the body of the <script> element: <script type="module"> /* javascript module code here */ </script> the script into which you import the module features basically acts as the top-level module. if you omit it, firefox for example gives you an
error of "syntax
error: import declarations may only appear at top level of a module". you can only use import and export statements inside modules, not regular scripts. other differences between modules and standard scripts you need to pay attention to local testing — if you try to load the html file locally (i.e. with a file:// url), you'll run into cors
errors due to javascript module security requirements. y...
...And 5 more matches
Arrow function expressions - JavaScript
gning to an undeclared identifier in a function. ...
... => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; } > y vm51587:1 uncaught reference
error: y is not defined at <anonymous>:1:1 (anonymous) @ vm51587:1 > f1(3) vm51533:1 x: 3, y: 3 4 > y 3 > f2 = x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; } x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; } > z vm51757:1 uncaught reference
error: z is not defined at <anonymous>:1:1 (anonymous) @ vm51757:1 > f2(4) vm51712:1 uncaught reference
error: z is not defined at f2 (<anonymous>:1:29) at <anonymous>:1:1 f2 @ vm51712:1 (anonymous) @ vm51800:1 > f3 = x => (z1 = x + 1) x => (z1 = x + 1) > z1 vm51891:1 uncaught reference
error: z1 is not defined at <anonymous>:1:1 (anonymous) @ vm51891:1 > f3(10) 11 > z1 11 f2 illus...
...reference
error: z is not defined at f2 (<anonymous>:1:29) at <anonymous>:1:1 f2 @ vm51712:1 (anonymous) @ vm51800:1 > f3 = x => (z1 = x + 1) x => (z1 = x + 1) > z1 vm51891:1 uncaught reference
error: z1 is not defined at <anonymous>:1:1 (anonymous) @ vm51891:1 > f3(10) 11 > z1 11 f2 illustrates that when explicitly setting the arrow function to apply strict mode, it does throw an
error when attempting to assign an undeclared variable. https://www.ecma-international.org/ecma-262/10.0/index.html#sec-strict-mode-code https://www.ecma-international.org/ecma-262/10.0/index.html#sec-arrow-function-definitions-runtime-semantics-evaluation correction: end invoked through call or apply since arrow functions do not have their own this, the methods call() and apply() can only pass in...
...And 5 more matches
Object.defineProperty() - JavaScript
if the old descriptor had its configurable attribute set to false the property is said to be “non-configurable”...
...property is said to be “non-configurable”. it is not possible to change any attribute of a non-configurable accessor property. for data properties, it is possible to modify the value if the property is writable, and it is possible to change writable attribute from true to false. it is not possible to switch between data and accessor property types when the property is non-configurable. a type
error is thrown when attempts are made to change non-configurable property attributes (except value and writable, if permitted) unless the current and new values are the same. writable attribute when the writable property attribute is set to false, the property is said to be “non-writable”. it cannot be reassigned. var o = {}; // creates a new object object.defineproperty(o, 'a', { value: 37,...
... attributes (except value and writable, if permitted) unless the current and new values are the same. writable attribute when the writable property attribute is set to false, the property is said to be “non-writable”. it cannot be reassigned. ...
...And 5 more matches
Object.freeze() - JavaScript
tive examples 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 type
error 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.
...s can still be modified, unless they are also frozen. as an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. freeze() returns the same object that was passed into the function. it does not create a frozen copy. in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. ...
...o elements can be added to or removed from the array. freeze() returns the same object that was passed into the function. it does not create a frozen copy. in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. in es2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned. ...
...And 5 more matches
const - JavaScript
he considerations about the "temporal dead zone" apply to both let and const. a constant cannot share its name with a function or a variable in the same scope. examples basic const usage constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters. ...
...ut the "temporal dead zone" apply to both let and const. a constant cannot share its name with a function or a variable in the same scope. examples basic const usage constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters. ...
...usage constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters. // define my_fav as a constant and give it the value 7 const my_fav = 7; // this will throw an
error - uncaught type
error: assignment to constant variable. my_fav = 20; // my_fav is 7 console.log('my favorite number is: ' + my_fav); // trying to redeclare a constant throws an
error // uncaught syntax
error: identifier 'my_fav' has already been declared const my_fav = 20; // the name my_fav is reserved for constant above, so this will fail too var my_fav = 20; // this throws an
error too let my_fav = 20; block scoping it's important to note the nature of block scoping. if (my_fav === 7) { // this is fine and creates a block scoped my_fav variable // (works equally ...
...And 5 more matches
Transitioning to strict mode - JavaScript
ning an existing code base to strict mode requires a bit more work. this article aims at providing guidance for developers. gradual transition strict mode has been designed so that the transition to it can be made gradually. it is possible to change each file individually and even to transition code to strict mode down to the function granularity. ...
...article aims at providing guidance for developers. gradual transition strict mode has been designed so that the transition to it can be made gradually. it is possible to change each file individually and even to transition code to strict mode down to the function granularity. ...
...ecuting: octal syntax var n = 023; with statement using delete on a variable name delete myvariable; using eval or arguments as variable or function argument name using one of the newly reserved keywords (in prevision for ecmascript 2015): implements, interface, let, package, private, protected, public, static, and yield declaring function in blocks if (a < b) { function f() {} } obvious
errors declaring twice the same name for a property name in an object literal {a: 1, b: 3, a: 7} this is no longer the case in ecmascript 2015 (bug 1041128). declaring two function parameters with the same name function f(a, b, b) {} these
errors are good, because they reveal plain
errors or bad practices. they occur before the code is running. new runtime
errors javascript used to si...
...And 5 more matches
console - Archive of obsolete content
if you have started firefox for your add-on from the command line with jpm run or jpm test then these messages appear in the command shell you used. if the add-on has been installed in firefox, then the messages 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. ...
...e 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, preceded by "
error:" and the name of your add-on: console.
error("this is an
error message");
error: my-addon: this is an
error message console.exception(exception) logs the given exception instance as an
error, outputting information about the exception's stack traceback if one is available. try { dothing(); } catch (e) { con...
...userexception: thing could not be done! console.info(object[, object, ...]) a synonym for console.log(). ...
...And 4 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
plays. disabling this cache forces xul documents to be reloaded any every time they are displayed. true browser.dom.window.dump.enabled (not present in firefox 3.5+) enables use of the dump method for debugging. refer to the “javascript debugging methods” sidebar. ...
...ng this cache forces xul documents to be reloaded any every time they are displayed. true browser.dom.window.dump.enabled (not present in firefox 3.5+) enables use of the dump method for debugging. refer to the “javascript debugging methods” sidebar. true javascript.options.showinconsole (present in firefox 3.5+) outputs javascript
errors to the
error console. ...
... browser.dom.window.dump.enabled (not present in firefox 3.5+) enables use of the dump method for debugging. refer to the “javascript debugging methods” sidebar. true javascript.options.showinconsole (present in firefox 3.5+) outputs javascript
errors to the
error console. true javascript.options.strict (present in firefox 3.5+) enforces strict
error output from javascript true table 1: preferences to set for developing extensions to make these changes, start your development profile, type about:config into firefox’s location bar and open the preferences window; find the preferences listed in table 1 and double-click on them to set them accordingly. some of these preferences do not exist—to create them, right-click, select “n...
...And 4 more matches
Promises - Archive of obsolete content
ous, procedural code. ...
...it is also available for use off-main-thread in workers as a synchronous api. ...
...promises, its standard usage is very easy to adapt to a promise-based approach. moreover, many third-party wrappers for the xmlhttprequest api now support promises out of the box. example direct usage task.spawn(function* () { // make the initial request. let resp = yield new promise((resolve, reject) => { let xhr = new xmlhttprequest; xhr.onload = resolve; xhr.on
error = reject; xhr.open("get", dataurl); xhr.responsetype = "json"; xhr.send(); }); let data = resp.target.response; // use the response to construct form data object for the // second request. let form = new formdata; form.append("id", data.id); form.append("content", data.content); // make the second request. resp = yield new promise((re...
...And 4 more matches
Introducing a complete toolchain - Learn web development
l the editor needs is "format on save" enabled. like many tools made more recently prettier comes with "sensible defaults". that means that you'll be able to use prettier without having to configure anything (if you are happy with the defaults). this lets you get on with what's important: the creative work. code linting tools linting helps with code quality but also is a way to catch potential
errors earlier during development. it's a key ingredient of a good toolchain and one that many development projects will include by default. web development linting tools mostly exist for javascript (though there are a few available for html and css). this makes sense: if an unknown html element or invalid css property is used, due to the resilient nature of these two languages nothing is likely to br...
...ind that if you want to refine and enforce a rule about how your code looks (or validates), it's very likely that it can be done with the right eslint configuration. a little later in this chapter, we'll provide the eslint config. once a working configuration is in place, running the command can generate some useful information. here is an example eslint output: ./my-project/src/index.js 2:8
error 'react' is defined but never used no-unused-vars 22:20
error 'body' is defined but never used no-unused-vars 96:19
error 'b' is defined but never used no-unused-vars ✖ 3 problems (3
errors, 0 warnings) note: we'll install eslint in the next section; don't worry about this for now. as with other tools, code editor integration support is typically good for eslint, and potentially m...
... separate dependencies reduces any unnecessary work when deploying to production (which we will look at in the next chapter). before starting on the development of the actual application code, a little configuration is required for our tools to work properly. it's not a prerequisite of developing for the web, but it's useful to have the tools configured correctly if they’re going to help catch
errors during development — which eslint is particularly useful for. configuring our tools in the root of the project (not in the src directory), we will add configuration files to configure some of our tools, namely prettier and eslint. this is general practice for tool configuration — you tend to find the config files in the project root, which more often than not contain configuration options ...
...And 4 more matches
Downloads.jsm
> getsummary(atype); constants constant description public work 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. ...
...escription public work 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 download
error object. ...
...ate 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 download
error 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 createdownload() creates a new download object. promise<download> createdownl...
...And 4 more matches
Encrypt Decrypt_MAC_Using Token
*/ secstatus decryptandverifymac(const char* outfilename, char *encryptedfilename, secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned...
... if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count == filelength) { decbuflen = decbuflen-paddinglength; } /* write the plain text to out file. */ temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write
error\n"); rv = secfailure; break; } /* save last block of ciphertext. */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac...
... generatesymkey(slot, ckm_generic_secret_key_gen, 160/8, &mackeyid, pwdata); if (mackey == null) { pr_fprintf(pr_stderr, "generatesymkey for macing returned null.\n"); rv = secfailure; goto cleanup; } /* get the encrypt key cka_id */ rv = gathercka_id(enckey, &encckaid); if (rv != secsuccess) { pr_fprintf(pr_stderr, "
error while wrapping encrypt key\n"); goto cleanup; } /* get the mac key cka_id */ rv = gathercka_id(mackey, &macckaid); if (rv != secsuccess) { pr_fprintf(pr_stderr, "can't get the mac key cka_id.\n"); goto cleanup; } if (noisefilename) { rv = seedfromnoisefile(noisefilename); if (rv != secsuccess) { port_set
error(pr_end_of_...
...And 4 more matches
mozIStorageConnection
storage/public/mozistorageconnection.idlscriptable this interface represents a database connection attached to a specific file or an in-memory database. it is the primary interface for interacting with a database, including creating prepared statements, executing sql, and examining database
errors. 1.0 68 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) for a general overview on how to use this interface, see storage. method overview void asyncclose([optional] in mozistoragecompletioncallback acallback); void begintransaction(); void begintransactionas(in print32 transactiontype); mozistoragestatement clone([optional] in boolean areadonly); ...
...e); attributes attribute type description connectionready boolean indicates if the connection is open and ready to use. this will be false if the connection failed to open, or it has been closed. read only. databasefile nsifile the current database nsifile. null if the database connection refers to an in-memory database. read only. last
error long the last sqlite
error code that occurred. read only. note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads. last
errorstring autf8string the english
error string reported by the sqlite library for the last sqlite operation. read only. note: this is not reliable if you are using asynchronous sta...
..., 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 of the given transact...
...And 4 more matches
nsIEffectiveTLDService
nal 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). ...
...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 returned by nsiidnservice.normalize() when the hostname contains characters disallowed in uris. getb...
...ng 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). ...
...And 4 more matches
nsIFaviconService
0 attributes attribute type description defaultfavicon nsiuri the default favicon uri. read only. methods addfailedfavicon() this method adds a given favicon's uri to the failed favicon cache. the lifespan of the favicon cache is up to the caching system. this cache will also be written to if you use setandloadfaviconforpage() method and it encounters an
error while fetching an icon. void addfailedfavicon( in nsiuri afaviconuri ); parameters afaviconuri the uri of an icon in the favicon service. can be null. expireallfavicons() expires all known favicons, removing them from the database. note: this is an asynchronous operation; when it completes, a "places-favicons-expired" notification is dispatched through the observer's service. void ex...
... 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, returning it as a da...
...ption if we don't have data. if there is no data but we have an entry for this favicon, returns null. astring getfavicondataasdataurl( in nsiuri afaviconuri ); parameters afaviconuri uri of the favicon whose data is being read. return value a data url containing the data for the favicon. this is null if there is no data but there is an entry for the favicon. exceptions thrown ns_
error_not_available thrown when we have never heard of this favicon url. getfaviconforpage() 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.getfaviconurlforpage() instead. this method retrieves the uri of the favicon for the given page. nsiuri g...
...And 4 more matches
nsIToolkitProfileService
eryinterface(components.interfaces.nsitoolkitprofile) to get access to its attributes and methods). selectedprofile nsitoolkitprofile the profile that is marked as "default=1" in the profiles.ini file. (not the profile currently in use.) not sure what happens if you change this setting but someone said: you can change profiles by setting this attribute's value. this may throw an ns_
error_failure (0x80004005) when trying to get the current profile if it's unavailable or if permissions restrict access. startoffline boolean startwithlastprofile boolean methods createprofile() creates a new profile. the profile temporary directory will be chosen based on where the profile directory is located. nsitoolkitprofile createprofile( in nsilocalfile a...
...ory 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 the risk of the profi...
... getprofilebyname() gets a profile, given the profile's name. ...
...And 4 more matches
Troubleshooting XPCOM components registration
often the first time you create an xpcom component, it may fail to register correctly. there are several common reasons that registration can fail: a component that is a binary (shared library) fails to load a javascript component has parsing
errors the shared library loaded correctly, but registration was not successful did registration succeed? it is important to not misdiagnose the problem. you can be certain that a component has failed to register by going to the
error console and evaluating components.classes["contract-id"].name where contract-id is your contract id. if the response is your contract id instead of an
error, the component was successfully registered and this is the wrong page. load failure of binary components on the mozilla trunk (firefox 3, xulrunner 1.9...
...as failed to register by going to the
error console and evaluating components.classes["contract-id"].name where contract-id is your contract id. if the response is your contract id instead of an
error, the component was successfully registered and this is the wrong page. load failure of binary components on the mozilla trunk (firefox 3, xulrunner 1.9), components that fail to load will print an
error to the
error console. chrome
errors must be enabled. ...
... components.classes["contract-id"].name where contract-id is your contract id. if the response is your contract id instead of an
error, the component was successfully registered and this is the wrong page. load failure of binary components on the mozilla trunk (firefox 3, xulrunner 1.9), components that fail to load will print an
error to the
error console. chrome
errors must be enabled. if the
error appears, you can use nspr logging to see additional information about the failure by running firefox from a command prompt: rem close all firefox windows! set nspr_log_modules=nsnativemoduleloader:5 set nspr_log_file=c:\path\to\logfile "c:\program files\mozilla firefox\firefox.exe" examining this log for warning and
errors may provide valuable clues why the component failed to load. if using ...
...And 4 more matches
Debugger.Frame - Firefox Developer Tools
ipt engine this frame is executing in: "interpreter": a frame running in the interpreter. "baseline": a frame running in the unoptimizing, baseline jit. "ion": a frame running in the optimizing jit. "wasm": a frame running in webassembly baseline jit. this the value of this for this frame (a debuggee value). for a wasmcall frame, this property throws a type
error. older the next-older visible frame, in which control will resume when this frame completes. if there is no older frame, this is null. depth the depth of this frame, counting from oldest to youngest; the oldest frame has a depth of zero. live true if the frame this debugger.frame instance refers to is still on the stack; false if it has completed execution or been popped in some other way. ...
... the script being executed in this frame (a debugger.script instance), or null on frames that do not represent calls to debuggee code. on frames whose callee property is not null, this is equal to callee.script. offset the offset of the bytecode instruction currently being executed in script, or undefined if the frame’s script property is null. for a wasmcall frame, this property throws a type
error. environment the lexical environment within which evaluation is taking place (a debugger.environment instance), or null on frames that do not represent the evaluation of debuggee code, like calls non-debuggee functions, host functions or "debugger" frames. callee the function whose application created this frame, as a debuggee value, or null if this is not a "call" frame. generator true if ...
...ull, this is an object, allocated in the same global as the debugger, with array.prototype on its prototype chain, a non-writable length property, and properties whose names are array indices. each property is a read-only accessor property whose getter returns the current value of the corresponding parameter. when the referent frame is popped, the argument value’s properties’ getters throw an
error. handler methods of debugger.frame instances each debugger.frame instance inherits accessor properties holding handler functions for spidermonkey to call when given events occur in the frame. calls to frames’ handler methods are cross-compartment, intra-thread calls: the call takes place in the thread to which the frame belongs, and runs in the compartment to which the handler method belong...
...And 4 more matches
View Source - Firefox Developer Tools
nd select view page source press ctrl + u on windows and linux, or cmd + u on macos the command opens a new tab with the source for the current page. view source features view source has three additional features, which can be accessed from the context menu in the view source tab: go to line scrolls to the specified line. if the number is higher than the lines in a file, you receive an
error message. wrap long lines (toggle) wraps long lines to the width of the page. syntax highlighting (toggle) applies syntax highlighting to the code.when syntax highlighting is on, view source also highlights parsing
errors in red. hovering your mouse over
errors displays a tooltip explaining the
error. this feature is useful when you're looking for html
errors. to access go to line from th...
...lection source", that behaves just like "view page source", except you only see the source for the selection. view mathml source if you context-click while the mouse is over some mathml, you'll see a context menu item labeled "view mathml source": click it to see the mathml source. limitations of view source there are limitations to what view source does for you that you need to be aware of. ...
...ept you only see the source for the selection. view mathml source if you context-click while the mouse is over some mathml, you'll see a context menu item labeled "view mathml source": click it to see the mathml source. limitations of view source there are limitations to what view source does for you that you need to be aware of.
error reporter ≠ validator view source only reports parsing
errors, not html validity
errors. ...
...And 4 more matches
IDBDatabase - Web APIs
a separate thread. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort fired when when a transaction is aborted and bubbles up to the connection object. also available via the onabort property. close fired when the database connection is unexpectedly closed. also available via the onclose property. ...
...these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort fired when when a transaction is aborted and bubbles up to the connection object. also available via the onabort property. close fired when the database connection is unexpectedly closed. also available via the onclose property. ...
...ventname property of this interface. abort fired when when a transaction is aborted and bubbles up to the connection object. also available via the onabort property. close fired when the database connection is unexpectedly closed. also available via the onclose property.
error fired when a request returns an
error and the event bubbles up to the connection object. also available via the on
error property. versionchange fired when a database structure change was requested. also available via the onversionchange property. example in the following code snippet, we open a database asynchronously (idbfactory), handle success and
error cases, and create a new object store in the case that an upgrade is needed (idbdatabase). for a complete working example, see our to-do notifications app (...
...And 4 more matches
MediaRecorder.start() - Web APIs
mediarecorder with the recorded data. if the source is still playing, a new blob is created and recording continues into that, and so forth. when the source stream ends, state is set to inactive and data gathering stops. a final dataavailable event is sent to the mediarecorder, followed by a stop event. note: if the browser is unable to start recording or continue recording, it will raise a dom
error event, followed by a mediarecorder.dataavailable event containing the blob it has gathered, followed by the mediarecorder.stop event. 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 ...
...x 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. ...
...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. ...
...And 4 more matches
Using the Payment Request API - Web APIs
st instead of legacy web forms. const checkoutbutton = document.getelementbyid('checkout-button'); if (window.paymentrequest) { let request = new paymentrequest(buildsupportedpaymentmethodnames(), buildshoppingcartdetails()); checkoutbutton.addeventlistener('click', function() { request.show().then(function(paymentresponse) { // handle successful payment }).catch(function(
error) { // handle cancelled or failed payment. for example, redirect to // the legacy web form checkout: window.location.href = '/legacy-web-form-checkout'; }); // every click on the checkout button should use a new instance of // paymentrequest object, because paymentrequest.show() can be // called only once per instance. request = new paymentrequest(buildsupport...
...the website does not know whether they can make // a fast payment, so pick a generic title. checkoutbutton.innertext = "checkout with w3c"; }); } note: see our customizing the payment button demo for the full code. checking before all prices are known if the checkout flow needs to k...
..., should the page fallback to manual // web form checkout? const supportedpaymentmethods = ... let shouldcallpaymentrequest = true; let fallbacktolegacyonpaymentrequestfailure = false; (new paymentrequest(supportedpaymentmethods, {total: {label: 'stub', amount: {currency: 'usd', value: '0.01'}}}) .canmakepayment() .then(function(result) { shouldcallpaymentrequest = result; }).catch(function(
error) { console.log(
error); // the user may have turned off query ability in their privacy settings. // let's use paymentrequest by default and fallback to legacy // web form based checkout. shouldcallpaymentrequest = true; fallbacktolegacyonpaymentrequestfailure = true; }); // user has clicked on the checkout button. we know // what's in the cart, but we don't have a `checkout` object. f...
...And 4 more matches
Using the Screen Capture API - Web APIs
initiated by calling navigator.mediadevices.getdisplaymedia(), which returns a promise that resolves to a stream containing the live screen contents. starting screen capture: async/await style async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.
error("
error: " + err); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise directly, as seen below. starting screen capture: promise style function startcapture(displaymediaoptions) { let capturestream = null; return navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => {...
..." + err); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise directly, as seen below. starting screen capture: promise style function startcapture(displaymediaoptions) { let capturestream = null; return navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => { console.
error("
error:" + err); return null; }); } either way, the user agent responds by presenting a user interface that prompts the user to choose the screen area to share. both of these implementations of startcapture() return the mediastream containing the captured display imagery. see options and constraints, below, for more on both how to specify the type of surface you want as well as other ways to ad...
...ment.getelementbyid("stop"); // options for getdisplaymedia() var displaymediaoptions = { video: { cursor: "always" }, audio: false }; // set event listeners for the start and stop buttons startelem.addeventlistener("click", function(evt) { startcapture(); }, false); stopelem.addeventlistener("click", function(evt) { stopcapture(); }, false); logging content to make logging of
errors and other issues easy, this example overrides certain console methods to output their messages to the <pre> block whose id is log. console.log = msg => logelem.innerhtml += `${msg}<br>`; console.
error = msg => logelem.innerhtml += `<span class="
error">${msg}</span><br>`; console.warn = msg => logelem.innerhtml += `<span class="warn">${msg}<span><br>`; console.info = msg => logelem.innerhtml += ...
...And 4 more matches
Using DTMF with WebRTC - Web APIs
receiverpc; its onicecandidate event handler is set up too. if addtrack() is supported, we set up the receiver's ontrack event handler; otherwise, we set up onaddstream. the track and addstream events are sent when media is added to the connection. finally, we call getusermedia() to obtain access to the caller's microphone. if successful, the function gotstream() is called, otherwise we log the
error because calling has failed. adding the audio to the connection as mentioned above, when the audio input from the microphone is obtained, gotstream() is called. its job is to build the stream being sent to the receiver, so the actual process of starting to transmit can begin. it also gets access to the rtcdtmfsender we'll use to issue dtmf on the connection. function gotstream(stream) { log("...
... the caller and the receiver, so we can just directly add the candidate to the receiver by calling its addicecandidate() method. that's handled by handlecallericeevent(): function handlecallericeevent(event) { if (event.candidate) { log("adding candidate to receiver: " + event.candidate.candidate); receiverpc.addicecandidate(new rtcicecandidate(event.candidate)) .catch(err => log("
error adding candidate to receiver: " + err)); } else { log("caller is out of candidates."); } } if the icecandidate event has a non-null candidate property, we create a new rtcicecandidate object from the event.candidate string and "transmit" it to the receiver by calling receiverpc.addicecandidate(), providing the new rtcicecandidate as its input. if addicecandidate() fails, the catch() cla...
...e to receiver: " + err)); } else { log("caller is out of candidates."); } } if the icecandidate event has a non-null candidate property, we create a new rtcicecandidate object from the event.candidate string and "transmit" it to the receiver by calling receiverpc.addicecandidate(), providing the new rtcicecandidate as its input. if addicecandidate() fails, the catch() clause outputs the
error to our log box. if event.candidate is null, that indicates that there are no more candidates available, and we log that information. dialing once the connection is open our design requires that when the connection is established, we immediately send the dtmf string. to accomplish that, we watch for the caller to receive an iceconnectionstatechange event. this event is sent when one of a number...
...And 4 more matches
Starting up and shutting down a WebXR session - Web APIs
age. the javascript code must, likewise, have been loaded securely. if the document wasn't loaded securely, you won't get very far. the navigator.xr property doesn't even exist if the document wasn't loaded securely. this may also be the case if there simply is no compatible xr hardware available. either way, you need to be prepared for the lack of an xr property and either gracefully handle the
error or provide some form of fallback. falling back to the webxr polyfill one fallback option is the webxr polyfill, provided by the immersive web working group that's in charge of the webxr standardization process. the polyfill brings support for webxr to browsers that don't have native webxr support, and smooths out the inconsistencies among implementations in the browsers that do have it, so it c...
...uldn't be created for some reason—such as feature policy disallowing its use or the user 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 s...
...reference spaces you need or prefer to use. ...
...And 4 more matches
WindowOrWorkerGlobalScope.fetch() - Web APIs
the fetch() method of the windoworworkerglobalscope mixin starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. the promise resolves to the response object representing the response to your request. the promise does not reject on http
errors — it only rejects on network
errors. you must use then handlers to check for http
errors. ...
...instead, a then() handler must check the response.ok and/or response.status properties. ...
...instead, a then() handler must check the response.ok and/or response.status properties. the fetch() method is controlled by the connect-src directive of content security policy rather than the directive of the resources it's retrieving. note: the fetch() method's parameters are identical to those of the request() constructor. ...
...And 4 more matches
Cognitive accessibility - Accessibility
wcag guidelines wcag, web content accessibility guidelines, includes several guidelines to improve cognitive accessibility. these guidelines are published by the web accessibility initiative (wai) of the world wide web consortium (w3c), the main international standards organization for the internet. this group is also responsible for the accessible rich inte...
...ng consistent web page layout and navigation; incorporating familiar elements, such as underlined links that are blue when not visited and purple when visited; dividing processes into logical, essential steps with progress indicators; making website authentication as easy as possible without compromising security; and making forms easy to complete, such as with clear
error messages and simple
error recovery. wcag guidelines wcag, web content accessibility guidelines, includes several guidelines to improve cognitive accessibility. these guidelines are published by the web accessibility initiative (wai) of the world wide web consortium (w3c), the main international standards organization for the internet. this group is also responsible for the accessible rich internet application (aria) gu...
...correct mistakes." while we all make mistakes, some people are more likely to make mistakes, less likely to notice a mistake, or have a harder time correcting a mistake once they make one. ...
...And 4 more matches
Audio and Video Delivery - Developer guides
mediastream recording new standards are being rolled out to allow your browser to grab media from your mic or camera using getusermedia ...
...ediarecorder object, take the resulting output and feed it to your audio or video source*. ...
...ing output and feed it to your audio or video source*. the main mechanism is outlined below: navigator.mediadevices.getusermedia({audio:true}) .then(function onsuccess(stream) { var recorder = new mediarecorder(stream); var data = []; recorder.ondataavailable = function(e) { data.push(e.data); }; recorder.start(); recorder.on
error = function(e) { throw e.
error || new
error(e.name); // e.name is ff non-spec } recorder.onstop = function(e) { var audio = document.createelement('audio'); audio.src = window.url.createobjecturl(new blob(data)); } settimeout(function() { rec.stop(); }, 5000); }) .catch(function on
error(
error) { console.log(
error.message); }); see mediarecorder api for more details. media sour...
...And 4 more matches
Index - HTTP
g any assets using http when the page is loaded using https. 31 csp: child-src csp, directive, http, reference, security the deprecated http content-security-policy (csp) child-src directive defines the valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>. for workers, non-compliant requests are treated as fatal network
errors by the user agent. 32 csp: connect-src csp, directive, http, reference, security the http content-security-policy (csp) connect-src directive restricts the urls which can be loaded using script interfaces. the apis that are restricted are: 33 csp: default-src csp, directive, http, reference, security the http content-security-policy (csp) default-src dir...
...e 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 reject with a notallowed
error. 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 domexceptio...
...returned by navigator.requestmediakeysystemaccess() will reject with a domexception. 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 type
error. ...
...And 4 more matches
Meta programming - JavaScript
ems.) target object which the proxy virtualizes. it is often used as storage backend for the proxy. invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target. invariants semantics that remain unchanged when implementing custom operations are called invariants. if you violate the invariants of a handler, a type
error will be thrown. handlers and traps the following table summarizes the available traps available to proxy objects. see the reference pages for detailed explanations and examples. handler / trap interceptions invariants handler.getprototypeof() object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof ...
...es 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 type
error 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. a property cannot be reported as non-existent if it exists as an own property of target and t...
...y to be 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 type
error 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() ...
...And 4 more matches
Promise.any() - JavaScript
essentially, this method is the opposite of promise.all(). ...
...essentially, this method is the opposite of promise.all(). ...
...essentially, this method is the opposite of promise.all(). ...
...And 4 more matches
Promise.prototype.catch() - JavaScript
tive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax p.catch(onrejected); p.catch(function(reason) { // rejection }); parameters onrejected a function called when the promise is rejected. this function has one argument: reason the rejection reason. the promise returned by catch() is rejected if onrejected throws an
error or returns a promise which is itself rejected; otherwise, it is resolved. return value internally calls promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onrejected handler. returns the value of that call, which is a promise. note the examples below are throwing instances of
error. this is considered good practice in contrast to ...
...en on the object upon which it was called, passing the parameters undefined and the received onrejected handler. returns the value of that call, which is a promise. note the examples below are throwing instances of
error. this is considered good practice in contrast to throwing strings; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an
error, and you might lose valuable information like stack traces. demonstration of the internal call: // overriding original promise.prototype.then/catch just to add some logs (function(promise){ var originalthen = promise.prototype.then; var originalcatch = promise.prototype.catch; promise.prototype.then = function(){ console.log('> > > > > > called .then on %o with arguments: ...
....then/catch just to add some logs (function(promise){ var originalthen = promise.prototype.then; var originalcatch = promise.prototype.catch; promise.prototype.then = function(){ console.log('> > > > > > called .then on %o with arguments: %o', this, arguments); return originalthen.apply(this, arguments); }; promise.prototype.catch = function(){ console.
error('> > > > > > called .catch on %o with arguments: %o', this, arguments); return originalcatch.apply(this, arguments); }; })(this.promise); // calling catch on an already resolved promise promise.resolve().catch(function xxx(){}); // logs: // > > > > > > called .catch on promise{} with arguments: arguments{1} [0: function xxx()] // > > > > > > called .then on promise{} with argumen...
...And 4 more matches
String.fromCodePoint() - JavaScript
le 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 range
error is thrown if an invalid unicode code point is given (e.g. "range
error: 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 been added to ecmas...
...x !== len; ++index) { var codepoint = +arguments[index]; // correctly handles all cases including `nan`, `-infinity`, `+infinity` // the surrounding `!(...)` is required to correctly handle `nan` cases // the (codepoint>>>0) === codepoint clause handles decimals and negatives if (!(codepoint < 0x10ffff && (codepoint>>>0) === codepoint)) throw range
error("invalid code point: " + codepoint); if (codepoint <= 0xffff) { // bmp code point codelen = codeunits.push(codepoint); } else { // astral code point; split in surrogate halves // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codepoint -= 0x10000; codelen = codeunits.push( (codepoint >> 10) + 0xd800, // hi...
...code points 0x010000 – 0x10ffff) by specifying their code point. inste...
...And 4 more matches
WebAssembly - JavaScript
tions, or to intl which is the namespace object for internationalization constructors and other language-sensitive functions. description the primary uses for the webassembly object are: loading webassembly code, using the webassembly.instantiate() function. creating new memory and table instances via the webassembly.memory()/webassembly.table() constructors. providing facilities to handle
errors that occur in webassembly via the webassembly.compile
error()/webassembly.link
error()/webassembly.runtime
error() constructors. constructor properties webassembly.compile
error() indicates an
error during webassembly decoding or validation. webassembly.global() represents a global variable instance, accessible from both javascript and importable/exportable across one or more webassembly.mod...
... webassembly.memory() an object whose buffer property is a resizable arraybuffer that holds the raw bytes of memory accessed by a webassembly instance. ...
... webassembly.memory() an object whose buffer property is a resizable arraybuffer that holds the raw bytes of memory accessed by a webassembly instance. ...
...And 4 more matches
Lexical grammar - JavaScript
per 2019 ecma-262 specs): 0e-5 // => 0 0e+5 // => 0 5e1 // => 50 175e-2 // => 1.75 1e3 // => 1000 1e-3 // => 0.001 binary binary number syntax uses a leading zero followed by a lowercase or uppercase latin letter "b" (0b or 0b). because this syntax is new in ecmascript 2015, see the browser compatibility table, below. if the digits after the 0b are not 0 or 1, the following syntax
error is thrown: "missing binary digits after 0b". var flt_signbit = 0b10000000000000000000000000000000; // 2147483648 var flt_exponent = 0b01111111100000000000000000000000; // 2139095040 var flt_mantissa = 0b00000000011111111111111111111111; // 8388607 octal octal number syntax uses a leading zero followed by a lowercase or uppercase latin letter "o" (0o or 0o). because this syntax is new in ecmas...
...01111111100000000000000000000000; // 2139095040 var flt_mantissa = 0b00000000011111111111111111111111; // 8388607 octal octal number syntax uses a leading zero followed by a lowercase or uppercase latin letter "o" (0o or 0o). because this syntax is new in ecmascript 2015, see the browser compatibility table, below. ...
... 0xfffffffffffffffff // 295147905179352830000 0x123456789abcdef // 81985529216486900 0xa // 10 bigint literal the bigint type is a numeric primitive in javascript that can represent integers with arbitrary precision. bigint literals are created by appending n to the end of an integer. ...
...And 4 more matches
let - JavaScript
{someproperty: "foo"} thing.showpublic(); // "foo" thing.showprivate(); // 1 the same privacy pattern with closures over local variables can be created with var, but those need a function scope (typically an iife in the module pattern) instead of just a block scope like in the example above. redeclarations redeclaring the same variable within the same function or block scope raises a syntax
error. if (x) { let foo; let foo; // syntax
error thrown. } you may encounter
errors in switch statements because there is only one block. let x = 1; switch(x) { case 0: let foo; break; case 1: let foo; // syntax
error for redeclaration. break; } however, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, ...
...ax
error thrown. } you may encounter
errors in switch statements because there is only one block. let x = 1; switch(x) { case 0: let foo; break; case 1: let foo; // syntax
error for redeclaration. break; } however, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, which will not produce the redeclaration
errors shown above. let x = 1; switch(x) { case 0: { let foo; break; } case 1: { let foo; break; } } temporal dead zone unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. accessing the variable before the initialization results in a reference
error. the variable is in a "tempora...
...h var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. accessing the variable before the initialization results in a reference
error. the variable is in a "temporal dead zone" from the start of the block until the initialization is processed. ...
...And 4 more matches
var - JavaScript
ey occur, are processed before any code is executed. this is called hoisting, and is discussed further below. the scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. ...
...g var will not trigger an
error, even in strict mode, and the variable will not lose its value, unless another assignment is performed. 'use strict'; function foo() { var x = 1; function bar() { var y = 2; console.log(x); // 1 (function `bar` closes over `x`) console.log(y); // 2 (`y` is in scope) } bar(); console.log(x); // 1 (`x` is in scope) console.log(y); // reference
error in strict mode, `y` is scoped to `bar` } foo(); variables declared using var are created before any code is executed in a process known as hoisting. their initial value is undefined. 'use strict'; console.log(x); // undefined (note: not reference
error) console.log('still going...'); // still going... var x = 1; console.log(x); // 1 console.log('still going...'); ...
...object for global variables, is set to be non-configurable because the identifier is to be treated as a variable, rather than a straightforward property of the global object. javascript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable. 'use strict'; var x = 1; globalthis.hasownproperty('x'); // true delete globalthis.x; // type
error in strict mode. fails silently otherwise. delete x; // syntax
error in strict mode. fails silently otherwise. note that in both nodejs commonjs modules and native ecmascript modules, top-level variable declarations are scoped to the module, and are not, therefore added as properties to the global object. unqualified identifier assignments the global object sits at the top of the scope chain. ...
...And 4 more matches
Caching compiled WebAssembly modules - WebAssembly
helper function contained inside instantiatecachedurl() — opendatabase() — creates an object store for storing wasm modules, and also handles clearing out the database if the dbversion is updated; it returns a promise resolving to the new database. ...
...inside instantiatecachedurl() — opendatabase() — creates an object store for storing wasm modules, and also handles clearing out the database if the dbversion is updated; it returns a promise resolving to the new database. ...
...; } console.log(`creating version ${event.newversion} wasm cache`); db.createobjectstore(storename) }; }); } looking up modules in the database our next function — lookupindatabase() — provides a simple promise-based operation for looking up the given url in the object store we created above. it resolves with the stored compiled module, or rejects with an
error. ...
...And 4 more matches
passwords - Archive of obsolete content
r the url. so: if a web server at http://www.example.com requested authentication with a response code like this: http/1.0 401 authorization required server: apache/1.3.27 www-authenticate: basic realm="exampleco login" the corresponding values for the credential (excluding username and password) should be: url: "http://www.example.com" realm: "exampleco login" oncomplete and on
error this api is explicitly asynchronous, so all its functions take two callback functions as additional options: oncomplete and on
error. oncomplete is called when the operation has completed successfully and on
error is called when the function encounters an
error. because the search function is expected to return a list of matching credentials, its oncomplete option is mandatory. because the other...
... globals functions search(options) this function is used to retrieve a credential, or a list of credentials, stored in the password manager. you pass it any subset of the possible properties a credential can contain. credentials which match all the properties you supplied are returned as an argument to the oncomplete callback. ...
...ing for http authentication credentials, the realm for which the credential was requested. for add-on credentials, a name for the credential. usernamefield 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. on
error 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 nsiexception 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 ...
...And 3 more matches
Rosetta - Archive of obsolete content
nattr++) { ocompiled.setattribute(aattrs[nattr].name, aattrs[nattr].value); } ocompiled.type = "text\/ecmascript"; if (oxhr200) { ocompiled.src = "data:text\/javascript," + encodeuricomponent(odicts[smimetype](oxhr200.responsetext)); } ocompiled.text = oxhr200 ? ...
...) { ocompiled.setattribute(aattrs[nattr].name, aattrs[nattr].value); } ocompiled.type = "text\/ecmascript"; if (oxhr200) { ocompiled.src = "data:text\/javascript," + encodeuricomponent(odicts[smimetype](oxhr200.responsetext)); } ocompiled.text = oxhr200 ? ...
...ribute(aattrs[nattr].name, aattrs[nattr].value); } ocompiled.type = "text\/ecmascript"; if (oxhr200) { ocompiled.src = "data:text\/javascript," + encodeuricomponent(odicts[smimetype](oxhr200.responsetext)); } ocompiled.text = oxhr200 ? ...
...And 3 more matches
Setting up an extension development environment - Archive of obsolete content
n about mozilla preferences, refer to the mozillazine article on "about:config". tip: you can install either the developer profile or devprefs add-ons to handle setting these preferences automatically, and skip the rest of this section. devprefs can now be found at https://github.com/noitidart/devprefs. maxversion needs to be set in install.rdf javascript.options.showinconsole = true. logs
errors in chrome files to the
error console. nglayout.debug.disable_xul_cache = true. disables the xul cache so that changes to windows and dialogs do not require a restart. this assumes you're using directories rather than jars. changes to xul overlays will still require reloading of the document overlaid. browser.dom.window.dump.enabled = true. enables the use of the dump() statement to print to th...
...ories rather than jars. changes to xul overlays will still require reloading of the document overlaid. browser.dom.window.dump.enabled = true. enables the use of the dump() statement to print to the standard console. see window.dump for more info. you can use nsiconsoleservice instead of dump() from a privileged script. javascript.options.strict = true. enables strict javascript warnings in the
error console. note that since many people have this setting turned off when developing, you will see lots of warnings for problems with their code in addition to warnings for your own extension. you can filter those with console2. devtools.chrome.enabled = true. this enables to run javascript code snippets in the chrome context of the scratchpad from the tools menu. don't forget to switch from conten...
...bug the javascript code of extensions. the devtools.chrome.enabled preference must also be set to true for the browser debugger to be enabled. devtools.debugger.prompt-connection = false. this prevents the browser debugger from prompting for connection permission every time. extensions.logging.enabled = true. this will send more detailed information about installation and update problems to the
error console. (note that the extension manager automatically restarts the application at startup sometimes, which may mean you won't have time to see the messages logged before 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+...
...And 3 more matches
Dehydra Function Reference - Archive of obsolete content
directory is searched last. includes are guarded so a file is only included once and subsequent include calls are ignored. this is accomplished by recording every included file into the _includedarray in the current namespace. include example include("map.js") // includes map.js into toplevel var map = {} include("map.js", map) // includes map.js into the map object require({version:, strict:, w
error:, gczeal:}) require is used to set runtime execution flags. it also returns the current values of these flags. require supports optional named arguments via javascript object where each parameter is a property. if a property is not specified then it will not be passed to the runtime. version integer: this sets js version similar to version() in js 1.7. strict boolean: controls js strict mode wer...
...runtime execution flags. it also returns the current values of these flags. require supports optional named arguments via javascript object where each parameter is a property. if a property is not specified then it will not be passed to the runtime. version integer: this sets js version similar to version() in js 1.7. ...
... optional: code is an integer parameter that allows warnings to be enabled(-wfoo) and disabled(-wno-) on the gcc commandline. ...
...And 3 more matches
Building XULRunner with Python - Archive of obsolete content
n script access to the dom and xpcom in addition to the usual java script. this gives access to python features and modules and builds on mark hammond's pyxpcom work from active state. xpcom components can also be created in python. currently (mar 07) python is not enabled by default so a custom build of mozilla is needed. this page provides instructions in the hope of eliminating much trial and
error. you should also read the the developer documentation on source code and building as wells as pyxpcom xulrunner with python promises to be a good platform for accessibility projects and both jambu alternative input and the iaccessible2 test tool are using it. of particular interested is access to msaa and iaccessible2 via the python comtypes package. development machine setup first a word of...
...runner with python promises to be a good platform for accessibility projects and both jambu alternative input and the iaccessible2 test tool are using it. of particular interested is access to msaa and iaccessible2 via the python comtypes package. development machine setup first a word of warning that zonealarm has exhibited memory leaks that cause build machines to crash with rather spurious
errors. you may want to uninstall it if you suspect this to be a problem. you will also want to disable any virus scanner resident monitoring as that will slow builds. ensure the pc is running xp with all the latest service packs and patches applied. microsoft c++ compiler is required and whilst the current free version is visual studio 8 express (msvc8) you will almost certainly want to use visual s...
...oad', 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["@mozilla.org/embedcomp/window-watcher;1"]...
...And 3 more matches
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
s compatibility reasons if you don't tell mozilla that you support it it will try to hand you an xt widget as a parent. however, before you do so you should make sure that the browser also supports xembed when the plugin is first initialized. if you've built your plugin so that it will support either xt or xembed you can include a fallback for older style hosting. ...
...g. if you haven't you can return an
error and the plugin will be ignored. it's good practice to do this in case people try to install your plugin for older versions of the browser that don't support xembed functionality. this is an incomplete example of what a piece of code might look like that tries to check for the proper mozilla version. this would be included in your np_initialize function. np
error np_initialize(npnetscapefuncs* nstable, nppluginfuncs* pluginfuncs) { np
error err = nperr_no_
error; prbool supportsxembed = pr_false; npntoolkittype toolkit = 0; [ code that copies all of the function tables and does ] [ other standard checks ] /* * make sure that the browser supports functionality we care * about. */ er...
...opies all of the function tables and does ] [ other standard checks ] /* * make sure that the browser supports functionality we care * about. ...
...And 3 more matches
Troubleshooting XForms Forms - Archive of obsolete content
troubleshooting check the file type is the page parsed as an xhtml document? right-click on a blank spot on the page, and select view page info. the type field should say application/xhtml+xml. ...
... troubleshooting check the file type is the page parsed as an xhtml document? right-click on a blank spot on the page, and select view page info. the type field should say application/xhtml+xml. ...
... troubleshooting check the file type is the page parsed as an xhtml document? right-click on a blank spot on the page, and select view page info. the type field should say application/xhtml+xml. ...
...And 3 more matches
Implementation Status - Archive of obsolete content
ttributes supported 3.2.2 linking attributes supported 3.2.3 single-node binding attributes supported 3.2.4 node-set binding attributes supported 3.2.5 model item property attributes partial in some cases a loop
error can occur on valid bindings 302168; 3.3.1 model supported 3.3.2 instance partial instance element with two child element does not trigger exception 337302; 3.3.3 submission partial no support for @indent and complex schema validation 278761; 278762; 3.3...
... 333782; 4.5.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. ...
...And 3 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
s glossary: definitions of web-related terms beginner, definitions, dictionary, glossary, index, landing, terminology web technologies contain long lists of jargon and abbreviations that are used in documentation and coding. this glossary provides definitions of words and abbreviations you need to know to successfully understand and build for the web. 2 404 glossary, http
errors, infrastructure, navigation a 404 is a standard response code meaning that the server cannot find the requested resource. 3 502 502, bad gateway, glossary, http
errors, infrastructure, navigation an http
error code meaning "bad gateway". 4 alpn alpn, draft, glossary, needscontent, tls application-layer protocol negotiation (alpn) is a tls extension...
...sage. 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 specification: 138 ftp codingscripting, ftp, glossary, protocol ftp (file transfer protocol) was the standard protocol for many ye...
...tcp, web performance, payload a packet, or network packet, is a formatted chunk of data sent over a network. the maincomponents of a network packet are the user data and control information. the user data is known as the payload. the control information is the information for delivering the payload. it consists of network addresses for the source and destination, sequencing information, and
error detection codes and is generally found in packet headers and footer. 313 page load time glossary, timings, web performance, metrics, page load time page load time is the time it takes for a page to load, measured from navigation start to the start of the load event 314 page prediction glossary, security, web performance, page prediction page prediction is...
...And 3 more matches
Packet - MDN Web Docs Glossary: Definitions of Web-related terms
a packet, or network packet, is a formatted chunk of data sent over a network. the maincomponents of a network packet are the user data and control information. the user data is known as the payload. the control information is the information for delivering the payload. it consists of network addresses for the source and destination, sequencing information, and
error detection codes and is generally found in packet headers and footer. a packet contains: hop limit a hop occurs when a packet is passed from one network to the next network. it is a field that is decreases by one each time a packet goes through, once it reaches 0 it has failed and the packet is discarded. over time the number packets can cause traversing within closed circuits, the number of pa ckets circulatin...
... a hop occurs when a packet is passed from one network to the next network. it is a field that is decreases by one each time a packet goes through, once it reaches 0 it has failed and the packet is discarded. over time the number packets can cause traversing within closed circuits, the number of pa ckets circulating would build up and then ultimately lead to the networking in failing. ...
...ed from one network to the next network. it is a field that is decreases by one each time a packet goes through, once it reaches 0 it has failed and the packet is discarded. over time the number packets can cause traversing within closed circuits, the number of pa ckets circulating would build up and then ultimately lead to the networking in failing. ...
...And 3 more matches
How do you make sure your website works properly? - Learn web development
er can display the version from its cache, resulting in faster response times and more efficient use of bandwidth. 403: forbidden you aren't allowed to display the resource. usually it has to do with a configuration mistake (e.g. your hosting provider forgot to give you access rights to a directory). 404: not found self-explanatory. we'll discuss how to solve this below. 500: internal server
error something went wrong on the server. for instance, maybe the server-side language (php, .net, etc.) stopped working, or the web server itself has a configuration problem. usually it's best to resort to your hosting provider's support team. 503: service unavailable usually resulting from a shortterm system overload. the server has some sort of problem. try again in a little while. as beginn...
... save, push to the server, and reload the page in your browser: there you go! let's look at the http statuses again: 200 for / and for unicorn_pic.png means that we succeeded in reloading the page and the image. 304 for basic.css means that this file has not changed since the last request, so the browser can use the file in its cache rather than receiving a fresh copy. ...
...er: there you go! let's look at the http statuses again: 200 for / and for unicorn_pic.png means that we succeeded in reloading the page and the image. 304 for basic.css means that this file has not changed since the last request, so the browser can use the file in its cache rather than receiving a fresh copy. ...
...And 3 more matches
Storing the information you need — Variables - Learn web development
n you are writing multiple lines of code together. try to get into the habit of including it. you can test whether these values now exist in the execution environment by typing just the variable's name, e.g. myname; myage; they currently have no value; they are empty containers. when you enter the variable names, you should get a value of undefined returned. if they don't exist, you'll get an
error message — try typing in scoobydoo; note: don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all — they are very different things. in the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. no value defined would mean that there is a box, but it has no value inside it. initializing a variable ...
...logname() { console.log(myname); } logname(); var myname; note: this won't work when typing individual lines into a javascript console, just when running multiple lines of javascript in a web document. this works because of hoisting — read var hoisting for more detail on the subject. hoisting no longer works with let. if we changed var to let in the above example, it would fail with an
error. ...
...there is no reason to redeclare variables — it just makes things more confusing. ...
...And 3 more matches
Listening to events on all tabs
talprogress the current progress for all requests associated with webprogress. amaxtotalprogress the total progress for all requests associated with webprogress. onsecuritychange notification called for security progress. this method will be called on security transitions (eg http -> https, https -> http, foo -> https) and after document load completion. it might also be called if an
error occurs during network loading. note: these notifications will only occur if a security package is installed. void onsecuritychange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest arequest, unsigned long astate ); parameters abrowser the browser that fired the notification. awebprogress the nsiwebprogress instance that fired the notification. are...
... arequest the nsirequest that has changed state. this parameter may be null. need more information on what null means. astateflags flags indicating the new state. this value is a combination of one of the state transition flags and one or more of the state type flags defined in the nsiwebprogresslistener documentation. any undefined bits are reserved for future use. ...
...onstatuschange notification that the status of a request has changed. ...
...And 3 more matches
Assert.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://testing-common/assert.jsm"); the assert class offers methods for performing common logical assertions. ...
... undefined less(lhs, rhs, message); undefined lessorequal(lhs, rhs, message); undefined setreporter(reporterfunc); undefined report(failed, actual, expected, message, operator); constructor creates a new assert object. let assert = new assert(reporterfunc); the new assert instance, assert, uses reporterfunc to report assertion results or throws an assertion
error when an assertion fails, as default behavior. ok, equal, notequal, deepequal, notdeepequal, strictequal, notstrictequal, throws, setreporter, report methods ok() pure assertion tests whether a value is truthy, as determined by !!guard. this statement is equivalent to assert.equal(true, !!guard, message_opt);. to test strictly for the value true, use assert.strictequal(true, guard, message_op...
...ult notstrictequal() the strict non-equality assertion tests for strict inequality, as determined by !==. undefined notstrictequal( actual, expected, message ); parameters actual test subject to be evaluated as not strictly equivalent to expected expected test reference to evaluate against actual message short explanation of the expected result throws() expected to throw an
error. undefined throws( block, expected, message ); parameters block function block to evaluate and catch eventual thrown
errors expected test reference to evaluate against the thrown result from block message short explanation of the expected result rejects() expected to reject a promise. returns a promise that resolves when the promise either resolves or rejects. promise rejects...
...And 3 more matches
NetUtil.jsm
stream.init(file, -1, -1, 0); // finally, we need an input stream to take data from. const test_data = "this is a test string"; let istream = cc["@mozilla.org/io/string-input-stream;1"]. createinstance(ci.nsistringinputstream); istream.setdata(test_data, test_data.length); netutil.asynccopy(istream, ostream, function(aresult) { if (!components.issuccesscode(aresult)) { // an
error occurred! } }) asyncfetch() the asyncfetch() method opens an input source, asynchronously, and gives an nsiinputstream containing the data obtained to the callback provided. the callback may then consume data from the input stream passed to the callback. note: prior to gecko 2, the input source was required to be specified as an nsichannel. note: support for specifying an nsiinputstream...
...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; } // consume the input stream. }); remarks note: if you specify an nsichannel as the input source, and its notification callbacks have already been set, callers are responsible for implementing nsibadcertlistener and nsissl
errorlistener. newchannel() creates a new channel for the specified uri string, nsiuri, or nsifile. nsichannel newchannel( awhattoload, [optional] aor...
... 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. string readinputstreamtostring( ainputstream, acount, aoptions ); parameters ainputstream the input stream from which to read...
...And 3 more matches
Encrypt Decrypt MAC Keys As Session Objects
"could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { pr_fprintf(pr_stderr, "pk11_findfixedkey failed (err %d)\n", pr_get
error()); pk11_freeslot(slot); return null; } return key; } /* * decrypt and verify mac */ secstatus decryptandverifymac(const char* outfilename, char *encryptedfilename, secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned ...
... if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count == filelength) { decbuflen = decbuflen-paddinglength; } /* write the plain text to out file */ temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write
error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac,...
... generatesymkey(slot, ckm_generic_secret_key_gen, 160/8, &mackeyid, pwdata); if (mackey == null) { pr_fprintf(pr_stderr, "generatesymkey for macing returned null.\n"); rv = secfailure; goto cleanup; } /* get the encrypt key cka_id */ rv = gathercka_id(enckey, &encckaid); if (rv != secsuccess) { pr_fprintf(pr_stderr, "
error while wrapping encrypt key\n"); goto cleanup; } /* get the mac key cka_id */ rv = gathercka_id(mackey, &macckaid); if (rv != secsuccess) { pr_fprintf(pr_stderr, "can't get the mac key cka_id.\n"); goto cleanup; } if (noisefilename) { rv = seedfromnoisefile(noisefilename); if (rv != secsuccess) { port_set
error(pr_end_of_...
...And 3 more matches
Encrypt and decrypt MAC using token
"could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { pr_fprintf(pr_stderr, "pk11_findfixedkey failed (err %d)\n", pr_get
error()); pk11_freeslot(slot); return null; } return key; } /* * decrypt and verify mac */ secstatus decryptandverifymac(const char* outfilename, char *encryptedfilename, secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned ...
... if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count == filelength) { decbuflen = decbuflen-paddinglength; } /* write the plain text to out file */ temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write
error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac,...
... generatesymkey(slot, ckm_generic_secret_key_gen, 160/8, &mackeyid, pwdata); if (mackey == null) { pr_fprintf(pr_stderr, "generatesymkey for macing returned null.\n"); rv = secfailure; goto cleanup; } /* get the encrypt key cka_id */ rv = gathercka_id(enckey, &encckaid); if (rv != secsuccess) { pr_fprintf(pr_stderr, "
error while wrapping encrypt key\n"); goto cleanup; } /* get the mac key cka_id */ rv = gathercka_id(mackey, &macckaid); if (rv != secsuccess) { pr_fprintf(pr_stderr, "can't get the mac key cka_id.\n"); goto cleanup; } if (noisefilename) { rv = seedfromnoisefile(noisefilename); if (rv != secsuccess) { port_set
error(pr_end_of_...
...And 3 more matches
NSS 3.21 release notes
ey_derive_dh - derives tls 1.2 master secret for dh (and ecdh) cipher suites ckm_tls12_key_safe_derive and ckm_tls_kdf are identifiers for additional pkcs#12 mechanisms for tls 1.2 that are currently unused in nss. ...
...1.2 master secret for dh (and ecdh) cipher suites ckm_tls12_key_safe_derive and ckm_tls_kdf are identifiers for additional pkcs#12 mechanisms for tls 1.2 that are currently unused in nss. ...
...nd ckm_tls_kdf are identifiers for additional pkcs#12 mechanisms for tls 1.2 that are currently unused in nss. ...
...And 3 more matches
NSS API Guidelines
h, pkcs11.h, pkcs11f.h, pkcs11p.h, pkcs11t.h, pkcs11u.h ssl provides an implementation of the ssl protocol using nss and nspr. ssl lib/ssl ssl.h, sslerr.h, sslproto.h, preenc.h secutil provides utility functions and data types used by other libraries. the library supports base-64 encoding/decoding, reader-writer locks, the secitem data type, der encoding/decoding,
error types and numbers, oid handling, and secure random number generation. utility for any layer lib/util base64.h, ciferfam.h, nssb64.h, nssb64t.h, nsslocks.h, nssrwlk.h, nssrwlkt.h, portreg.h, pqgutil.h, secasn1.h, secasn1t.h, seccomon.h, secder.h, secdert.h, secdig.h, secdigt.h, secitem.h, secoid.h, secoidt.h, secport.h, secrng.h, secrngt.h, secerr.h, watcomfx.h naming conventions ...
...ty all these are useful, but they don't combine well. now some of the pointer-tracking pressure has eased off, we can drop its use when it becomes too difficult. many routines are defined to take an nssarena *arenaopt argument. this means if an arena is specified (non-null), it is used, otherwise (null) the routine uses the heap. you can think of the heap as a default arena you can't destroy. ...
...l. now some of the pointer-tracking pressure has eased off, we can drop its use when it becomes too difficult. many routines are defined to take an nssarena *arenaopt argument. this means if an arena is specified (non-null), it is used, otherwise (null) the routine uses the heap. you can think of the heap as a default arena you can't destroy.
error handling nss 3.0 introduces the concept of an
error stack. when something goes wrong, the call stack unwinds, with routines returning an
error indication. each level which flags a problem, adds its own
error number to the stack. at the bottom of the stack is the fundamental
error, for example: file not found, and on top is an
error precisely relating to what you are doing. note:
error stacks are vertical, and never horizontal. if multiple things...
...And 3 more matches
OLD SSL Reference
tion needs for communicating with cryptographic modules. in particular, these functions are used for obtaining certificates, keys, and passwords. ...
...nicating with cryptographic modules. in particular, these functions are used for obtaining certificates, keys, and passwords. ...
...e functions are used for obtaining certificates, keys, and passwords. ...
...And 3 more matches
NSS_3.12.3_release_notes.html
pr 4.7.4 header files and shared libraries, which nss 3.12.3 requires. nspr 4.7.4 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.4/. new in nss 3.12.3 changes in behavior: in the development of nss 3.12.3, it became necessary to change some old library behaviors due to the discovery of certain vulnerabilities in the old behaviors, and to correct some
errors that had limited nss's ability to interoperate with cryptographic hardware and software from other sources. most of these changes should cause no problems for nss users, but in some cases, some customers' software, hardware and/or certificates may be dependent on the old behaviors, and may have difficulty with the new behaviors. in anticipation of that, the nss team has provided ways to...
... nss 3.12.3. nss_hash_alg_support string specifies algorithms allowed to be used in certain applications, such as in signatures on certificates and crls. see documentation at this link. nss_strict_nofork string ("1", "disabled", or any other non-empty value) it is an
error to try to use a pkcs#11 crypto module in a process before it has been initialized in that process, even if the module was initialized in the parent process. beginning in nss 3.12.3, softoken will detect this
error. this environment variable controls softoken's response to that
error. if set to to "1" or unset, softoken will trigger an assertion failure in debug builds, ...
...cs#11 crypto module in a process before it has been initialized in that process, even if the module was initialized in the parent process. beginning in nss 3.12.3, softoken will detect this
error. this environment variable controls softoken's response to that
error. if set to to "1" or unset, softoken will trigger an assertion failure in debug builds, and will report an
error in non-debug builds. if set to "disabled", softoken will ignore forks, and behave as it did in older versions. if set to any other non-empty value, softoken will report an
error in both debug and non-debug builds. nss_use_decoded_cka_ec_point boolean (any non-empty value to enable) tell...
...And 3 more matches
JSAPI reference
ete since jsapi 8 you can also compile javascript code into a function: struct jsfunction js::compilefunction 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 js
errorformatstring added in spidermonkey 17 class js
errorreport class js::autosaveexceptionstate added in spidermonkey 31 enum jsexntype added in spidermonkey 17 js_report
error js_reportwarning js_report
errornumber js_report
errornumberuc js_report
errorflagsandnumber js_report
errorflagsandnumberuc js_report
errornumberucarray added in spidermonkey 24 js_reportoutofmem...
...class js
errorreport class js::autosaveexceptionstate added in spidermonkey 31 enum jsexntype added in spidermonkey 17 js_report
error js_reportwarning js_report
errornumber js_report
errornumberuc js_report
errorflagsandnumber js_report
errorflagsandnumberuc js_report
errornumberucarray added in spidermonkey 24 js_reportoutofmemory js_reportallocationoverflow added in spidermonkey 1.8 js_get
errorreporter js_set
errorreporterobsolete since jsapi 52 js_
errorfromexception js_get
errorprototype 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::create
error added in spidermonkey 38 js_isexceptionpending js_getpendingexception js_setpendingexception j...
...ow and catch javascript exceptions: js::create
error added in spidermonkey 38 js_isexceptionpending js_getpendingexception js_setpendingexception js_clearpendingexception js_throwstopiteration added in spidermonkey 1.8 js_isstopiteration added in spidermonkey 31 typedef jsexceptionstate js_saveexceptionstate js_restoreexceptionstate js_dropexceptionstate these functions translate
errors into exceptions and vice versa: js_reportpendingexception js_
errorfromexception js_throwreported
error obsolete since jsapi 29 values and types typedef jsval js::value js::value constructors: js::nullvalue added in spidermonkey 24 js::undefinedvalue added in spidermonkey 24 js::booleanvalue added in spidermonkey 24 js::truevalue added in spidermonkey 24 js::falsevalue add...
...And 3 more matches
imgIContainer
bsolete 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 currentframeindex unsigned long the index ...
... currentframeindex unsigned 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 ...
... 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 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-progres...
...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 only. obso...
...ching 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 to use nsiaccessible...
...primitivevalue 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(). domstring getcomputedstyle...
...And 3 more matches
nsIContentPrefCallback2
this will be called exactly once for each method invocation, and afterward no other callback methods will be called. void handlecompletion( in unsigned short reason ); ...
...this will be called exactly once for each method invocation, and afterward no other callback methods will be called. void handlecompletion( in unsigned short reason ); ...
...gecko 20.0 inherits from: nsisupports last changed in gecko 20.0 (firefox 20.0 / thunderbird 20.0 / seamonkey 2.17) method overview void handlecompletion(in unsigned short reason); void handle
error(in nsresult
error); void handleresult(in nsicontentpref pref); constants constant value description complete_ok 0 complete_
error 1 methods handlecompletion() called when the method finishes. ...
...And 3 more matches
nsIContentPrefService
avascript 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 preferences are to be r...
...re 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
nsIDownloadManager
read only. constants constant value description download_notstarted -1 the download has not been started yet. download_downloading 0 the download is in the process of being downloaded. download_finished 1 download completed including any processing of the target file. download_failed 2 the download failed due to
error. download_canceled 3 the user canceled the download. download_paused 4 the download is currently paused. download_queued 5 the download is in the queue but is not presently downloading. download_blocked_parental 6 the download has been blocked, either by parental controls or the virus scanner determining that a file is infected and cann...
...he 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 (firefox 3.5 / thunde...
...o 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 managers to let us know ...
...And 3 more matches
nsIScriptableIO
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. nsiscriptableio provides a convenient api for creating files and streams, as well as for reading and writing data to them. for your convenience, this api is published through a global io object. for more details about how to use this object, see the file and stream guide. network/base/public/nsiscriptableio.idlscriptable please add a summary to this article. last changed in geck...
...string 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 ); parameters afil...
...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 specified string or file. e...
...And 3 more matches
nsIWebProgressListener
extended validation == high assurance. the topmost document uses an ev cert. location change flags constant value description location_change_same_document 0x00000001 this flag is on when awebprogress did not load a new document. for example, the location change is due to an anchor scroll or a pushstate/popstate/replacestate. location_change_
error_page 0x00000002 this flag indicates that awebprogress redirected from the requested document to an internal page to show
error status, such as about:net
error, about:cert
error and so on. methods onlocationchange() called when the location of the window being watched changes. this is not when a load is requested, but rather once it is verified that the load is going to occur in the ...
...gress the current progress for all requests associated with awebprogress. amaxtotalprogress the total progress for all requests associated with awebprogress. onsecuritychange() notification called for security progress. this method will be called on security transitions (for example http -> https, https -> http, foo -> https) and after document load completion. it might also be called if an
error occurs during network loading. note: these notifications will only occur if a security package is installed. void onsecuritychange( in nsiwebprogress awebprogress, in nsirequest arequest, in unsigned long astate ); parameters awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has new security state. astate a value composed of the s...
...astatus ); parameters awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has changed state. this parameter may be null. astateflags flags indicating the new state. this value is a combination of one of the state transition flags and one or more of the state type flags defined above. any undefined bits are reserved for future use. astatus
error status code associated with the state change. this parameter should be ignored unless astateflags includes the state_stop bit. the status code indicates success or failure of the request associated with the state change. note: astatus may be a success code even for server generated
errors, such as the http 404 file not found
error. in such cases, the request itself should be queried for extended ...
...And 3 more matches
nsIMsgCloudFileProvider
as such, the type should be an alphanumpheric string with no spaces. displayname acstring readonly: used for displaying the service name in the user interface. ...
...as such, the type should be an alphanumpheric string with no spaces. displayname acstring readonly: used for displaying the service name in the user interface. serviceurl acstrin...
...per size limit in bytes for a file to be uploaded. if this value is not known, returns -1. remainingfilespace long long readonly: the remaining storage space available for this account in bytes. if this value is not known, returns -1. filespaceused long long readonly: the total amount of space used by this account. if this value is not known, returns -1. last
error acstring readonly: the last
error message received from the server. constants the following constants are used for the status codes passed to the onstoprequest functions of the nsirequestobserver's used by the asynchronous methods of nsimsgcloudfileprovider. constant value description offlineerr 0x80550014 returned when it appears that there is no acti...
...And 3 more matches
Drawing and Event Handling - Plugins
print.window contains the window in which the plug-in should print. on ms windows, note that the coordinates for the window rectangle are in twips format. for this reason, you need to convert the x - and y - coordinates using the windows api call dptolp when you output text. ...
... the window parameter is a pointer to the drawing target for the plug-in. for windowless plug-ins, the platform-specific window information specified in window->window is a platform-specific handle to a drawable. ...
...ecified in window->window is a platform-specific handle to a drawable. ms windows and unix for windowed plug-ins on ms windows and unix, the window->window field is a handle to a subwindow of the netscape window hierarchy. mac os the window->window field points to an np_port structure. getting information to receive information from the browser, the plug-in calls the npn_getvalue method. np
error npn_getvalue(npp instance, npnvariable variable, void *value); the instance parameter represents the current plug-in. unix and ms windows the queried information is returned in the variable parameter. this parameter is valid only for the unix and ms windows platforms. for unix, the values are either the current display (npnvxdisplay) or the application's context (npnvxtappcontext). for ms win...
...And 3 more matches
Initialization and Destruction - Plugins
-ins consume no resources, other than disk space, if not referenced. this chapter ends with initialize and shutdown example, which includes the np_initialize and np_shutdown methods. initialization the browser calls np_initialize when a plug-in is loaded and before the first instance is created. use this function to allocate the memory and resources shared by all instances of your plug-in. np
error np_initialize(void) { }; after the last plug-in instance is deleted, the browser calls np_shutdown, which releases the memory or resources allocated by np_initialize. for an example that shows the use of both the np_initialize and np_shutdown methods, see initialize and shutdown example. during initialization, when the browser encounters data of a mime type registered for a plug-in (either em...
...ws are open and display the same data type. at this point, a plug-in can call the npn_setvalue function to specify whether it is windowed (the default) or windowless. plug-in instances are created with npp_new and destroyed with npp_destroy. npp_new informs the plug-in of the creation of a new instance with the specified mime type. you can allocate instance-specific private data at this time. np
error npp_new(npmimetype plugintype, npp instance, uint16 mode, int16 argc, char *argn[], char *argv[], npsaveddata *saved); the plugintype parameter represents the mime type of this instance of the plug-in. you can assign more than one mime type to a plug-in, which could potentially allow the plug-in to respond to data streams of different types with d...
... has left the page containing the instance, closed the window, or quit the application. if this is the last instance created by a plug-in, np_shutdown is called. you should not perform any graphics operations in npp_destroy because the instance window is no longer guaranteed to be valid. also, be sure to delete any private instance-specific information stored in the plug-in's instance->pdata. np
error npp_destroy(npp instance, npsaveddata **save); the instance parameter represents the plug-in instance to delete. the plug-in can use the optional save parameter to save data for reuse by a new instance with the same url. the data is passed to npp_new through its saved parameter. for example, a video player could save the last frame number to be displayed. when the user returns to the page, the...
...And 3 more matches
Browser Console - Firefox Developer Tools
however, rather than logging this information for a single content tab, it logs information for all content tabs, for add-ons, and for the browser's own code. ...
...nt process (i.e. the messages from scripts in all the opened pages) by setting or clearing the checkbox labeled show content messages. the following image shows the browser console focused on the same page as above after clicking on the show content messages checkbox. browser console logging the browser console logs the same sorts of messages as the web console: http requests warnings and
errors (including javascript, css, security warnings and
errors, and messages explicitly logged by javascript code using the console api). input/output messages: commands send to the browser via the command line, and the result of executing them. however, it displays such messages from: web content hosted by all browser tabs the browser's own code add-ons. messages from add-ons the browser c...
...lient/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); var clearbtn = hud.chromewindow.document.queryselector('.webconsole-clear-console-button'); clearbtn.addeventlistener('mouseover', function() { hud.jsterm.clearoutput(true); }, false); bonus features available for add-on sdk add-ons, the console api is available automatically. ...
...And 3 more matches
console.assert() - Web APIs
if the assertion is true, nothing happens. note: this feature is available in web workers. syntax console.assert(assertion, obj1 [, obj2, ..., objn]); console.assert(assertion, msg [, subst1, ..., substn]); // c-like message formatting parameters assertion any boolean expression. if the assertion is false, the message is written to the console. obj1 ... objn a list of javascript objects to output. the string representations of each of these objects are appended together in the order listed and output. msg a javascript string containing zero or more substitution strings. subst1 ... ...
...ed together in the order listed and output. msg a javascript string containing zero or more substitution strings. subst1 ... substn javascript objects with which to replace substitution strings within msg. this parameter gives you additional control over the format of the output. ...
...ce substitution strings within msg. this parameter gives you additional control over the format of the output. ...
...And 3 more matches
Constraint validation API - Web APIs
lements listed below with a number of new properties and methods (elements that can have a form attribute that indicates their form owner): htmlbuttonelement htmlfieldsetelement htmlinputelement htmlobjectelement htmloutputelement htmlselectelement htmltextareaelement properties validity a read-only property that returns a validitystate object, whose properties represent validation
errors for the value of that element. validationmessage a read-only property that returns an empty string if the element is not a candidate for constraint validation, or if the element's value is valid. if the element's value is not valid, it returns a localized validation message. this will be displayed in the ui if the element is the only form control with a validity problem; if a custom
error mess...
...ise it returns true. reportvalidity() htmlformelement method checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. otherwise, it returns true. setcustomvalidity(message) sets a custom
error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. to clear this state, invoke the function with an empty string passed as its argument. in this case the custom
error message is cleared, the element is considered valid, and no message is shown. examples take the following form: ...
...the custom
error message is cleared, the element is considered valid, and no message is shown. examples take the following form: <form> <label for="name">enter username (upper and lowercase letters): </label> <input type="text" name="name" id="name" required pattern="[a-za-z]+"> <button>submit</button> </form> the basic html form validation features will cause this to produce a default
error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. ...
...And 3 more matches
FileSystemEntry.copyTo() - Web APIs
d by the entry to a new location on the file system. there are some typical restrictions on what you can do: a directory can't be copied into itself. an entry can't be copied into its parent directory unless you specify a new name. when copying a directory, the copy is always recursive; you can't leave out subfolders. syntax filesystementry.copyto(newparent[, newname][, successcallback][,
errorcallback]); parameters newparent a filesystemdirectoryentry object specifying the destination directory for the copy operation. newname optional if this parameter is provided, the copy is given this string as its new file or directory name. successcallback optional a function which is called when the copy operation is succesfully completed. receives a single input parameter: a filesysteme...
...ntry object specifying the destination directory for the copy operation. newname optional if this parameter is provided, the copy is given this string as its new file or directory name. successcallback optional a function which is called when the copy operation is succesfully completed. receives a single input parameter: a filesystementry based object providing the copied item's new details. ...
...on. newname optional if this parameter is provided, the copy is given this string as its new file or directory name. successcallback optional a function which is called when the copy operation is succesfully completed. receives a single input parameter: a filesystementry based object providing the copied item's new details.
errorcallback optional an optional callback which is executed if an
error occurs while copying the items. ...
...And 3 more matches
FileSystemEntry.moveTo() - Web APIs
move is always recursive; you can't leave out subfolders. you can't move a file such that it replaces an existing directory, and you can't move a directory such that it replaces an existing file. however, a file can replace a file and a directory can replace a directory. you can only overwrite a directory if it's empty. syntax filesystementry.moveto(newparent[, newname][, successcallback][,
errorcallback]); parameters newparent a filesystemdirectoryentry object specifying the destination directory for the move operation. newname optional if this parameter is provided, the entry is renamed to have this string as its new file or directory name. successcallback optional a function which is called when the move operation is succesfully completed. receives a single input parameter: a ...
...t specifying the destination directory for the move operation. newname optional if this parameter is provided, the entry is renamed to have this string as its new file or directory name. successcallback optional a function which is called when the move operation is succesfully completed. receives a single input parameter: a filesystementry based object providing the moved item's new details. ...
...me optional if this parameter is provided, the entry is renamed to have this string as its new file or directory name. successcallback optional a function which is called when the move operation is succesfully completed. receives a single input parameter: a filesystementry based object providing the moved item's new details.
errorcallback optional an optional callback which is executed if an
error occurs while moving the items. ...
...And 3 more matches
FileSystemEntry.remove() - Web APIs
the filesystementry interface's method remove() deletes the file or directory from the file system. directories must be empty before they can be removed. to recursively remove a directory as well as all of its contents and its subdirectories, call filesystemdirectoryentry.removerecursively() instead. ...
...ry from the file system. directories must be empty before they can be removed. to recursively remove a directory as well as all of its contents and its subdirectories, call filesystemdirectoryentry.removerecursively() instead. syntax filesystementry.remove(successcallback[,
errorcallback]); parameters successcallback a function which is called once the file has been successfully removed.
errorcallback optional an optional callback which is called if the attempt to remove the file fails. return value undefined. ...
...f its contents and its subdirectories, call filesystemdirectoryentry.removerecursively() instead. syntax filesystementry.remove(successcallback[,
errorcallback]); parameters successcallback a function which is called once the file has been successfully removed.
errorcallback optional an optional callback which is called if the attempt to remove the file fails. return value undefined.
errors file
error.invalid_modification_err the specified entry was the file system's root directory, or the specified entry is a directory which isn't empty. ...
...And 3 more matches
FileSystemFileEntry.file() - Web APIs
the filesystemfileentry interface's method file() returns a file object which can be used to read data from the file represented by the directory entry. syntax filesystemfileentry.file(successcallback[,
errorcallback]); parameters successcallback a callback function which is called when the file has been created successfully; the file is passed into the callback as the only parameter.
errorcallback optional if provided, this must be a method which is called when an
error occurs while trying to create the file. this callback receives as input a file
error object describing the
error. editor's note: we need to find out what kinds of
errors can occur and document them. return value undefined. example this example establishes a method, readfile(), reads a text file and calls a sp...
...o create the file. this callback receives as input a file
error object describing the
error. editor's note: we need to find out what kinds of
errors can occur and document them. return value undefined. example this example establishes a method, readfile(), reads a text file and calls a specified callback function with the received text (in a string object) once the read is completed. if an
error occurs, a specified (optional)
error callback is called. ...
...te: we need to find out what kinds of
errors can occur and document them. return value undefined. example this example establishes a method, readfile(), reads a text file and calls a specified callback function with the received text (in a string object) once the read is completed. if an
error occurs, a specified (optional)
error callback is called. ...
...And 3 more matches
Fullscreen API - Web APIs
fullscreenenabled property tells you whether or not it is possible to engage full-screen mode. this is false if full-screen mode is not available for any reason (such as the "fullscreen" feature not being allowed, or full-screen mode not being supported). event handlers the fullscreen api defines two events which can be used to detect when full-screen mode is turned on and off, as well as when
errors occur during the process of changing between full-screen and windowed modes. event handlers for these events are available on the document and element interfaces. note: these event handler properties are not available as html content attributes. in other words, you cannot specify event handlers for fullscreenchange and fullscreen
error in the html content. they must be added by javascript code.
...the html content. they must be added by javascript code. event handlers on documents document.onfullscreenchange an event handler for the fullscreenchange event that's sent to a document when that document is placed into full-screen mode, or when that document exits full-screen mode. this handler is called only when the entire document is presented in full-screen mode. document.onfullscreen
error an event handler for the fullscreen
error event that gets sent to a document when an
error occurs while trying to enable or disable full-screen mode for the entire document. event handlers on elements element.onfullscreenchange an event handler which is called when the fullscreenchange event is sent to the element, indicating that the element has been placed into, or removed from, full-scre...
... obsolete properties document.fullscreen a boolean value which is true if the document has an element currently being displayed in full-screen mode; otherwise, this returns false. ...
...And 3 more matches
IDBObjectStore.createIndex() - Web APIs
ult 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 domexception of one of the following types: exception description constraint
error occurs if an index with the same name already exists in the database. index names are case-sensitive. invalidaccess
error occurs if the provided key path is a sequence, and multientry is set to true in the objectparameters object. invalidstate
error occurs if either: the method was not called from a versionchange transaction mode callback, i.e. from inside...
... invalidaccess
error occurs if the provided key path is a sequence, and multientry is set to true in the objectparameters object. invalidstate
error occurs if either: the method was not called from a versionchange transaction mode callback, i.e. from inside a idbopendbrequest.onupgradeneeded handler. the object store has been deleted. syntax
error occurs if the provided keypath is not a valid key path. transactioninactive
error occurs if the transaction this idbobjectstore belongs to is not active (e.g. ...
... mode callback, i.e. from inside a idbopendbrequest.onupgradeneeded handler. the object store has been deleted. syntax
error occurs if the provided keypath is not a valid key path. transactioninactive
error occurs if the transaction this idbobjectstore belongs to is not active (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstate
error was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. createindex() is used to create new indexes on the object store. for a full working example, see our to-...
...And 3 more matches
Request.cache - Web APIs
esponse; but update if it's too old. // abortcontroller and signal to allow better memory cleaning. ...
...ould be a function that takes a path and a // reference to the controller since it would need to change the value let controller = new abortcontroller(); fetch("some.json", {cache: "only-if-cached", mode: "same-origin", signal: controller.signal}) .catch(e => e instanceof type
error && e.message === "failed to fetch" ? ({status: 504}) : // workaround for chrome; which simply fails with a type
error promise.reject(e)) .then(res => { if (res.status === 504) { controller.abort() controller = new abortcontroller(); return fetch("some.json", {cache: "force-cache", mode: "same-origin", signal: controller.signal}) } const date = res.headers.get("date"), dt = date ? new date(date).gettime() : 0 if (dt < (date.now() - 86400000)) { // if older than 24 hou...
... living standard initial definition ...
...And 3 more matches
Using writable streams - Web APIs
nderlying sink (specified in the chunk parameter). close(controller) — a method that is called if the app signals that it has finished writing chunks to the stream. it should do whatever is necessary to finalize writes to the underlying sink, and release access to it. abort(reason) — a method that will be called if the app signals that it wishes to abruptly close the stream and put it in an
errored state. the constructor call in our example looks like this: const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(...
...this is called when each chunk is actually written (see the next section). the close() method is called automatically when writing has finished — it prints the entire decoded result to the ui in one string. the abort() method si...
..., queuingstrategy); the write() method contains a promise including code that decodes each written chunk into a format that can be written to the ui. this is called when each chunk is actually written (see the next section). the close() method is called automatically when writing has finished — it prints the entire decoded result to the ui in one string. the abort() method simply prints an
error to the console if the stream is aborted. writing to actually write content to the stream we call the sendmessage() function, passing it a message to be written and the stream to write to: sendmessage("hello, world.", writablestream); the sendmessage() definition looks like so: function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const d...
...And 3 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
ernion which will be used to represent the rotation to apply to the reference space for the object in the frame being rendered. radians_per_degreee is the value to multiply an angle in degrees by to convert the angle into radians. the last four variables declared are storage for references to the <div> elements into which we'll output the matrices when we want to show them to the user. ...
...present the rotation to apply to the reference space for the object in the frame being rendered. radians_per_degreee is the value to multiply an angle in degrees by to convert the angle into radians. the last four variables declared are storage for references to the <div> elements into which we'll output the matrices when we want to show them to the user. ...
...ed. radians_per_degreee is the value to multiply an angle in degrees by to convert the angle into radians. the last four variables declared are storage for references to the <div> elements into which we'll output the matrices when we want to show them to the user. logging
errors a function called loggl
error() is implemented to provide an easily customized way to output logging information for
errors that occur while executing webgl functions. function loggl
error(where) { let err = gl.get
error(); if (err) { console.
error(`webgl
error returned by ${where}: ${err}`); } } this takes as its only input a string, where, which is used to indicate what part of the program generated the
error, since similar
errors can have in multiple situations. the vertex and fragment shaders the ver...
...And 3 more matches
async function - JavaScript
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 the await expression. use of async / await enables the use of ordinary try / catch blocks around asynchronous code. the await keyword is only valid inside async functions. if you use it outside of an async function's body, you will get a syntax
error. the purpose of async/await is to simplify the syntax necessary to consume promise-based apis. the behavior of async/await is similar to combining generators and promises. async functions always return a promise. if the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. for example, the following: async function foo() { return 1 } ...
...n foo() { const result1 = await new promise((resolve) => settimeout(() => resolve('1'))) const result2 = await new promise((resolve) => settimeout(() => resolve('2'))) } foo() note how the promise chain is not built-up in one go. instead, the promise chain is constructed in stages as control is successively yielded from and returned to the async function. as a result, we must be mindful of
error handling behavior when dealing with concurrent asynchronous operations. for example, in the following code an unhandled promise rejection
error will be thrown, even if a .catch handler has been configured further along the promise chain. this is because p2 will not be "wired into" the promise chain until control returns from p1. async function foo() { const p1 = new promise((resolve) => sett...
...t be "wired into" the promise chain until control returns from p1. async function foo() { const p1 = new promise((resolve) => settimeout(() => resolve('1'), 1000)) const p2 = new promise((_,reject) => settimeout(() => reject('2'), 500)) const results = [await p1, await p2] // do not do this! use promise.all or promise.allsettled instead. } foo().catch(() => {}) // attempt to swallow all
errors... examples async functions and execution order function resolveafter2seconds() { console.log("starting slow promise") return new promise(resolve => { settimeout(function() { resolve("slow") console.log("slow promise is done") }, 2000) }) } function resolveafter1second() { console.log("starting fast promise") return new promise(resolve => { settimeout(funct...
...And 3 more matches
/loader - Archive of obsolete content
t of common globals that will be shared across modules. this can be done using the optional globals option. for example, the sdk uses this feature to provide a global console object: let { loader } = require('toolkit/loader'); let loader = loader({ globals: { console: { log: dump.bind(dump, 'log: '), info: dump.bind(dump, 'info: '), warn: dump.bind(dump, 'warn: '),
error: dump.bind(dump, '
error: ') } } }); be careful not to misuse this feature! in general it is not recommended to provide features via globals, it's almost always better to use pseudo-modules or, even better, modules. resolve the optional resolve option enables you to completely customize module resolution logic. resolve is assigned a function that takes: the id of the module passed int...
...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 bel...
...// please note: both `globals` and `modules` are just for illustration // purposes we don't suggest populating them with these values. globals: { // provide developers with well known `console` object, hopefully // with a more advanced implementation. ...
...And 2 more matches
Finding window handles - Archive of obsolete content
stems: windows - hwnd mac os x - nswindow* linux - gdkwindow* (it will be gdkwindow* no matter what desktop/window manager) is in use, for explanation why see the article: standard os libraries - unix section) windows components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new
error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.n...
...pes.uint64(hwndstring)); var rez_setforegroundwindow = setforegroundwindow(hwnd); console.log('rez_setforegroundwindow:', rez_setforegroundwindow, rez_setforegroundwindow.tostring()); user32.close(); mac os x objective-c components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new
error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.n...
...ast(gtkwinptr, gtkwidget.ptr); var backto_gdkwinptr = gtk_widget_get_window(gtkwidgetptr); working with xid xid to gdkwindow* // soon to come xid to gtkwindow* // soon to come now onto the examples! ...
...And 2 more matches
Local Storage - Archive of obsolete content
we'll discuss logging in this section, but first let's look at the right (or at least, common and scalable) way of managing local files. ...
...we'll discuss logging in this section, but first let's look at the right (or at least, common and scalable) way of managing local files. ...
...rned about privacy and storing private information locally without deleting it. a good argument can be done for both, so it is up to you to choose what to do in this case. the fuel library has an uninstall event you can use to perform these operations. logging good logging is essential in all kinds of software projects. any extension that is more complex than a hello world needs some way to log
errors and trace execution without having to fire up a debugger. it used to be the case that custom logging solutions were necessary, but mozilla labs have come up with a javascript implementation of a logger similar to the log4j logger used in java projects. the logger is called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above. to use this logger, yo...
...And 2 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> ... <script> document.write("<script type='text\/javascript'>alert('hello');</" + "script>") </script> debug javascript mozilla provides several ways to debug javascript-related issues found in applications created for internet explorer. ...
...clicking on the link will open mozilla's internal view source window with the offending line highlighted. the console also allows you to evaluate javascript. ...
...clicking on the link will open mozilla's internal view source window with the offending line highlighted. the console also allows you to evaluate javascript. ...
...And 2 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
using xpinstall to run an exe (native code) installer if you wish to run a native installer (exe) to install plugin software, but wish to make the delivery of this native installer streamlined and within the browser's process, then you ought to consider wrapping it in an xpi package. from javascript, you can call xpinstall's execute method of the install object to...
... prompt runs the setup executable, and that "-s" is some // invocation parameter defined by the setup.exe file, perhaps to force // the installer to run silently. we are passing "-s" to the setup file. // by passing 'true' we are telling the install script to block // on the execution of the installable, and do it synchronously // must call performinstall to make it all happen... err = getlast
error(); if (!err) performinstall(); else cancelinstall(err); installing plugin files to the current browser installing to the current browser is the task that is the most important for the xpi package to succeed in. here is a code snippet that accomplishes this: // name of the files to be installed var plugin_file = "npmyplugin.dll"; var component_file = "npmypluginscriptablepeer.xpt"; //...
...n.dll"; var component_file = "npmypluginscriptablepeer.xpt"; // invoke initinstall to start the installation .... var pluginfolder = getfolder("plugins"); // verify disk space is appropriate .... err = addfile("@myplugin.com/myplugin,version=2.5.0.0", "2.5.0.0", plugin_file, pluginsfolder, null); if (err != 0) { //alert("installation of myplugin plug-in failed. ...
...And 2 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
allation all installations must begin with initinstall(). the initinstall() method on the install object creates a new installation for the specified software and version. in the browser.xpi installation, this function appears at line 20: var err = initinstall("netscape seamonkey", "browser", "6.0.0.2000110807"); if you call a method on the install object before initinstall(), you will get an
error. the initinstall method takes the following parameters: the display name of the package, the name of the package as it appears in the client registry, and the version, which can be expressed as a number or as an installversion object. in the example above, "netscape seamonkey" is the display name, "browser" is the registry name, and the version is "6.0.0.2000110807." see initinstall in the xpins...
...nt, the install calls you have been making on the install object are preliminary only. recall that an install process takes the following general form: initinstall(); if (verify_space()) { err = add_dirs_and_files; register_files; if (err==success) { performinstall() }; else { cancelinstall() }; } in this arrangement, the actual execution of the installation is checked against the
errors returned from the addition of files to the installation, which may itself have been conditioned on some verification of version and necessary disk space. the actual install code used to execute the installation appears in theinstall.js file as follows: if (err==success) { err = performinstall(); logcomment("performinstall() returned: " + err); } else { cancelinstall(...
...e installation, which may itself have been conditioned on some verification of version and necessary disk space. ...
...And 2 more matches
window - Archive of obsolete content
related elements prefwindow, dialog, dialogheader related topics user notes ...
... related elements prefwindow, dialog, dialogheader related topics user notes to change the icon to a win...
... related elements prefwindow, dialog, dialogheader related topics user notes to change the icon to a window's title bar check this page on window icons. ...
...And 2 more matches
Mozilla release FAQ - Archive of obsolete content
to start understanding the issues with this example, you should dig up the rfcs for the relevant protocols, any documents written on the subject, etc. for this particular example, you would want to go look at relevant topics stuart cheshire's discussion on latency versus bandwidth internet -- under the covers (by me) the rfc for http the w3's html 4.0 definition building mozilla i get x
error when trying to build mozilla - what's wrong? first, make sure that you have the latest release of the mozilla source. secondly, ensure that you have fully read the build instructions for your platform. these instructions are included in the source tree, and are also available on the mozilla website: detailed build instructions: unix/x win32 mac if your version of make chokes on the makefi...
...te: detailed build instructions: unix/x win32 mac if your version of make chokes on the makefiles (on unix), you might not be using gnu make. grab the latest version of gnu make from the gnu ftp site. regarding shells, i would like to recommend the following: if you are using unix, use bash-family shells for the build because of the better control over redirection (in case you want to log
errors and messages) if you are using win32, using the default shell cmd.exe (as opposed to 4dos or 4nt) will probably yield better results. regarding compilation options, it would be good not to compile with optimization, because it's much slower to build, and on windows platforms, there's a bug in some versions of vc++ that makes mozilla crash in many common circumstances if compiled with optimizatio...
... post to netscape.public.mozilla.builds or try to fix it yourself. patches are appreciated. in what directory should i be in order to get a cvs update of the source? you should be at the top of the source (the directory with the top-level makefile). if you wish only to refresh a certain area of the tree, you can go to that area and do a cvs update there. ...
...And 2 more matches
NP_Initialize - Archive of obsolete content
description the browser calls this function only once: when a plug-in is loaded, before the first instance is created. ...
... description the browser calls this function only once: when a plug-in is loaded, before the first instance is created. ...
... description the browser calls this function only once: when a plug-in is loaded, before the first instance is created. ...
...And 2 more matches
Using IO Timeout And Interrupt On NT - Archive of obsolete content
this technical memo is a cautionary note on using netscape portable runtime's (nspr) io timeout and interrupt on windows nt 3.51 and 4.0. due to a limitation of the present implementation of nspr io on nt, programs must follow the following guideline: if a thread calls an nspr io function on a file descriptor and the io function fails with <tt>pr_io_timeout_
error</tt> or <tt>pr_pending_interrupt_
error</tt>, the file descriptor must be closed before the thread exits. in this memo we explain the problem this guideline is trying to work around and discuss its limitations. nspr io on nt the io model of nspr 2.0 is synchronous and blocking. a thread calling an io function is blocked until the io operation finishes, either due to a successful io completion or an
error. if the io operation ...
...lain the problem this guideline is trying to work around and discuss its limitations. nspr io on nt the io model of nspr 2.0 is synchronous and blocking. a thread calling an io function is blocked until the io operation finishes, either due to a successful io completion or an
error. if the io operation cannot complete before the specified timeout, the io function returns with <tt>pr_io_timeout_
error</tt>. if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt> call, the io function returns with <tt>pr_pending_interrupt_
error</tt>. on windows nt, nspr io is implemented using nt's overlapped (also called asynchronous) io. when a thread calls an io function, the thread issues an overlapped io request using the overlapped buffer in its <tt>prthread</tt> structure. then the thr...
...s up the thread that issued the io request earlier. this is the normal way the thread is awakened. io timeout and interrupt however, nspr may wake up the thread in two other situations: if the overlapped io request is not completed before the specified timeout. (note that we can't specify timeout on overlapped io requests, so the timeouts are all handled at the nspr level.) in this case, the
error is <tt>pr_io_timeout_
error</tt>. if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt> call. in this case, the
error is <tt>pr_pending_interrupt_
error</tt>. these two
errors are generated by the nspr layer, so the os is oblivious of what is going on and the overlapped io request is still in progress. the os still has a pointer to the overlapped buffer in the thread's <tt>pr...
...And 2 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
g approach - do not use! if (document.all) { // internet explorer 4+ elm = document.all['menu']; } else { // assume navigator 4 elm = document.layers['menu']; } note how the above example assumed that any browser that was not internet explorer was navigator 4 and attempted to use layers. this is a common source of problems when using browsers based upon gecko as well as opera. a similar
error can be seen in the following example: // wrong approach - do not use! if (document.layers) { // navigator 4 elm = document.layers['menu']; } else { // assume internet explorer 4+ elm = document.all['menu']; } netscape 6 was the first commercial browser released based upon gecko. due to a lack of communication and understanding, many sites have created inappropriate detection strategies...
... of the string netscape6 in the user agent and used tests similar to: if (navigator.useragent.indexof('netscape6') != -1) { // netscape 6 code } note how this type of detection misses any other gecko based browser. unfortunately, the netscape 6 user agent string was not sufficiently generalizable due to it's use of the string netscape6 as a description of the vendor. netscape 7 corrects this
error and introduces another chance for user agent string based detection to fail. mozilla/5.0 (...) gecko/200207xx netscape/7.0 note how netscape 7 no longer uses the string netscape6 as the vendor. any user agent string detection strategy for gecko based upon the existence of the string netscape6 will fail to detect netscape 7. using javascript objects to determine vendor/version as we already d...
...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. ...
...And 2 more matches
Old Proxy API - Archive of obsolete content
d, performing new proxy(...args) calls the proxy’s calltrap with this bound to a new object delegating to the proxy's prototype. handler is an object that implements the handler api. handler api there are two kinds of traps: fundamental and derived traps. if one of the fundamental traps isn't implemented and the proxy is used in a way that expects the fundamental trap to be defined, then an
error is thrown. if a derived trap is implemented, then that trap's code is called whenever the corresponding behavior happens on the proxy. if the derived trap is undefined, a default implementation using the fundamental traps is used. in other words: fundamental traps are required, derived traps are optional. fundamental traps emulated javascript code handler method description ...
...tors. 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 type
error 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.get...
... common mistakes and misunderstanding when starting using proxies, there are often a few beginners' mistakes and misunderstandings: not implementing all traps. proxies are, by default, "semanticless" objects. if a trap isn't implemented, then if it's a derived trap, the default implementation is used. however, if a fundamental trap is unimplemented, then a call to this trap will throw a type
error. to make sure no
error is thrown when your object is used, you have to implement at least all fundamental traps. unwanted recursion. be careful of how you use the receiver argument in 'get' and 'set' traps. var p = proxy.create({get: function(receiver, name) { print(receiver); // looks for receiver's tostring method. receiver turns out to be the proxy, so calling print results in calling the...
...And 2 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
d() { return "exposed to the browser"; } function notexposed() { return "can't see me!"; } </script> <script runat="client"> alert( exposed() ); alert( notexposed() ); </script> there are two blocks of scripts defined, one with runat set to server and the other set to client. this creates a strict separation of the two environments. as it stands, the code in the client block would throw an
error since the server-side javascript is not within scope. if you intend to allow the execution of server-side javascript from the client-side, you can correct the code in listing 1 by doing one of three things. change the runat attribute value of server to server-proxy. add a statement inside the server-side script block to expose a particular server-side function to the browser. this sta...
... jaxer – example application the example application consists of a simple form used to accept comments from public users and was built to cover some of the most us...
... runat attribute set to both. the function defined within this file checks the form to make sure it is complete, returning a boolean. the both context it operates within is a very powerful concept as we are able to use this code to check values entered in the form on both the client and server side. no custom validation libraries for each environment makes for rapid development with less risk for
error. towards the bottom of the code are two div tags with ids form-comments and out-logger. the form-comments div is used to render the form and the out-logger will be used as a log display as each comment is added. the completed user interface is shown in figure 1. figure 1 – the user interface server-side dom processing another powerful...
...And 2 more matches
WAI-ARIA basics - Learn web development
ested <div>s along with css/javascript is used to create a complex ui-feature, or a native control is greatly enhanced/changed via javascript, not only can keyboard accessibility suffer, but screenreader users will find it difficult to work out what the feature does if there are no semantics or other clues. in such situations, aria can help to provide those missing semantics. ...
... does if there are no semantics or other clues. in such situations, aria can help to provide those missing semantics. form validation and
error alerts first of all, let's revisit the form example we first looked at in our css and javascript accessibility article (read keeping it unobtrusive for a full recap). ...
... in such situations, aria can help to provide those missing semantics. form validation and
error alerts first of all, let's revisit the form example we first looked at in our css and javascript accessibility article (read keeping it unobtrusive for a full recap). ...
...And 2 more matches
Sending forms through JavaScript - Learn web development
gle string and replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions. urlencodeddata = urlencodeddatapairs.join( '&' ).replace( /%20/g, '+' ); // define what happens on successful data submission xhr.addeventlistener( 'load', function(event) { alert( 'yeah! data sent and response loaded.' ); } ); // define what happens in case of
error xhr.addeventlistener( '
error', function(event) { alert( 'oops! something went wrong.' ); } ); // set up our request xhr.open( 'post', 'https://example.com/cors.php' ); // add the required http header for form data post requests xhr.setrequestheader( 'content-type', 'application/x-www-form-urlencoded' ); // finally, send our data. xhr.send( urlencodeddata ); } btn.addeventl...
...senddata( data ) { const xhr = new xmlhttprequest(), fd = new formdata(); // push our data into our formdata object for( name in data ) { fd.append( name, data[ name ] ); } // define what happens on successful data submission xhr.addeventlistener( 'load', function( event ) { alert( 'yeah! data sent and response loaded.' ); } ); // define what happens in case of
error xhr.addeventlistener('
error', function( event ) { alert( 'oops! something went wrong.' ); } ); // set up our request xhr.open( 'post', 'https://example.com/cors.php' ); // send our formdata object; http headers are set automatically xhr.send( fd ); } btn.addeventlistener( 'click', function() { senddata( {test:'ok'} ); } ) here's the live result: using formdata bound to a...
... const form = document.getelementbyid( "myform" ); // ...and take over its submit eve...
...And 2 more matches
Introducing asynchronous JavaScript - Learn web development
at a quick example. when you fetch an image from a server, you can't return the result immediately. that means that the following (pseudocode) wouldn't work: let response = fetch('myimage.png'); let blob = response.blob(); // display your image blob in the ui somehow that's because you don't know how long the image will take to download, so when you come to run the second line it will throw an
error (possibly intermittently, possibly every time) because the response is not yet available. instead, you need your code to wait until the response is returned before it tries to do anything else to it. there are two main types of asynchronous code style you'll come across in javascript code, old-style callbacks and newer promise-style code. in the below sections we'll review each of these in turn.
...us successful operation, so you can go forward and do something else to it. each .then() block returns another promise, meaning that you can chain multiple .then() blocks onto each other, so multiple asynchronous operations can be made to run in order, one after another. the catch() block at the end runs if any of the .then() blocks fail — in a similar way to synchronous try...catch blocks, an
error object is made available inside the catch(), which can be used to report the kind of
error that has occurred. note however that synchronous try...catch won't work with promises, although it will work with async/await, as you'll learn later on. note: you'll learn a lot more about promises later on in the module, so don't worry if you don't understand them fully yet. the event queue async ope...
... advantages over old-style callbacks: you can chain multiple async operations together using multiple .then() operations, passing the result of one into the next one as an input. this is much harder to do with callbacks, which often ends up with a messy "pyramid of doom" (also known as callback hell). promise callbacks are always called in the strict order they are placed in the event queue.
error handling is much better — all
errors are handled by a single .catch() block at the end of the block, rather than being individually handled in each level of the "pyramid". promises avoid inversion of control, unlike old-style callbacks, which lose full control of how the function will be executed when passing a callback to a third-party library. the nature of asynchronous code let's explore...
...And 2 more matches
Functions — reusable blocks of code - Learn web development
company.'); } // second.js let name = 'zaptec'; function greeting() { alert('our company is called ' + name + '.'); } both functions you want to call are called greeting(), but you can only ever access the first.js file's greeting() function (the second one is ignored). in addition, attempting to declare the name variable a second time with the let keyword in the second.js file results in an
error. note: you can see this example running live on github (see also the source code). keeping parts of your code locked away in functions avoids such problems, and is considered the best practice. it is a bit like a zoo. the lions, zebras, tigers, and penguins are kept in their own enclosures, and only have access to the things inside their enclosures — in the same manner as the function sco...
...nd outputs it in a paragraph on the page. open the example up in a browser and in your text editor. open the javascript console in your browser developer tools. in the javascript console, enter the following command: output(x); you should see the value of variable x output to the screen. now try entering the following in your console output(y); output(z); both of these should return an
error along the lines of "reference
error: y is not defined". why is that? because of function scope — y and z are locked inside the a() and b() functions, so output() can't access them when called from the global scope. however, what about when it's called from inside another function? try editing a() and b() so they look like this: function a() { let y = 2; output(y); } function b() { let ...
...ot in the same scope as x is defined in, x is a global variable so is available inside all code, everywhere. finally, try updating your code like this: function a() { let y = 2; output(z); } function b() { let z = 3; output(y); } save and reload again, and try this again in your javascript console: a(); b(); this time the a() and b() calls will both return an annoying reference
error: variable name is not defined
error — this is because the output() calls and the variables they are trying to print are not in the same function scopes — the variables are effectively invisible to those function calls. note: the same scoping rules do not apply to loop (e.g. for() { ... }) and conditional blocks (e.g. if() { ... }) — they look very similar, but they are not the same thing...
...And 2 more matches
Handling text — strings in JavaScript - Learn web development
to start with, enter the following lines: let string = 'the revolution will not be televised.'; string; just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. the only difference here is that when writing a string, you need to surround the value with quotes. if you don't do this, or miss one of the quotes, you'll get an
error. try entering the following lines: let badstring = this is a test; let badstring = 'this is a test; let badstring = this is a test'; these lines don't work because any text without quotes around it is assumed to be a variable name, property name, a reserved word, or similar. if the browser can't find it, then an
error is raised (e.g. "missing; before statement"). if the browser can see where ...
...badstring = this is a test'; these lines don't work because any text without quotes around it is assumed to be a variable name, property name, a reserved word, or similar. if the browser can't find it, then an
error is raised (e.g. "missing; before statement"). if the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an
error (with "unterminated string literal"). if your program is raising such
errors, then go back and check all your strings to make sure you have no missing quote marks. the following will work if you previously defined the variable string — try it now: let badstring = string; badstring; badstring is now set to have the same value as string. single quotes vs. double quotes in javascript, yo...
...trings in. both of the following will work okay: let sgl = 'single quotes.'; let dbl = "double quotes"; sgl; dbl; there is very little difference between the two, and which you use is down to personal preference. you should choose one and stick to it, however; differently quoted code can be confusing, especially if you use two different quotes on the same string! the following will return an
error: let badquotes = 'what on earth?"; the browser will think the string has not been closed because the other type of quote you are not using to contain your strings can appear in the string. for example, both of these are okay: let sgldbl = 'would you eat a "fish supper"?'; let dblsgl = "i'm feeling blue."; sgldbl; dblsgl; however, you can't include the same quote mark inside the string i...
...And 2 more matches
What is JavaScript? - Learn web development
outputs a product (the web page). a very common use of javascript is to dynamically modify html and css to update a user interface, via the document object model api (as mentioned above). note that the code in your web documents is generally loaded and executed in the order it appears on the page. if the javascript loads and tries to run before the html and css it is affecting has been loaded,
errors can occur. you will learn ways around this later in the article, in the script loading strategies section. browser security each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the ...
...to it (line 3) so that when the paragraph is clicked, the updatename() code block (lines 5–8) is run. the updatename() code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display. if you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an
error returned in the browser developer console — type
error: para is undefined. this means that the para object does not exist yet, so we can't add an event listener to it. note: this is a very common
error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them. interpreted versus compiled code you might hear the terms interpreted and compile...
...ou are using javascript to manipulate elements on the page (or more accurately, the document object model), your code won't work if the javascript is loaded and parsed before the html you are trying to do something to. in the above code examples, in the internal and external examples the javascript is loaded and run in the head of the document, before the html body is parsed. this could cause an
error, so we've used some constructs to get around it. in the internal example, you can see this structure around the code: document.addeventlistener("domcontentloaded", function() { ... }); this is an event listener, which listens for the browser's "domcontentloaded" event, which signifies that the html body is completely loaded and parsed. the javascript inside this block will not run until afte...
...And 2 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
to understand what's happening here, let's talk some more about that component lifecycle we mentioned earlier. component lifecycle, and the onmount() function when a component is instantiated, svelte runs the initialization code (that is, the <script> section of the component). but at that moment, all the nodes that comprise the component ...
...he name input dom node if (autofocus) nameel.focus() now go back to the todos component, and pass the autofocus prop into the <newtodo> component call, like so: <!-- newtodo --> <newtodo autofocus on:addtodo={e => addtodo(e.detail)} /> if you try your app out now, you'll see that the page is now blank, and in your devtools web console you'll see an
error along the lines of: type
error: nameel is undefined. to understand what's happening here, let's talk some more about that component lifecycle we mentioned earlier. component lifecycle, and the onmount() function when a component is instantiated, svelte runs the initialization code (that is, the <script> section of the component). but at that moment, all the nodes that comprise the component are not attached to the dom, i...
... try and see what happens to the nameel variable. to start with, add the following line at the beginning of the newtodo.svelte <script> section: import { onmount } from 'svelte' and these lines at the end of it: console.log('initializing:', nameel) onmount( () => { console.log('mounted:', nameel) }) now remove the if (autofocus) nameel.focus() line to avoid throwing the
error we were seeing before. the app will now work again, and you'll see the following in your console: initializing: undefined mounted: <input id="todo-0" class="input input__lg" type="text" autocomplete="off"> as you can see, while the component is initializing nameel is undefined, which makes sense because the node input doesn't even exist yet. after the component has been mounted, svelt...
...And 2 more matches
Links and Resources
klist - guidelines to making java accessibility. accessibility information resource center for developers at adobe - flash mx accessibility, pdf document accessibility and actionscript accessibility. ...
...w available and excellent online accessibility validators which check single webpages according to checkpoints of wcag guidelines and then reports
errors or warnings. webxact™ from watchfire® corporation webxact™ is a free and complete online accessibility validation service that can test single pages for quality, accessibility and privacy issues. the accessibility report will contain
errors and warnings for "automatic checkpoints" and "manual checkpoints"; detailed and useful information (line numbers, instances/occurences, textual references to guidelines) will be included for web authors. ...
...just like webxact, it can also perform a "complete webpage quality check" for accessibility, privacy, searchability, metadata and even alt text attribute quality. accessibility valet from webthing description and summary to be written. ...
...And 2 more matches
Application cache implementation overview
es from. after these steps the update is in initialized state waiting to be scheduled. when the update is about to actually start, the scheduling service calls nsofflinecacheupdate::begin() method, that switches the update to checking state (+invokes onchecking event) and starts fetch of the manifest file. note: whenever a load of an items (including the manifest) fails due to a network or server
error or leads to a redirect, the update fails and completely rollbacks any changes made (i.e. all files downloaded are deleted and the new cache version is discarded.) an md5 hash is then calculated from the manifest content we download from the server to be compared to existing md5 (in case of an “update”). during the load, manifest is parsed according the “parsing the cache manifest” html5 s...
... download”. if so, the update switches to downloading state and fetches in parallel items listed in the manifest by call to nsofflinecacheupdate::processnexturi(). if the new hash is identical, update invokes onnoupdate event and is 'finished'. then it associates any documents waiting for this update to finish with the current existing nsiapplicationcache. if the manifest load failed, on
error event is invoked and the update 'finishes'. the parallel load is implemented by asynchronous recursive calls to processnexturi(), a method searching always a single entry that is scheduled to load. when found, channel is open for it (+onprogress event is invoked). processnexturi then invokes it self asynchronously via dispatch to a main thread when not already on the concurrency limit of 15 l...
...cle is stopped. from now on processnexturi can only be called from loadcompleted() again. note: the processnexturi method early returns when state of the update is different then downloading. on downloading state loadcompleted checks whether load of the item succeeded. if so, its marked as valid in the new cache version and processnexturi() is called. otherwise, the update invokes on
error and 'finishes'. when processnexturi discovers there are no more items to download it starts a “manifest check” implemented by nsmanifestcheck. nsmanifestcheck downloads the manifest from the server one more time and checks its content has not changed again. the results is passed to the original update via manifestcheckcompleted method. when the manifest is ...
...And 2 more matches
Chrome registration
t manifest is used: this manifest is "chrome.manifest" in the root of an extension, or theme, or xulrunner application. the plaintext chrome manifests are in a simple line-based format. ...
...firefox 3, thunderbird 3, and seamonkey 2 support mixed case. bug resolved in mozilla 1.9; see bug 132183. manifest instructions comments # this line is a comment - you can put here whatever you want a line is a comment if it begins with the character '#'. ...
...iple appversion flags may be included on a single line, in which case the line is applied if any of the flags match. the version string must conform to the toolkit version format. note: versions of gecko before gecko 1.8.0.13 and gecko 1.8.1.5 contained a bug where if you use the comparisons <, > or =, the version string had be two or more characters long. if not, you would get a message in the
error console that the appversion flag was not recognized. see bug 380398. platformversion when supporting more then one application, it is often more convenient for an extension to specify which gecko version it is compatible with. this is particularly true for binary components. if there are chrome registration lines which only apply to a particular gecko version, the flag platformversion=versio...
...And 2 more matches
IPDL Tutorial
rocess ipc plugins content process plugin process each protocol is declared in a separate file. the ipdl compiler generates several c++ headers from each ipdl protocol. this generated code manages the details of the underlying communication layer (sockets and pipes), constructing and sending messages, ensuring that all actors adhere to their specifications, and handling many
error conditions. the following ipdl code defines a very basic interaction of browser and plugin actors: async protocol pplugin { child: async init(nscstring pluginpath); async shutdown(); parent: async ready(); }; this code declares the pplugin protocol. two messages can be sent from the parent to the child, init() and shutdown(). one message can be sent from the child to the parent, ready()...
...meter is, for both resolve and success callbacks, the returns value itself (as a const reference); if the message returns multiple values (e.g. initasync above), the parameter is, for both resolve and success callbacks, a tuple of the return values (e.g. tuple<bool, bool>). on the other hand the reject/failure callbacks take a mozilla::ipc::responserejectreason&& and are called in case of a fatal
error, such as an ipc
error. therefore, besides callback/promise style response handling, these two overloads are functionally equivalent. the generated c++ will result in something containing: class pplugininstanceparent { public: typedef mozpromise<tuple<bool, bool> responserejectreason, true> asyncinitpromise; typedef mozpromise<bool, responserejectreason, true> otherfunctionpromise; void ...
...ee from c++ the ipdl compiler generates methods that allow actors to access their manager (if the actor isn't top-level) and their managees (if any) from c++. ...
...And 2 more matches
Implementing QueryInterface
// ...but that won't matter when someone calls me wrongly in a non-debug build. ...
... // ...but that won't matter when someone calls me wrongly in a non-debug build. ...
... ns_imethodimp nsmyimplementation::queryinterface( refnsiid aiid, void** ainstanceptr ) { ns_assertion(ainstanceptr, "queryinterface requires a non-null destination!"); // it's a logic
error, not a runtime
error, to call me without any place to put my answer! // ...but that won't matter when someone calls me wrongly in a non-debug build. if ( !ainstanceptr ) return ns_
error_null_pointer; nsisupports* foundinterface; if ( aiid.equals(nscomtypeinfo<nsix>::getiid()) ) foundinterface = ns_static_cast(nsix*, this); else if ( aiid.equals(nscomtypeinfo<nsiy>::getiid()) ) foundinterface = ns_static_cast(nsiy*, this); // ...as many cases as needed... else if ( aiid.equals(nscomtypeinfo<nsisupports>::getiid()) ) foundinterface = ns_st...
...And 2 more matches
Bootstrapping a new locale
irefox 3.6 is released from the 1.9.2 branch. from now on may be needs some corrections, (see expected structure below $cd ab-cd/browser/chrome/browser) may be needs $cp -r mozilla-1.9.x/browser/locales/ ab-cd and then $mv ab-cd/en-us ab-cd/browser and the same for the others the commands seems symbolic and not real ... see also structure expected more below. ...
... new working directory so you are in the ~/[your working directory]/[ab-cd]/ path and can start localizing. ...
...rt editing, you will need a text editing application. you can choose to use: notepad++ or notepad2 on windows, vim, gedit or kate on gnu/linux, textwrangler on mac os x. ...
...And 2 more matches
Localizing without a specialized tool
ing for convenience, try saving the output of this command to a text file on your desktop so you can review it as you go. run: $ compare-locales mozilla-1.9.2/browser/locales/l10n.ini l10n-mozilla-1.9.2 x-testing > ~/desktop/x-testing.compare open the x-testing.compare file that is on your desktop. ...
...these two string examples translated, you can now test your work to see immediately where you have translated. refer to the building and testing section of the create a new localization page. going one-by-one with your compare-locales output open for review, we will start with the first file with "// add and localize this file" note. you should see // add and localize this file aboutcert
error.dtd notice from the compare-locales output that this file is located in the directory /browser/chrome/browser. you will want to copy this file from the en-us sources into the proper ab-cd directory. to do this, you first need to create the directory structure and then copy the file into it. type the command pwd again, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-t...
... the en-us sources into the proper ab-cd directory. to do this, you first need to create the directory structure and then copy the file into it. type the command pwd again, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-testing and then type the command mkdir /browser/chrome/browser now, copy the file by typing cp mozilla-1.9.2/browser/locales/chrome/browser/aboutcert
error.dtd l10n-mozilla-1.9.2/x-testing/browser/chrome/browser/aboutcert
error.dtd you should now see the aboutcert
error.dtd file in that newly created directory. your compare locales output follows the exact nested source structure. each time you see a directory or set of sub-directories, you will need to run the mkdir command inside your locale directory and then copy the .dtd or .properties files in...
...And 2 more matches
Mozilla DOM Hacking Guide
e absolutely horrific globalresolve() member function of the nswindowsh helper, as an example of those functions. this is not for the faint of heart, and is not absolutely necessary, so you might want to skip this section if you don't have too much time (and i suppose you don't). user's guide to class info warning: this document has not yet been reviewed by the dom gurus, it might contain some
errors. specifically, due to some changes that happened around, april 2002, some things that were not possible before are now possible. i will try to update this guide as soon as possible. please send any comment to fabian guisset. when should domclassinfo be used to add a new interface to an existing dom object to expose a new dom object to javascript to add a new js external constructor, like ...
..., the second one will map .location to .location.href. as of writing this document, the code in nswindowsh::newresolve() looks like this: (nsdomclassinfo.cpp) if (flags & jsresolve_assigning) { // only define the property if we are setting it. if (str == slocation_id) { // setting the location property. nscomptr<nsidomwindow> window(do_queryinterface(native)); ns_ensure_true(window, ns_
error_unexpected); nscomptr<nsidomlocation> location; rv = window->getlocation(getter_addrefs(location)); ns_ensure_success(rv, rv); // use the dom to get the location object of the window object. jsval v; rv = wrapnative(cx, obj, location, ns_get_iid(nsidomlocation), &v); // this xpconnect method creates a wrapper for the location object on the // window object. ns_ensure_su...
...val v; rv = wrapnative(cx, obj, location, ns_get_iid(nsidomlocation), &v); // this xpconnect method creates a wrapper for the location object on the // window object. ns_ensure_success(rv, rv); if (!::js_defineucproperty(cx, obj, ::js_getstringchars(str), ::js_getstringlength(str), v, nsnull, nsnull, 0)) { return ns_
error_failure; } // this js api call defines the "location" property on the window object, its // value being the xpconnect wrapper for the location object. *objp = obj; return ns_ok; } this is the first step. it is required to have the getter for .location work as well, but that's another story. the second step is to map .location to .location.href in nswindowsh::setproperty() if (s...
...And 2 more matches
NSS_3.12.1_release_notes.html
bug 67890: create self-signed cert with existing key that signed csr bug 129303: nss needs to expose interfaces to deal with multiple token sources of certs. ...
... bug 430916: add sustaining asserts bug 431805: leak in nssarena_destroy() bug 431929: memory leaks o...
... libpkix unconditionally dump socket traffic to stdout bug 430368: vfychain -t option is undocumented bug 430369: vfychain -o succeeds even if -pp is not specified bug 430399: vfychain -pp crashes bug 430405:
error log is not produced by cert_pkixverifycert bug 430743: update ssltap to understand the tls session ticket extension bug 430859: pkix: policy mapping fails verification with
error invalid arguments bug 430875: document the policy for the order of cipher suites in ssl_implementedciphers. ...
...And 2 more matches
NSS_3.12.2_release_notes.html
nss tools and test programs you also need to download the nspr 4.7.1 binary distributions to get the nspr 4.7.1 header files and shared libraries, which nss 3.12.2 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. new in nss 3.12.2 new functions in the nss shared library: sec_pkcs12addcertorchainandkey (see p12.h) new pkcs11
errors (see secerr.h) sec_
error_pkcs11_general_
error sec_
error_pkcs11_function_failed sec_
error_pkcs11_device_
error bugs fixed the following bugs have been fixed in nss 3.12.2. bug 200704: pkcs11: invalid session handle 0 bug 205434: fully implement new libpkix cert verification api from bug 294531 bug 302670: use the installed libz.so where available bug 305693: shlibsign generates pq...
...ed the following bugs have been fixed in nss 3.12.2. ...
... been fixed in nss 3.12.2. bug 200704: pkcs11: invalid session handle 0 bug 205434: fully implement new libpkix cert verification api from bug 294531 bug 302670: use the installed libz.so where available bug 305693: shlibsign generates pqg for every run bug 311483: exposing includecertchain as a parameter to sec_pkcs12addcertandkey bug 390527: get rid of pkix
errormsg variable in pkix_
error bug 391560: libpkix does not consistently return pkix_validatenode tree that truly represent failure reasons bug 408260: certutil usage doesn't give enough information about trust arguments bug 412311: replace pr_interval_no_wait with pr_interval_no_timeout in client initialization calls bug 423839: add multiple pkcs#11 token password command line option to nss tools. bug 432260: [[@ pk...
...And 2 more matches
EncDecMAC using token object - sample 3
status rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { pr_fprintf(pr_stderr, "pk11_findfixedkey failed (err %d)\n", pr_get
error()); pk11_freeslot(slot); return null; } return key; } /* * decrypt and verify mac */ secstatus decryptandverifymac(const char* outfilename, char *encryptedfilename, secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocks...
...; if (rv != secsuccess) { pr_fprintf(pr_stderr, "decrypt failure\n"); goto cleanup; } if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count == filelength) { decbuflen = decbuflen-paddinglength; } /* write the plain text to out file */ temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write
error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac, newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure...
...p; } /* generate a second key to use for macing, also a token object. ...
...And 2 more matches
JS::CompileOptions
ion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. version jsversion javascript version used to compile the script. methods some methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow method chain. methods of js::readonlycompileoptions method description bool muted
errors() const determines if
errors are muted. the web platform allows scripts to be loaded from arbitrary cross-origin sources. this allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax
errors (via a window.on
error handler) for juicy morsels of its contents. to counter thi...
... are muted. the web platform allows scripts to be loaded from arbitrary cross-origin sources. this allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax
errors (via a window.on
error handler) for juicy morsels of its contents. to counter this attack, html5 specifies that script
errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in js
errorreports. const char *filename() const returns filename of the source code. const char *introducerfilename() const returns filen...
... for introducerfilename. returns false if it failed to duplicate. owningcompileoptions &setline(unsigned l) sets each property and returns the instance itself. ...
...And 2 more matches
Animated PNG graphics
t black means red, green, blue and alpha components are all set to zero. for purposes of chunk descriptions, an unsigned int shall be a 32-bit unsigned integer in network byte order limited to the range 0 to (2^32)-1; an unsigned short shall be a 16-bit unsigned integer in network byte order with the range 0 to (2^16)-1; and a byte shall be an 8-bit unsigned integer with the range 0 to (2^8)-1. ...
... a 32-bit unsigned integer in network byte order limited to the range 0 to (2^32)-1; an unsigned short shall be a 16-bit unsigned integer in network byte order with the range 0 to (2^16)-1; and a byte shall be an 8-bit unsigned integer with the range 0 to (2^8)-1.
error handling apng is designed to allow incremental display of frames before the entire image has been read. this implies that some
errors may not be detected until partway through the animation. it is strongly recommended that when any
error is encountered decoders should discard all subsequent frames, stop the animation, and revert to displaying the default image. a decoder which detects an
error before the animation has started should display the default image. an
error message may be displayed to the user if appropriate. struc...
...ld be appropriately padded with fully transparent pixels if extra space will be needed for later frames. each frame is identical for each play, therefore it is safe for applications to cache the frames. chunk sequence numbers the 'fctl' and 'fdat' chunks have a 4 byte sequence number. both chunk types share the sequence. the purpose of this number is to detect (and optionally correct) sequence
errors in an animated png, since the png specification does not impose ordering restrictions on ancillary chunks. the first 'fctl' chunk must contain sequence number 0, and the sequence numbers in the remaining 'fctl' and 'fdat' chunks must be in order, with no gaps or duplicates. the tables below illustrates the use of sequence numbers for images with more than one frame and more than one 'fdat' chu...
...And 2 more matches
Using XPCOM Utilities to Make Things Easier
value. in the coming chapters, you'll see examples that use this version in the weblock component. smart pointers all of the interfaces that you've seen so far are reference counted. leaking a reference by not releasing an object, as the code below demonstrates, can be a major problem. { nsisupports* value = nsnull; object->method(&value); if (!value) return; // ... if (ns_failed(
error)) return; // <------------ leaks |value| //... ns_release(value); // release our reference } a method returns an nsisupports interface pointer that has been reference counted before it is returned (assuming it wasn't nsnull). if you handle an
error condition by returning prematurely, whatever value points at will leak-it will never be deleted. this is a trivial fix in this example, ...
... of scope begs for a tool that can aid the developer. in xpcom, this tool is the nscomptr, orsmart pointer class, which can save you countless hours and simplify your code when you're dealing with interface pointers. using smart pointers, the code above can be simplified to: { nscomptr<nsisupports> value; object->method(getter_addrefs(value)); if (!value) return; // ... if (ns_failed(
error)) return; // ... } the style or syntax may be unfamilar, but smart pointers are worth learning and using because they simplify the task of managing references. nscomptr is a c++ template class that acts almost exactly like raw pointers, that can be compared and tested, and so on. when you pass them to a getter, you must do something special, however: you must wrap the variable with the fu...
...is desirable, since the nscomptr is handling reference counting for you. if for some reason you need to adjust the reference count, you must assign the nscomptr to a new variable and addref that. this is a common pattern when you have a local nscomptr in a function and you must pass back a reference to it, as in the following: someclass::get(nsisupports** aresult) { if (!aresult) return ns_
error_null_pointer; nscomptr<nsisupports> value; object->method(getter_addrefs(value)); *aresult = value.get(); ns_if_addref(*aresult); return ns_ok; } the first thing that this method does is check to see that the caller passed a valid address. if not, it doesn't even try to continue. next, it calls another method on an object that is presumed to exist in this context. you can call a .ge...
...And 2 more matches
mozIStorageService
abackupparentdirectory optional the directory to put the backup into. if this is not specified, the backup is placed in the same directory as the original file. return value an nsifile object representing the newly-created backup file. opendatabase() opens a database connection to the specified file. the specified file is created if it does not already exist. 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). consumers should check mozistorageconnection.connectionready to ensure that they can use the database. if this value is false, it is strongly recommended that the database be backed up with mozistorageco...
...connection to "foo.sqlite" and "foo.sqlite" will corrupt your database. if your database contains virtual tables (for example, for full-text indexes), you must use mozistorageservice.openunshareddatabase() to open it, since those tables are not compatible with a shared cache. if you use this method to open a database containing virtual tables, it will think the database is corrupted and throw ns_
error_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. e...
...onnection 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 the type of storage reque...
...And 2 more matches
nsIAccessibleHyperLink
nce 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 embedded character within the p...
... 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 set on the accessible for this...
...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
nsIControllers
icontroller 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 order, rather than...
... 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, 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. controller the cont...
...And 2 more matches
nsICryptoHash
h("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 aalgorithm the hash...
... 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 aalgorithm the hash algor...
...thstring() 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 buffer adata. except...
...And 2 more matches
nsIDOMGeoGeolocation
ows an exception when importing, try using this: var geolocation = components.classes["@mozilla.org/geolocation;1"] .getservice(components.interfaces.nsisupports); method overview void clearwatch(in unsigned short watchid); void getcurrentposition(in nsidomgeopositioncallback successcallback, [optional] in nsidomgeoposition
errorcallback
errorcallback, [optional] in nsidomgeopositionoptions options); unsigned short watchposition(in nsidomgeopositioncallback successcallback, [optional] in nsidomgeoposition
errorcallback
errorcallback, [optional] in nsidomgeopositionoptions options); attributes attribute ty...
...cently retrieved location as seen by the provider. may be null. read only. methods clearwatch() when the clearwatch() method is called, the watch() process stops calling for new position identifiers and cease invoking callbacks. void clearwatch( in unsigned short watchid ); parameters none. getcurrentposition() acquires the user's current position via a new position object. ...
... may be null. read only. methods clearwatch() when the clearwatch() method is called, the watch() process stops calling for new position identifiers and cease invoking callbacks. void clearwatch( in unsigned short watchid ); parameters none. getcurrentposition() acquires the user's current position via a new position object. if this fails,
errorcallback is invoked with an nsidomgeoposition
error argument. ...
...And 2 more matches
nsILivemarkService
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 ); parameters afeeduri fe...
... 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 ); parameters folder ...
... 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 folderid the id of the...
...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 specificall...
...unless the setfolderreadonly() method has been called to specifically make the folder read-only. it's true for non-folder nodes. if this container is a remote container, this flag may be redefined by the remote container provider. read-only. containeropen boolean set this to true to allow descent into this container. when closed, attempting to call getchild() or access childcount results in an
error. when you're done reading the container's children, set this to false. for host 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...
... 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
nsIPushSubscription
key: string.fromcharcode.apply(null, btoa(subscription.getkey("p256dh"))), secret: string.fromcharcode.apply(null, btoa(subscription.getkey("auth"))), })); } pushservice.subscribe( "ch...
... key: string.fromcharcode.apply(null, btoa(subscription.getkey("p256dh"))), secret: string.fromcharcode.apply(null, btoa(subscription.getkey("auth"))), })); } pushservice.subscribe( "chrome://my-module/push", scr...
... key: string.fromcharcode.apply(null, btoa(subscription.getkey("p256dh"))), secret: string.fromcharcode.apply(null, btoa(subscription.getkey("auth"))), })); } pushservice.subscribe( "chrome://my-module/push", scriptsecu...
...And 2 more matches
nsIURI
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. exceptions thrown ns_
error_failure if host is not applicable to the uri scheme (e.g. about:blank) note: characters are not escaped. ipv6 addresses are not enclosed in square brackets. hostport autf8string the "host:port" part of the uri (or simply the host, if port is -1). exceptions thrown ns_
error_failure if hostport is not applicable to the uri scheme (e.g. abo...
...tf-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 value of -1 corresponds to the...
...rs 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 value of -1 corresponds to the protocol's default port (for example -1 implies port 80 for http uris). exceptions thrown ns_
error_failure if port is not applicable to the uri scheme (e.g. about:blank) prepath autf8string the prepath returns the string before the path (such as "scheme://user:password@host:port"). this is related to the web origin concept of rfc6454. this is useful for authentication, managing sessions, or for checking the origin of an uri to prevent cross-site scri...
...And 2 more matches
XPCOM reference
gfolder interface. there are currently three folder classes - nslocalmailfolder, nsimapmailfolder, and nsnewsfolder. they all inherit from nsmsgdbfolder, which implements a lot of the core functionality. ...
...asses - nslocalmailfolder, nsimapmailfolder, and nsnewsfolder. they all inherit from nsmsgdbfolder, which implements a lot of the core functionality. ...
...nslocalmailfolder, nsimapmailfolder, and nsnewsfolder. they all inherit from nsmsgdbfolder, which implements a lot of the core functionality. ...
...And 2 more matches
Standard OS Libraries
unix unix based operating systems are linux, *bsd, solaris, etc. there is a star/asterik ("*") before "bsd" because this means the bsd family such as freebsd, ...
... unix unix based operating systems are linux, *bsd, solaris, etc. there is a star/asterik ("*") before "bsd" because this means the bsd family such as freebsd, openbsd (who by the way made ssh), ...
...if you would like to do stuff off of the main thread, in chromeworker's, then you should use ...
...And 2 more matches
Working with data
forms of the syntax for creating cdata objects without immediately assigning them a value: var mycdataobj = new type; var mycdataobj = new type(); var mycdataobj = type(); these all do the same thing: they return a new cdata object of the specified type, whose data buffer has been populated entirely with zeroes. note: if type.size is undefined, creating a new object this way will throw a type
error 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 co...
...ized 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 isn't possible, type
error is thrown. the resulting data is then copied into a new cdata object. if the original value is already a cdata object, the original object is simply duplicated directly into the new one. if type is an array type of unspecified length, the following steps are taken: if the value is a size value, a new array of that length is created, with its cells ready to accept values of the same type as th...
...is a utf-16 string, the new cdata object is the result of converting the utf-16 string to utf-8, with a null terminator. if the value is a javascript array object and it has a non-negative length, a new array is created and the contents of the array specified by value are converted to cdata objects and copied into the new array, which is then returned. if none of these conditions are met, a type
error is thrown. if type is ctypes.void_t, a type
error is thrown. example: creating an array let arraytype = ctypes.arraytype(ctypes.int32_t); let myarray = new arraytype(5); at this point, myarray.length is 5; there are 5 entries in the array. myarray.constructor.size is 20; the total size of the array's data buffer is 20 bytes (5 entries, 4 bytes apiece). example: creating an array of strings ...
...And 2 more matches
UInt64
st 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 type
error 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. method overview ...
...); 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. exceptions thrown type
error 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 type
error num is not a 64-bit integer object. l...
... join() 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. ...
...And 2 more matches
Debugger.Environment - Firefox Developer Tools
iates 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 type
error 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...
...or a given environment. this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.) if a debugger.environment instance’s referent is not a debuggee environment, then attempting to access its properties (other than inspectable) or call any its methods throws an instance of
error. debugger.environment instances protect their referents from the garbage collector; as long as the debugger.environment instance is live, the referent remains live. garbage collection has no visible effect on debugger.environment instances. accessor properties of the debugger.environment prototype object a debugger.environment instance inherits the following accessor properties from its protot...
...icating that the environment was introduced by a with statement. parent the environment that encloses this one (the “outer” environment, in ecmascript terminology), or null if this is the outermost environment. object a debugger.object instance referring to the object whose properties this environment reflects. if this is a declarative environment record, this accessor throws a type
error (since declarative environment records have no such object). both "object" and "with" environments have object properties that provide the object whose properties they reflect as variable bindings. callee if this environment represents the variable environment (the top-level environment within the function, which receives var definitions) for a call to a functionf, then this property’s value ...
...And 2 more matches
Document - Web APIs
ocument.onbeforescriptexecute represents the event handling code for the beforescriptexecute event. document.oncopy represents the event handling code for the copy event. document.oncut represents the event handling code for the cut event. document.onfullscreenchange is an eventhandler representing the code to be called when the fullscreenchange event is raised. document.onfullscreen
error is an eventhandler representing the code to be called when the fullscreen
error event is raised. document.onpaste represents the event handling code for the paste event. document.onreadystatechange represents the event handling code for the readystatechange event. document.onselectionchange is an eventhandler representing the code to be called when the selectionchange event is raised. ...
...t event is sent, indicating that a css animation has started playing. globaleventhandlers.onauxclick an eventhandler called when an auxclick event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button). globaleventhandlers.onblur is an eventhandler representing the code to be called when the blur event is raised. globaleventhandlers.on
error is an on
erroreventhandler representing the code to be called when the
error event is raised. globaleventhandlers.onfocus is an eventhandler representing the code to be called when the focus event is raised. globaleventhandlers.oncancel is an eventhandler representing the code to be called when the cancel event is raised. globaleventhandlers.oncanplay is an eventhandler representing the cod...
... is an eventhandler representing the code to be called when the pointerenter event is raised. globaleventhandlers.onpointerleave is an eventhandler representing the code to be called when the pointerleave event is raised. globaleventhandlers.onpointerlockchange is an eventhandler representing the code to be called when the pointerlockchange event is raised. globaleventhandlers.onpointerlock
error is an eventhandler representing the code to be called when the pointerlock
error event is raised. globaleventhandlers.onprogress is an eventhandler representing the code to be called when the progress event is raised. globaleventhandlers.onratechange is an eventhandler representing the code to be called when the ratechange event is raised. globaleventhandlers.onreset is an eventhandler re...
...And 2 more matches
FileSystemEntry.getParent() - Web APIs
the filesystementry interface's method getparent() obtains a filesystemdirectoryentry. syntax filesystementry.getparent(successcallback[,
errorcallback]); parameters successcallback a function which is called when the parent directory entry has been retrieved. the callback receives a single input parameter: a filesystemdirectoryentry object representing the parent directory. the parent of the root directory is considered to be the root directory, itself, so be sure to watch for that.
errorcallback optional an optional callback which is executed if an
error occurs. there's a single parameter: a file
error describing what went wrong. return value undefined.
errors file
error.invalid_state_err the operation failed because the file system's state doesn't permit it. this can happen...
... example this example renames the file specified by the variable fileentry to "newname.html". ...
... occurs. there's a single parameter: a file
error describing what went wrong. return value undefined.
errors file
error.invalid_state_err the operation failed because the file system's state doesn't permit it. this can happen, for example, if the file system's cached state differs from the actual state of the file system. file
error.not_found_err the specified path could not be found. file
error.security_err security restrictions prohibit obtaining the parent directory's information. example this example renames the file specified by the variable fileentry to "newname.html". ...
...And 2 more matches
FileSystemFileEntry.createWriter() - Web APIs
the filesystemfileentry interface's method createwriter() returns a filewriter object which can be used to write data into the file represented by the directory entry. syntax filesystemfileentry.createwriter(successcallback[,
errorcallback]); parameters successcallback a callback function which is called when the filewriter has been created successfully; the filewriter is passed into the callback as the only parameter.
errorcallback optional if provided, this must be a method which is caled when an
error occurs while trying to create the filewriter. this callback receives as input a file
error object describing the
error. return value undefined. example this example establishes a method, writetofileentry(), which outputs a text string to the file corresponding to the passed-in...
...this blob is then output to the filewriter object to be written to the file. this api has no official w3c or whatwg specification. ...
... value undefined. example this example establishes a method, writetofileentry(), which outputs a text string to the file corresponding to the passed-in directory entry. function writetofileentry(entry, text) { entry.createwriter(function(filewriter) { let data = blob([text], { type: "text/plain" }); filewriter.write(data); }, function(file
error) { /* do whatever to handle the
error */ }); } the success callback for the createwriter() call takes the text which was passed in and creates a new blob object of type text/plain that contains the passed text. this blob is then output to the filewriter object to be written to the file. this api has no official w3c or whatwg specification. browser compatibility the compatibility table on this page is generated from structured ...
...And 2 more matches
FileSystemFileEntry - Web APIs
by the file system entry. basic concepts to write content to file, create a filewriter object by calling createwriter(). to read a file, obtain a file object representing its contents by calling file(). example the following code creates an empty file called "log.txt" (if it doesn't exist) and fills it with the text "meow". inside the success callback, event handlers are set up to handle the
error error and writeend events. the text data is written to the file by creating a blob, appending text to it, and passing the blob to filewriter.write(). function oninitfs(fs) { fs.root.getfile('log.txt', {create: true}, function(fileentry) { // create a filewriter object for our filesystemfileentry (log.txt). fileentry.createwriter(function(filewriter) { filewriter.onwriteend = fun...
...ob, appending text to it, and passing the blob to filewriter.write(). function oninitfs(fs) { fs.root.getfile('log.txt', {create: true}, function(fileentry) { // create a filewriter object for our filesystemfileentry (log.txt). ...
...ewriter(function(filewriter) { filewriter.onwriteend = function(e) { console.log('write completed.'); }; filewriter.on
error = function(e) { console.log('write failed: ' + e.tostring()); }; // create a new blob and write it to log.txt. var bb = new blobbuilder(); bb.append('meow'); filewriter.write(bb.getblob('text/plain')); },
errorhandler); },
errorhandler); } window.requestfilesystem(window.temporary, 1024*1024, oninitfs,
errorhandler); specifications specification status comment file and directory entries apithe definition of 'filesystemfileentry' in that specification. draft draft of proposed api browser compatibility the compatibility table on this page is generated from ...
...And 2 more matches
FileHandle API - Web APIs
ration always writes content at the end of the file. truncate : this operation keeps the nth-first bytes of the file and removes the rest. // get a lockedfile object from the handle var myfile = myfilehandle.open('readwrite'); // start a writing operation var writing = myfile.append('some content'); writing.onsuccess = function () { console.log('writing operation successful'); } writing.on
error = function () { console.log('something goes wrong in the writing process: ' + this.
error); } reading it's possible to directly write the content of a lockedfile object without using an intermediate file object and a filereader object. the lockedfile interface provides a readastext method and a readasarraybuffer method. those two methods expect a size to indicate how many bytes must be read ...
...for example, there are many apis that expect blob or file objects such as filereader (which can be easier to use to read the whole file) or xmlhttprequest. it's possible to get a file object representing the current sta...
...ion will start with the byte at index 0 in the file myfile.location = 0; // start a reading operation for the whole file content var reading = myfile.readastext(size); reading.onsuccess = function () { console.log('the content of the file is:'); console.log(this.result); } reading.on
error = function () { console.log('something goes wrong in the reading process: ' + this.
error); } } file snapshot in many cases it can be handy to get a snapshot of the file. for example, there are many apis that expect blob or file objects such as filereader (which can be easier to use to read the whole file) or xmlhttprequest. it's possible to get a file object representing the current state of the file handled by the filehandle object by using the getfile method. such a file obje...
...And 2 more matches
Introduction to the File and Directory Entries API - Web APIs
api. each of the apis adds different functionality. these apis are a giant evolutionary leap for web apps, which can now cache and process large amounts of data. about this document this introduction discusses essential concepts and terminology in the file and directory entries api. it gives you the big picture and orients you to key concepts. it also describes restrictions that raise security
errors if you ignore them. to learn more about terminology used in this api, see the definitions section. for the reference documentation on the file and directory entries api, see the reference landing page and its subpages. the specification is still being defined and is subject to change. overview the file and directory entries api includes both asynchronous and synchronous versions of the inte...
...instead, it is a virtualized file system that looks like a full-fledged file...
...alfilesystemsyncurl(). these synchronous methods are members of the worker's global scope only, not the window object. the synchronous api can be simpler for some tasks. its direct, in-order programming model can make code easier to read. the drawback of synchronous api has to do with its interactions with web workers, which has some limitations. when using the asynchronous api, always use the
error callbacks when using the asynchronous api, always use the
error callbacks. although the
error callbacks for the methods are optional parameters, they are not optional for your sanity. you want to know why your calls failed. at minimum, handle the
errors to provide
error messages, so you'll have an idea of what's going on. the file and directory entries api interacts with other apis the file an...
...And 2 more matches
HTMLObjectElement.setCustomValidity - Web APIs
additionally you must call the reportvalidity method on the same element or nothing will happen. ...
...additionally you must call the reportvalidity method on the same element or nothing will happen. ...
...additionally you must call the reportvalidity method on the same element or nothing will happen. ...
...And 2 more matches
Ajax navigation example - Web APIs
"></script> <link rel="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxrequest = new (function () { function closereq () { oloadingbox.parentnode && document.body.removechild(oloadingbox); bisloading = false; } function abortreq () { if (!bisloading) { return; } oreq.abort(); closereq(); } function ajax
error () { alert("unknown
error."); } function ajaxload () { var vmsg, nstatus = this.status; switch (nstatus) { case 200: vmsg = json.parse(this.responsetext); document.title = opageinfo.title = vmsg.page; document.getelementbyid(stargetid).innerhtml = vmsg.content; if (bupdateurl) { ...
... case 2: // successful 2xx console.log("successful code " + vmsg); break; case 3: // redirection 3xx console.log("redirection code " + vmsg); break; */ case 4: /* client
error 4xx */ alert("client
error #" + vmsg); break; case 5: /* server
error 5xx */ alert("server
error #" + vmsg); break; default: /* unknown status */ ajax
error(); } } ...
...unction filterurl (surl, sviewmode) { return surl.replace(rsearch, "") + ("?" + surl.replace(rhost, "&").replace(rview, sviewmode ? ...
...And 2 more matches
IDBObjectStore.add() - Web APIs
ransaction’s complete event in addition to the idbobjectstore.add request’s success event, because the transaction may still fail after the success event fires. in other words, the success event is only triggered when the transaction has been successfully queued. the add method is an insert only method. if a record already exists in the object store with the key parameter as its key, then an
error constrain
error event is fired on the returned request object. for updating existing records, you should use the idbobjectstore.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 unspecifi...
... 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 domexception of one of the following types: exception description readonly
error the transaction associated with this operation is in read-only mode. transactioninactive
error this idbobjectstore's transaction is inactive. data
error any of the following conditions apply: the object store uses in-line keys or has a key generator, and a key parameter was provided. the object store uses out-of-line keys and has no key generator, and...
...s in-line keys or has a key generator, and a key parameter was provided. the object store uses out-of-line keys and has no key generator, and no key parameter was provided. the object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key. the key parameter was provided but does not contain a valid key. invalidstate
error the idbobjectstore has been deleted or removed. dataclone
error the data being stored could not be cloned by the internal structured cloning algorithm. constraint
error an insert operation failed because the primary key constraint was violated (due to an already existing record with the same primary key value). example in the following code snippet, we open ...
...And 2 more matches
MediaDevices.getDisplayMedia() - Web APIs
ser-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 domexception
error object to the promise's failure handler. possible
errors are: abort
error an
error or failure that doesn't match any of the other exceptions below occurred. invalidstate
error the call to getdisplaymedia() was not made from code running due to a user action, such as an event handler. another potential cause for this event: the document in whose context getdisplaymedia() was called is not full...
...
error an
error or failure that doesn't match any of the other exceptions below occurred. invalidstate
error the call to getdisplaymedia() was not made from code running due to a user action, such as an event handler. another potential cause for this event: the document in whose context getdisplaymedia() was called is not fully active; for example, perhaps it is not the frontmost tab. notallowed
error permission to access a screen area was denied by the user, or the current browsing instance is not permitted access to screen sharing. notfound
error no sources of screen video are available for capture. ...
...er potential cause for this event: the document in whose context getdisplaymedia() was called is not fully active; for example, perhaps it is not the frontmost tab. notallowed
error permission to access a screen area was denied by the user, or the current browsing instance is not permitted access to screen sharing. notfound
error no sources of screen video are available for capture. notreadable
error the user selected a screen, window, tab, or other source of screen data, but a hardware or operating system level
error or lockout occurred, preventing the sharing of the selected source. ...
...And 2 more matches
MediaSource.endOfStream() - Web APIs
the endofstream() method of the mediasource interface signals the end of the stream. syntax mediasource.endofstream(endofstream
error); parameters endofstream
error optional a domstring representing an
error to throw when the end of the stream is reached. the possible values are: network: terminates playback and signals that a network
error has occured. this can be used create a custom
error handler related to media streams. for example, you might have a function that handles media chunk requests, separate from other network requests. ...
...hen the end of the stream is reached. the possible values are: network: terminates playback and signals that a network
error has occured. this can be used create a custom
error handler related to media streams. for example, you might have a function that handles media chunk requests, separate from other network requests. ...
...unk requests, separate from other network requests. when you make an xmlhttprequest call for a media chunk, and onabort or on
error triggers, you might want to call endofstream('network'), display a descriptive message in the ui, and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.) decode: terminates playback and signals that a decoding
error has occured. 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. ...
...And 2 more matches
Navigator.getUserMedia() - Web APIs
user for permission to use up to one video input device (such as a camera or shared screen) and up to one audio input device (such as a microphone) as the source for a mediastream. if permission is granted, a mediastream whose video and/or audio tracks come from those devices is delivered to the specified success callback. if permission is denied, no compatible input devices exist, or any other
error condition occurs, the
error callback is executed with a mediastream
error object describing what went wrong. if the user instead doesn't make a choice at all, neither callback is executed. this is a legacy method. please use the newer navigator.mediadevices.getusermedia() instead. while technically not deprecated, this old callback version is marked as such, since the specification strongly enco...
...he user instead doesn't make a choice at all, neither callback is executed. this is a legacy method. please use the newer navigator.mediadevices.getusermedia() instead. while technically not deprecated, this old callback version is marked as such, since the specification strongly encourages using the newer promise returning version. syntax navigator.getusermedia(constraints, successcallback,
errorcallback); parameters constraints a mediastreamconstraints object specifying the types of media to request, along with any requirements for each type. for details, see the constraints section under the modern mediadevices.getusermedia() method, as well as the article capabilities, constraints, and settings. successcallback a function which is invoked when the request for media access is app...
...e parameter: the mediastream object that contains the media stream. your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as 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. ...
...And 2 more matches
RTCPeerConnection.createOffer() - Web APIs
een deprecated and its use is strongly discouraged. you should update any existing code 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 rtcpeerconnection
errorcallback which will be passed a single domexception 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 ...
...l 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. ...
...riptioninit 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. invalidstate
error the rtcpeerconnection is closed. notreadable
error 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 required to be secured, that results in an
error. operation
error examining the state of the system to determine resource availability in order to generate the offer failed for some reason. example here we see a handler for the neg...
...And 2 more matches
RTCPeerConnection.setLocalDescription() - Web APIs
configuration, the description submitted by calling setlocaldescription() does not immediately take effect. instead, the current connection configuration remains in place until negotiation is complete. only then does the agreed-upon configuration take effect. syntax apromise = rtcpeerconnection.setlocaldescription(sessiondescription); pc.setlocaldescription(sessiondescription, successcallback,
errorcallback); parameters sessiondescription optional an rtcsessiondescriptioninit or rtcsessiondescription which specifies the configuration to be applied to the local end of the connection. if the description is omitted, the webrtc runtime tries to automatically do the right thing. implicit description if you don't explicity provide a session description, the webrtc runtime will try to ha...
...use the promise-based version of setlocaldescription() instead. the parameters for the older form of setlocaldescription() are described below, to aid in updating 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 rtcpeerconnection
errorcallback which gets called if the description can't be set. it is passed a single domexception 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 err...
...ing 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: invalidstate
error the connection's signalingstate is "closed", indicating that the connection is not currently open, so negotiation cannot take place. invalidsessiondescription
error the rtcsessiondescription specified by the sessiondescription parameter is invalid. examples implicit descriptions one of the advantages of the parameter-free form of setlocaldescription() is that it lets you simplify your n...
...And 2 more matches
Using Service Workers - Web APIs
quest api. those features are not used here so that you can focus on understanding promises. const imgload = (url) => { return new promise((resolve, reject) => { var request = new xmlhttprequest(); request.open('get', url); request.responsetype = 'blob'; request.onload = () => { if (request.status == 200) { resolve(request.response); } else { reject(
error('image didn\'t load successfully;
error code:' + request.statustext)); } }; request.on
error = () => { reject(
error('there was a network
error.')); }; request.send(); }); } we return a new promise using the promise() constructor, which takes as an argument a callback function with resolve and reject parameters. somewhere in the function, we need to define what happ...
...in the resolved case, we display the image inside myimage and append it to the body (its argument is the request.response contained inside t...
...in the resolved case, we display the image inside myimage and append it to the body (its argument is the request.response contained inside the promise’s resolve met...
...And 2 more matches
WebRTC API - Web APIs
ned to the closing state, indicating that it will be closed soon. you can detect the completion of the closing process by watching for the close event. connectionstatechange the connection's state, which can be accessed in connectionstate, has changed. datachannel a new rtcdatachannel is available following the remote peer opening a new data channel. this event's type is rtcdatachannelevent.
error an rtc
errorevent indicating that an
error occurred on the data channel.
error an rtc
errorevent indicating that an
error occurred on the rtcdtlstransport. this
error will be either dtls-failure or fingerprint-failure. gatheringstatechange the rtcicetransport's gathering state has changed. icecandidate an rtcpeerconnectioniceevent which is sent whenever the local device has identified a new ...
... iceconnectionstatechange sent to an rtcpeerconnection when its ice connection's state—found in the iceconnectionstate property—changes. icegatheringstatechange sent to an rtcpeerconnection when its ice gathering state—found in the icegatheringstate property—changes. ...
... iceconnectionstatechange sent to an rtcpeerconnection when its ice connection's state—found in the iceconnectionstate property—changes. icegatheringstatechange sent to an rtcpeerconnection when its ice gathering state—found in the icegatheringstate property—changes. ...
...And 2 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
a possible s...
... a possible solution a possible way to solve the "this" problem is to replace the two native settimeout() or setinterval() global fun...
... a possible solution a possible way to solve the "this" problem is to replace the two native settimeout() or setinterval() global functions with...
...And 2 more matches
WritableStreamDefaultWriter - Web APIs
ite to the underlying sink. constructor writablestreamdefaultwriter() creates a new writablestreamdefaultwriter object instance. properties writablestreamdefaultwriter.closedread only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the writer's lock is released, or rejects if the stream
errors. writablestreamdefaultwriter.desiredsizeread only returns the desired size required to fill the stream's internal queue. writablestreamdefaultwriter.readyread only returns a promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. methods writablestreamdefaultwrit...
...aultwriter.readyread only returns a promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. ...
... no longer successfully write to the stream and it is to be immediately moved to an
error state, with any queued writes discarded. writablestreamdefaultwriter.close() closes the associated writable stream. writablestreamdefaultwriter.releaselock() releases the writer's lock on the corresponding stream. after the lock is released, the writer is no longer active. if the associated stream is
errored when the lock is released, the writer will appear
errored in the same way from now on; otherwise, the writer will appear closed. writablestreamdefaultwriter.write() writes a passed chunk of data to a writablestream and its underlying sink, then returns a promise that resolves to indicate the success or failure of the write operation. examples the following example shows the creation o...
...And 2 more matches
Using XMLHttpRequest - Web APIs
{ var arraybuffer = oreq.response; // not responsetext /* ... */ } oreq.open("get", url); oreq.responsetype = "arraybuffer"; oreq.send(); for more examples check out the sending and receiving binary data page monitoring progress xmlhttprequest provides the ability to listen to various events that can occur while the request is being processed. this includes periodic progress notifications,
error notifications, and so forth. support for dom progress event monitoring of xmlhttprequest transfers follows the specification for progress events: these events implement the progressevent interface. the actual events you can monitor to determine the state of an ongoing transfer are: progress the amount of data that has been retrieved has changed. load the transfer is complete; all data is n...
...gressevent interface. the actual events you can monitor to determine the state of an ongoing transfer are: progress the amount of data that has been retrieved has changed. load the transfer is complete; all data is now in the response var oreq = new xmlhttprequest(); oreq.addeventlistener("progress", updateprogress); oreq.addeventlistener("load", transfercomplete); oreq.addeventlistener("
error", transferfailed); oreq.addeventlistener("abort", transfercanceled); oreq.open(); // ... // progress on transfers from the server to the client (downloads) function updateprogress (oevent) { if (oevent.lengthcomputable) { var percentcomplete = oevent.loaded / oevent.total * 100; // ... } else { // unable to compute progress information since the total size is unknown } } fun...
... server to the client (downloads) function updateprogress (oevent) { if (oevent.lengthcomputable) { var percentcomplete = oevent.loaded / oevent.total * 100; // ... } else { // unable to compute progress information since the total size is unknown } } function transfercomplete(evt) { console.log("the transfer is complete."); } function transferfailed(evt) { console.log("an
error occurred while transferring the file."); } function transfercanceled(evt) { console.log("the transfer has been canceled by the user."); } lines 3-6 add event listeners for the various events that are sent while performing a data transfer using xmlhttprequest. note: you need to add the event listeners before calling open() on the request. otherwise the progress events will not fire. the prog...
...And 2 more matches
XMLHttpRequest: loadend event - Web APIs
the loadend event is fired when a request has completed, whether successfully (after load) or unsuccessfully (after abort or
error). ...
...has completed, whether successfully (after load) or unsuccessfully (after abort or
error). ...
...ssfully (after abort or
error). ...
...And 2 more matches
Alerts - Accessibility
examples of common problems include e-mail addresses which are not valid, or a name field which does not contain at least a first name or a surname. the form first, please read about the aria-required technique if you have not done so, as this technique expands upon that. ...
...contains the “@” symbol, and if the name entry contains at least 1 character. if the above criteria is not met, the field’s aria-invalid attribute will be given a value of “true”. if the criteria was not met, the user will be notified via an alert. instead of using the javascript ‘alert’ function, we’ll use a simple wai-aria widget for notification. this notifies the user of the
error, but allows for them continue modifying the form without losing focus (caused by the “onblur” handler in javascript's default ‘alert’ function). below is example javascript code which could be inserted above the closing “head” tag: <script type="application/javascript"> function removeoldalert() { var oldalert = document.getelementbyid("alert"); if (oldalert){ documen...
..."aria-invalid", "true"); addalert(amsg); } else { elem.setattribute("aria-invalid", "false"); removeoldalert(); } } </script> the checkvalidity function the primary method in javascript used for form validation is the checkvalidity function. this method takes three parameters: the id of the input that is to be validated, the term to search for to ensure validity, and the
error message to be inserted into the alert. to see if it is valid, the function checks whether the indexof the input’s value is anything greater than -1. a value of -1 or less is returned if the index of the search term could not be found within the value. if invalid, the function does two things: it sets the element’s aria-invalid attribute to “true”, which will indicate to screen reader...
...And 2 more matches
Accessibility Information for Web Authors - Accessibility
ce (available in english and in 9 other languages) on accessible website authoring, which goes into greater depth. in 30 days, you will know why your website should be accessible and how to make it more accessible. automated checking & repair cynthia says™ from hisoftware® company "cynthia says™" is a free online webpage accessibility validation service that is designed to identify
errors in webpage related to section 508 standards and/or the wcag guidelines. it can perform a "complete webpage quality check" for accessibility, privacy, searchability, metadata and even alt text attribute quality. the web author chooses the guidelines (as a basis for
errors and warnings) to be used by "cynthia says™": section 508, wcag priorities 1, 2 and 3. the output data report is displayed in...
...for manual verification, not selected, not available, not related, etc. accessibility valet from webthing description and summary to be written. wave 4.0 beta (web accessibility versatile evaluator) from webaim and sponsored by temple university institute on disabilities wave 4.0 beta is another powerful, free online webpage accessibility validation service that identifies accessibility
errors and reports accessibility warnings about webpage related to section 508 standards and/or the wcag guidelines. its purpose is to aid humans in the web accessibility evaluation process. rather than providing a complex technical report, wave 4.0 shows the original web page with embedded icons and indicators that reveal the accessibility information within your page. you can get accessibity report f...
...nd reports accessibility warnings about webpage related to section 508 standards and/or the wcag guidelines. its purpose is to aid humans in the web accessibility evaluation process. rather than providing a complex technical report, wave 4.0 shows the original web page with embedded icons and indicators that reveal the accessibility information within your page. you can get accessibity report for
errors, warnings. you can view the structure and order view of the document. you can see a text-only view and and outline view of the document. you can install a custom wave toolbar in firefox for a quick, easy and convenient evaluation of web pages directly within firefox. you can also add a wave bookmarklet in firefox or even wave direct links for checking a webpage. html advanced validator (fi...
...And 2 more matches
Box-shadow generator - CSS: Cascading Style Sheets
node; this.topic = topic; this.checkbox = checkbox; checkbox.addeventlistener('change', function(e) { notify.call(this); }.bind(this)); buttons[topic] = this; } var getnode = function getnode(topic) { return buttons[topic].node; } var setvalue = function setvalue(topic, value) { try { buttons[topic].checkbox.checked = value; notify.call(buttons[topic]); } catch(
error) { console.log(
error, topic, value); } } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { if (subs...
...ebutton = function togglebutton(topic, value) { var display = (value === true) ? ...
...on(topic, value) { var display = (value === true) ? ...
...And 2 more matches
Feature-Policy - HTTP
face. when this policy is disabled and there were no user gestures, the promise returned by htmlmediaelement.play() will reject with a domexception. 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 notallowed
error domexception. camera controls whether the current document is allowed to use video input devices. when this policy is disabled, the promise returned by getusermedia() will reject with a notallowed
error domexception. display-capture controls whether or not the current document is permitted to use the getdisplaymedia() method to capture screen contents. when this policy is disabled, the promise...
...t is allowed to use video input devices. when this policy is disabled, the promise returned by getusermedia() will reject with a notallowed
error domexception. display-capture controls whether or not the current document is permitted to use the getdisplaymedia() method to capture screen contents. when this policy is disabled, the promise returned by getdisplaymedia() will reject with a notallowed
error 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 security
error domexception to be be thrown. encrypted-media controls whether the current document is allowed to use the encrypted media extensions api (eme...
... execute in frames while they're not being rendered (e.g. if an iframe is hidden or display: none). execution-while-out-of-viewport controls whether tasks should execute in frames while they're outside of the visible viewport. fullscreen controls whether the current document is allowed to use element.requestfullscreen(). when this policy is disabled, the returned promise rejects with a type
error. geolocation controls whether the current document is allowed to use the geolocation interface. when this policy is disabled, calls to getcurrentposition() and watchposition() will cause those functions' callbacks to be invoked with a position
error code of permission_denied. gyroscope controls whether the current document is allowed to gather information about the orientation of the device th...
...And 2 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
e ... slightly odd. and array, which is a special kind of object. and date and regexp, which are objects that you get for free. and to be technically accurate, functions are just a special type of object. so the type diagram looks more like this: number string boolean symbol (new in es2015) object function array date regexp null undefined and there are some built-in
error types as well. things are a lot easier if we stick with the first diagram, however, so we'll discuss the types listed there for now. numbers numbers in javascript are "double-precision 64-bit format ieee 754 values", according to the spec — there's no such thing as an integer in javascript (except bigint), so you have to be a little careful. see this example: console.log(3 / 2); ...
...variable is *not* visible out here for (let myletvariable = 0; myletvariable < 5; myletvariable++) { // myletvariable is only visible in here } // myletvariable is *not* visible out here const allows you to declare variables whose values are never intended to change. the variable is available from the block it is declared in. const pi = 3.14; // variable pi is set pi = 1; // will throw an
error because you cannot change a constant variable. var is the most common declarative keyword. it does not have the restrictions that the other two keywords have. this is because it was traditionally the only way to declare a variable in javascript. a variable declared with the var keyword is available from the function it is declared in. var a; var name = 'simon'; an example of scope with a var...
...alue?') these are also semantically equivalent. the second method has the advantage that the name of the property is provided as a string, which means it can be calculated at run-time. however, using this method prevents some javascript engine and minifier optimizations being applied. it can also be used to set and get properties with names that are reserved words: obj.for = 'simon'; // syntax
error, because 'for' is a reserved word obj['for'] = 'simon'; // works fine starting in ecmascript 5, reserved words may be used as object property names "in the buff". this means that they don't need to be "clothed" in quotes when defining object literals. see the es5 spec. for more on objects and prototypes see object.prototype. for an explanation of object prototypes and the object prototype ch...
...And 2 more matches
Warning: 08/09 is not a legal ECMA-262 octal constant - JavaScript
javascript execution won't be halted. what went wrong? decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. ...
...javascript execution won't be halted. what went wrong? decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. ...
...javascript execution won't be halted. what went wrong? decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. ...
...And 2 more matches
Array.prototype.reduce() - JavaScript
rwise, it starts from index 1. array optional the array reduce() was called upon. initialvalue optional a value to use as the first argument to the first call of the callback. if no initialvalue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentvalue. calling reduce() on an empty array without an initialvalue will throw a type
error. return value the single value that results from the reduction. description the reduce() method executes the callback once for each assigned value present in the array, taking four arguments: accumulator currentvalue currentindex array the first time the callback is called, accumulator and currentvalue can be one of two values. if initialvalue is provided in the call to reduce(), the...
...he array. if no initialvalue is provided, then accumulator will be equal to the first value in the array, and currentvalue will be equal to the second. note: if initialvalue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. if initialvalue is provided, it will start at index 0. if the array is empty and no initialvalue is provided, type
error will be thrown. if the array only has one element (regardless of position) and no initialvalue is provided, or if initialvalue is provided but the array is empty, the solo value will be returned without calling callback. it is almost always safer to provide an initialvalue, because there can be up to four possible output types without initialvalue, as shown in the following example: let maxcal...
...ck = ( acc, cur ) => math.max( acc.x, cur.x ); let maxcallback2 = ( max, cur ) => math.max( max, cur ); // reduce without initialvalue [ { x: 2 }, { x: 22 }, { x: 42 } ].reduce( maxcallback ); // nan [ { x: 2 }, { x: 22 } ].reduce( maxcallback ); // 22 [ { x: 2 } ].reduce( maxcallback ); // { x: 2 } [ ].reduce( maxcallback ); // type
error // map & reduce with initialvalue; better solution, also works for empty or larger arrays [ { x: 22 }, { x: 42 } ].map( el => el.x ) .reduce( maxcallback2, -infinity ); how reduce() works suppose the following use of reduce() occurred: [0, 1, 2, 3, 4].reduce(function(accumulator, currentvalue, currentindex, array) { return accumulator + currentvalue }) the callbac...
...And 2 more matches
Object.seal() - JavaScript
t fixed and immutable. making all properties non-configurable also prevents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a type
error (most commonly, although not exclusively, when in strict mode code). the prototype chain remains untouched. however, the __proto__ property is sealed as well. comparison to object.freeze() existing properties in objects frozen with object.freeze() are made immutable. objects sealed with object.seal() can have their existing properties changed. examples using object.seal var obj = { prop: ...
...hanged or removed. obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; var o = object.seal(obj); o === obj; // true object.issealed(obj); // === true // changing property values on a sealed object // still works. obj.foo = 'quux'; // but you can't convert data properties to accessors, // or vice versa. ...
...ert data properties to accessors, // or vice versa. object.defineproperty(obj, 'foo', { get: function() { return 'g'; } }); // throws a type
error // now any changes, other than to property values, // will fail. obj.quaxxor = 'the friendly duck'; // silently doesn't add the property delete obj.foo; // silently doesn't delete the property // ...and in strict mode such attempts // will throw type
errors. function fail() { 'use strict'; delete obj.foo; // throws a type
error obj.sparky = 'arf'; // throws a type
error } fail(); // attempted additions through // object.defineproperty will also throw. ...
...And 2 more matches
Promise.all() - JavaScript
the promise.all() method takes an iterable of promises as an input, and returns a single promise that resolves to an array of the results of the input promises. this returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises. it rejects immediately upon any of the input promises rejecting or non-promises throwing an
error, and will reject with this first rejection message /
error. the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax promise.all(iterable); parameters iterable an iterable object such as an array. return value an already resolved pro...
...((resolve, reject) => { settimeout(() => resolve('one'), 1000); }); var p2 = new promise((resolve, reject) => { settimeout(() => resolve('two'), 2000); }); var p3 = new promise((resolve, reject) => { settimeout(() => resolve('three'), 3000); }); var p4 = new promise((resolve, reject) => { settimeout(() => resolve('four'), 4000); }); var p5 = new promise((resolve, reject) => { reject(new
error('reject')); }); // using .catch: promise.all([p1, p2, p3, p4, p5]) .then(values => { console.log(values); }) .catch(
error => { console.
error(
error.message) }); //from console: //"reject" it is possible to change this behaviour by handling possible rejections: var p1 = new promise((resolve, reject) => { settimeout(() => resolve('p1_delayed_resolution'), 1000); }); var p2 = new promis...
... ...
...And 2 more matches
String.prototype.repeat() - 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 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 range
error: repeat count must be non-negative. range
error: 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) { string.prototype.
...ty 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. ...
...() with the following snippet: if (!string.prototype.repeat) { string.prototype.repeat = function(count) { 'use strict'; if (this == null) throw new type
error('can\'t convert ' + this + ' to object'); var str = '' + this; // to convert string to integer. count = +count; // check nan if (count != count) count = 0; if (count < 0) throw new range
error('repeat count must be non-negative'); if (count == infinity) throw new range
error('repeat count must be less than infinity'); count = math.floor(count); if (str.length == 0 || count == 0) return ''; // ensuring count is a 31-bit integer allows us to heavily optimize the // main part. but anyway, most current (august 2014) browsers can't handle // strings 1 <...
...And 2 more matches
Object initializer - JavaScript
us a pull request. syntax let o = {} let o = {a: 'foo', b: 42, c: {}} let a = 'foo', b = 42, c = {} let o = {a: a, b: b, c: c} let o = { property: function (parameters) {}, get property() {}, set property(value) {} }; new notations in ecmascript 2015 please see the compatibility table for support for these notations. in non-supporting environments, these notations will lead to syntax
errors. // shorthand property names (es2015) let a = 'foo', b = 42, c = {}; let o = {a, b, c} // shorthand method names (es2015) let o = { property(parameters) {} } // computed property names (es2015) let prop = 'foo' let o = { [prop]: 'hey', ['b' + 'ar']: 'there' } description an object initializer is an expression that describes the initialization of an object. objects consist of propertie...
...rty": value syntax. the property name must be double-quoted, and the definition cannot be a shorthand. in json the values can only be strings, numbers, arrays, true, false, null, or another (json) object. a function value (see "methods" above) can not be assigned to a value in json. objects like date will be a string after json.parse(). json.parse() will reject computed property names and an
error will be thrown. examples creating objects an empty object with no properties can be created like this: let object = {} however, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. you simply notate a list of key: value pairs delimited by commas. the following code creates an object with three properti...
...a = 'foo', b = 42, c = {}; // shorthand property names (es2015) let o = {a, b, c} // in other words, console.log((o.a === {a}.a)) // true duplicate property names when using the same name for your properties, the second property will overwrite the first. let a = {x: 1, x: 2} console.log(a) // {x: 2} in ecmascript 5 strict mode code, duplicate property names were considered a syntax
error. ...
...And 2 more matches
throw - JavaScript
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. ...
... expression to throw. description use the throw statement to throw an exception. when you throw an exception, expression specifies the value of the exception. each of the following throws an exception: throw '
error2'; // generates an exception with a string value throw 42; // generates an exception with the value 42 throw true; // generates an exception with the value true throw new
error('required'); // generates an
error object with the message of required also note that the throw statement is affected by automatic semicolon insertion (asi) as no line terminator between the throw keyword and the expression is allowed. examples throw an object you can specify an object when you throw an exception. you can then reference the object's properties in the catch block. the follow...
...zip code. if the zip code uses an invalid format, the throw statement throws an exception by creating an object of type zipcodeformatexception. /* * creates a zipcode object. * * accepted formats for a zip code are: * 12345 * 123...
...And 2 more matches
Classes and Inheritance - Archive of obsolete content
type of the newly created object: let shape = shape(2, 3); object.getprototypeof(shape) == shape.prototype; // => true all instances of a class have the same prototype. this makes the prototype the perfect place to define properties that are shared between instances of the class. to illustrate this, let's add a member function to the class shape: shape.prototype.draw = function () { throw
error("not yet implemented"); } let shape = shape(2, 3); shape.draw(); // =>
error: not yet implemented inheritance and constructors suppose we want to create a new class, circle, and inherit it from shape. since every circle is also a shape, the constructor for shape must be called every time we call the constructor for circle. since javascript does not have native support for inheritance, it doesn...
... constructor to create instances of the class circle: let circle = circle(2, 3, 5); circle instanceof circle; // => true circle.x; // => 2 circle.y; // => 3 circle.radius; // => 5 inheritance and prototypes there is a problem with the definition of circle in the previous section that we have glossed over thus far. consider the following: let circle = circle(2, 3, 5); circle.draw(); // => type
error: circle.draw is not a function this is not quite right. the method draw is defined on instances of shape, so we definitely want it to be defined on instances of circle. the problem is that draw is defined on the prototype of shape, but not on the prototype of circle. we could of course copy every property from the prototype of shape over to the prototype of circle, but this is needlessly ineffi...
...totype chain of an object from the bottom up. consequently, overriding a method is as simple as providing a new definition on the prototype of the subclass: circle.prototype.draw = function (ctx) { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, 2 * math.pi, false); ctx.fill(); }; with this definition in place, we get: let shape = shape(2, 3); shape.draw(); //
error: not yet implemented let circle = circle(2, 3, 5); circle.draw(); // type
error: ctx is not defined which is the behavior we were aiming for. classes in the add-on sdk we have shown how to emulate classical inheritance in javascript using constructors and prototypes. however, as we have seen, this takes a significant amount of boilerplate code. the add-on sdk team consists of highly trained pr...
...nt, which is an object which properties will be defined on the prototype of the resulting constructor. the semantics of class are based on what we've learned earlier. for instance, to define a constructor for a class shape in terms of class, we can write: let shape = class({ initialize: function (x, y) { this.x = x; this.y = y; }, draw: function () { throw new
error("not yet implemented"); } }); the property initialize is special. when it is present, the call to the constructor is forwarded to it, as are any arguments passed to it (including the this object). in effect, initialize specifies the body of the constructor. note that the constructors created with class automatically check whether they are called as constructors, so an explicit check is no l...
event/target - Archive of obsolete content
chaining emitters can also have their m...
... chaining emitters can also have their methods chained: target.on('message', handlemessage) .on('data...
...('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 console. chaining emitters can also have their methods chained: target.on('message', handlemessage) .on('data', parsedata) .on('
error', hand...
...events on these objects may be emitted via emit function exported by event/core module. methods initialize() method initializes this event source. it goes through properties of a given options and registers listeners for the ones that look like event listeners. ...
platform/xpcom - Archive of obsolete content
y is unregistered as soon as the add-on which created it is unloaded. by including this option, set to false, the factory is not automatically unregistered and you must unregister it manually using the unregister() function. functions register(factory) register the factory or service supplied. if the factory or service is already registered, this function throws components.results.ns_
error_factory_exists. by default, factories and services are registered automatically, so you should only call register() if you have overridden the default behavior. parameters factory : object the factory or service to register. unregister(factory) unregister the factory or service supplied. if the factory or service is not registered, this function does nothing. by default, factories and serv...
...ervice isn't registered, this function returns null. this function wraps components.classesbyid. parameters id : string a class id. returns object : the factory or service identified by the class id. factorybycontract(contract) given a contract id this function returns the associated factory or service. if the factory or service isn't registered, this function throws components.results.ns_
error_factory_not_registered. this function is similar to the standard components.classes[contractid] with one significant difference: that components.classes is not updated at runtime. so if a factory is registered with the contract id "@me.org/mycomponent", and another factory is already registered with that contract id, then: components.classes["@me.org/mycomponent"] will return the old factory,...
... it yourself. it is passed an interface identifier and searches for the identifier in the interfaces property of: this object any of this object's ancestors any classes in the implements array property of the instance (for example, any classes added to this object via the implements option defined in heritage). if it finds a match, it returns this, otherwise it throws components.results.ns_
error_no_interface. parameters interface : iid the interface to ask for. this is typically given as a property of the components.interfaces object. returns object : the object itself(this). properties interfaces the set of interfaces supported by this class. unknown sets this to nsisupports. factory use this class to register an xpcom factory. to register a factory for a component, construct ...
...eated it is unloaded. to override this behavior, you can pass register and/or unregister options, set to false. if you do this, you can use the register() and unregister() functions to register and unregister. methods createinstance(outer, iid) creates an instance of the component associated with this factory. parameters outer : null this argument must be null, or the function throws cr.ns_
error_no_aggregation. iid : iid interface identifier. these objects are usually accessed through the components.interfaces, or ci, object. the methods of this interface will be callable on the returned object. if the object implements an interface that's already defined in xpcom, you can pass that in here: var about = aboutfactory.createinstance(null, ci.nsiaboutmodule); // you can now access the n...
jpm - Archive of obsolete content
with the node package manager npm. installing npm there are two ways to get npm. download and install node.js from nodejs.org. node.js includes npm. or, if you have a package manager like apt, install npm via that. for example, in an ubuntu or debian terminal window, enter sudo apt-get install nodejs nodejs-legacy npm. to test your installation, run: /usr/bin/env node -v if you get an
error message saying /usr/bin/env: node: no such file or directory and you have installed nodejs through a package manager, nodejs may have been installed under a different executable name. to ensure compatibility with jpm, however, it must be present in your path under the name node. on debian and ubuntu, this can be remedied by ensuring you installed the compatibility package, nodejs-legacy: sudo a...
...ding the built-in modules for more information. -p --profile profile by default, jpm uses a clean temporary firefox profile each time you call jpm run. use the --profile option to instruct jpm to launch firefox with an existing profile. the profile value may be a profile name or the path to the profile. see using profiles for more information. --stop-on-
error by default, jpm test keeps running tests even after tests fail. specify --stop-on-
error to stop running tests after the first failure: jpm test --stop-on-
error --tbpl print test output in treeherder format --times number run tests number of times: jpm test --times 2 -v --verbose verbose operation. --no-copy use wi...
...ost:8888/ see using post and watchpost for more information. -v --verbose verbose operation: jpm watchpost --post-url http://localhost:8888/ -v jpm sign this feature is only supported from jpm 1.0.4 onwards. this command retrieves a new xpi for your add-on signed by mozilla. this allows you to self-host your add-on so that users can install it without
error when signed add-ons are required. you can sign an xpi you've already generated by passing the xpi file in the --xpi argument, like this: jpm sign --api-key ${jwt_issuer} --api-secret ${jwt_secret} --xpi <xpi file> alternatively, you can omit the --xpi argument, in which case jpm sign will generate an xpi from the current directory (or --addon-dir). jpm sign --api-key ${jwt_issuer} --api-secre...
...mozilla.org. on the amo key management page, these values are labeled "jwt_issuer" and "jwt_secret". here are some possible outcomes of running the sign command: your add-on passed validation, was signed by mozilla, and a new signed xpi was downloaded to your working directory. your add-on failed validation, was not signed, and you got a link to a detailed report. after fixing the validation
errors, you can run the command again. you add-on passed validation but it could not be automatically signed because your add-on is listed. listed add-ons will require a manual review before they can be signed. your add-on at this exact version number already exists, so it was not signed. increment the version number in your package.json file and run the command again. under the hood, jpm sign crea...
How to convert an overlay extension to restartless - Archive of obsolete content
it from an interface: const xmlhttprequest = components.constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsixmlhttprequest"); here's how to load a file using it: function loadfile(url,type,returnresult) { var request = new xmlhttprequest(); request.open("get", url, true); // async=true request.responsetype = type; request.on
error = function(event) { log
errormessage("
error attempting to load: " + url); returnresult(null); }; request.onload = function(event) { if (request.response) returnresult(request.response); else request.on
error(event); }; request.send(); } loadfile("chrome://myaddon/content/filename.ext",datatype,function(data) { /* do stuff w...
...cate success. in such cases, request.readystate == 4, request.status == 0 and request.response will evaluate to true. if your file is text, use "text" as your data type. if you're getting json this way make sure to explicitly set the type as "text" if you intend to parse it yourself. even though it says that the default type is "text", firefox will attempt to autodetect and fail, resulting in an
error message in the console. this doesn't seem to break anything, but it is easily avoidable by being explicit with the type. mdn says you can set the type to "json" instead, if you prefer to have it parse things for you. if your file is not text or json, then you're going to want to read binary data. the new way to do this is to use javascript typed arrays. specify "arraybuffer" as your data type to...
...king add-on that will update without a firefox restart... usually. some parts work only if you don't look too closely; localization is one of them. as mentioned in the previous section, you'll need to clear the chrome caches on add-on shutdown, namely for chrome images and properties files. doing this will get an update's new properties file to load, however sometimes this will instead produce an
error on the next property access. it just doesn't seem that it can reliably clear the cache correctly, for whatever reason. string changes seem to be fine, however the addition or removal of strings can sometimes produce this
error. it's not reliably reproducible, but it does happen. yes, this is a pain in the ass. the suggestion that seems to work is to use a hack to bypass the string bundle cache. ...
...esource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/xpcomutils.jsm"); xpcomutils.definelazygetter(this, "strings", function() { return loadpropertiesfile("chrome://myaddon/locale/mystrings.properties"); }); function loadpropertiesfile(path) { /* hack: the string bundle cache is cleared on addon shutdown, however it doesn't appear to do so reliably.
errors can erratically happen on next load of the same file in certain instances. (at minimum, when strings are added/removed) the apparently accepted solution to reliably load new versions is to always create bundles with a unique url so as to bypass the cache. this is accomplished by passing a random number in a parameter after a '?'. (this random id is otherwise ignored) the loa...
Connecting to Remote Content - Archive of obsolete content
son, html and plain text. in this section we'll look into the xml and json communication mechanisms. let url = "http://www.example.com/"; let request = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(components.interfaces.nsixmlhttprequest); request.onload = function(aevent) { window.alert("response text: " + aevent.target.responsetext); }; request.on
error = function(aevent) { window.alert("
error status: " + aevent.target.status); }; request.open("get", url, true); request.send(null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode. you can see that an instance of the xmlhttprequest class is created and it holds all functionality for making a request. we create this instance using xpcom instead of the usua...
...null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode. you can see that an instance of the xmlhttprequest class is created and it holds all functionality for making a request. we create this instance using xpcom instead of the usual way (new xmlhttprequest()) because this way works both in chrome and non-chrome code. following initialization, onload and on
error handlers are registered to a callback function to handle the response returned from the remote server. in both cases aevent.target is an nsixmlhttprequest. in the onload callback function, the responsetext parameter contains the server response as text. if the response is an xml document, the responsexml property will hold an xmldocument object that can be manipulated using dom methods. sometime...
... </shops> <total>2</total> </data> when a valid xml response comes back from the remote server, the xml document object can be manipulated using different dom methods, to display the data in the ui or store it into a local datasource. ...
... a normal firefox window, so use it sparingly. a tutorial on tamper data can be found here. note: you should always test your connection code to cover edge cases, like when there is no internet connection, or the computer is connected to a local network with no internet access (like at an airport or hotel room). make sure you're not telling users everything is ok, or worse, bombarding them with
error messages. « previousnext » this tutorial was kindly donated to mozilla by appcoast. ...
XPCOM Objects - Archive of obsolete content
identifier, in this case corresponding to the observer service. you'll usually know what string to use by reading examples and documentation. there is no comprehensive list of these (that we know of), and that's understandable since it would be a very long list, and it can be extended by add-ons. if you want to see the list in your current firefox installation, just run the following code in the
error console: var str = ""; for (var i in components.classes) { str += i + "\n" }; str a run on firefox 3.6.2 with a few extensions installed yields 876 strings. that's quite a lot. luckily, you'll only need to know a handful of those for extension development. the @mozilla.org/ prefix is just a way to keep things namespaced. we would use something like @xulschool.com/ to make our own components...
...t installed at the same time. the implementation object itself should be easy to understand. the only aspects to take into account are that methods and attributes 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 purp...
...; categorymanager.addcategoryentry( "content-policy", "xulschool hello world", contract_id, true, true); }, in this case the component would need to implement nsicontentpolicy. and, finally, the factory object. var counterfactory = { /* single instance of the component. */ _singletonobj: null, createinstance: function(aouter, aiid) { if (aouter != null) { throw cr.ns_
error_no_aggregation; } // in this case we need a unique instance of the service. if (!this._singletonobj) { this._singletonobj = messagecounter; } return this._singletonobj.queryinterface(aiid); } }; if we wanted a class that can be instantiated, instead of a singleton service, the factory would look like this: var counterfactory = { createinstance: function(aoute...
...ique instance of the service. if (!this._singletonobj) { this._singletonobj = messagecounter; } return this._singletonobj.queryinterface(aiid); } }; if we wanted a class that can be instantiated, instead of a singleton service, the factory would look like this: var counterfactory = { createinstance: function(aouter, aiid) { if (aouter != null) { throw cr.ns_
error_no_aggregation; } return (new counter()).queryinterface(aiid); } }; the instructions on how to build an idl file are included in the section setting up a development environment. c++ xpcom components c++ xpcom components are no longer supported in firefox extensions. they are only available to code built into firefox itself. if you are writing an extension and need to interact wi...
popChallengeResponse - Archive of obsolete content
ption "challengestring" a base-64 encoded cmmf popodeckeychallcontent message. the current implementation does not conform to that defined in the cmmf draft, and we intend to change this implementation to that defined in the cmc rfc.. see below for the current implementation. ...
...estring" a base-64 encoded cmmf popodeckeychallcontent message. the current implementation does not conform to that defined in the cmmf draft, and we intend to change this implementation to that defined in the cmc rfc.. see below for the current implementation. ...
...odeckeychallcontent message. the current implementation does not conform to that defined in the cmmf draft, and we intend to change this implementation to that defined in the cmc rfc.. see below for the current implementation. ...
...defined in the cmmf draft, and we intend to change this implementation to that defined in the cmc rfc.. see below for the current implementation. the resultstring will either be a base-64 encoded popodeckeyrespcontent message, or one of the following
error strings:
error string description "
error:invalidparameter:xxx" the parameter xxx was an invalid value. "
error:internal
error" the software encountered some internal
error, such as out of memory challenge-response proof of possession expected input: popodeckeychallcontent ::= sequence of challenge -- one challenge per encryption key certification request (in the -- same order as these requests appear in fullcerttemplates). challenge ::= sequence { owf algorithmidentifie...
Moving, Copying and Deleting Files - Archive of obsolete content
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. there are several methods of the nsifile object which may be used to move and copy files on disk. nsifile.copyto() is used to copy a file, while nsifile.moveto() is used to move files. nsifile.remove() may be used to delete a file. copying a file nsifile.copyto() is used to copy files or directories, and should be called on the source file to copy. this method takes two arguments, the f...
...ed 'source.txt' within the user's home directory to the desktop. in addition, the file is renamed to 'destination.txt'. two file objects are created, the first is the file to copy, and the second is the directory in which to copy the file to. nsifile.copyto() of the former is called, passing the latter as the first argument to nsifile.copyto(). naturally, the destination must be a directory or an
error will occur. in this case, we assume that 'source.txt' is a file. if the item to copy is a directory, it can be copied in the same manner as above without changes. this allows an entire directory and its contents to be copied from one location to another. you might use this to make a backup of a directory of files for instance. var file = io.newfile("home", "importantdata"); var destination = io...
... copying to a different directory, but you would want to specify a filename when copying a file to another name within the same directory. in this latter situation, you may also omit the destination directory. var file = io.newfile("desktop", "myimage.png"); file.copyto(null, "anotherimage.png"); here, a file is copied within the same directory as the supplied destination is null. a number of
errors could occur when copying a file, for instance if the file to copy does not exist or the destination directory is not writable. it is a good idea to enclose file operations within a try-catch block in order to capture any
errors that might occur. for a list of possible file related
errors, see file
errors. moving a file to move a file, nsifile.moveto() may be used which functions similarly to n...
...() before moving the file. deleting a file to delete a file, use nsifile.remove(). this method takes one boolean argument which indicates whether to delete recursively or not. if true and the file object refers to a directory, the directory will be removed as well all files and subdirectories within it. if false, a directory will only be removed if it is empty. if the directory is not empty, an
error will occur. for files, the argument is simply ignored. var file = io.newfile("home", "photo.jpg"); file.remove(false); this example removes the file called 'photo.jpg'. ...
Additional Install Features - Archive of obsolete content
le:///","bin"); var grep = getfolder(binfolder, "grep"); var mainfolder = getfolder("file:///", "main"); file.copy(grep, mainfolder); the first line will retrieve a reference to the /bin directory. the text 'file:///' is a special string which means the root of the filesystem. from there, we get the file 'grep' which is contained inside the 'bin' directory. ...
...'bin' directory. if this file does not exist, an
error will occur during the installation. next, we get the 'main' folder, again from the file system root. finally, we call the file.copy function which copies the source file to the destination. functions also exist to move(), rename() and execute() files. thus, you can move files that might conflict with your package out of the way. handling
errors you will likely want to handle
errors gracefully. this will occur if a file or directory cannot be found, there is insufficient disk space or for a number of other reasons. you can use the getlast
error() function to determine whether an
error occured. if it returns success, no
error occured. otherwise, the number will be an
error code which indicates the type of
error that occured. you can call ...
...irectory cannot be found, there is insufficient disk space or for a number of other reasons. you can use the getlast
error() function to determine whether an
error occured. if it returns success, no
error occured. otherwise, the number will be an
error code which indicates the type of
error that occured. you can call this function at any point during the installation script to determine whether an
error occured during the last operation. if an
error occurs, you will likely want to abort the installation. you may also want to display an
error message to the user. ...
... which indicates the type of
error that occured. you can call this function at any point during the installation script to determine whether an
error occured during the last operation. if an
error occurs, you will likely want to abort the installation. you may also want to display an
error message to the user. for example, you might put the following as the last section of your script: if (getlast
error() == success) { performinstall(); } else { cancelinstall(); }
error codes that could be returned by getlast
error() are listed in the mozilla source file nsinstall.h. during installation, a log file is created that contains the operations that are performed. it will also show any
errors that occured. the log file can be found in the file 'install.log' in the mozilla installation directory. a ...
XUL Questions and Answers - Archive of obsolete content
a scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn’t work on a mac? unfortunately, no simple solution to this...
... a scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn’t work on a mac? unfortunately, no simple solution to this was pos...
... animated gif; support for apng is planned) plugins templates with non-rdf datasources? support for non-rdf datasources for xul template is planned (bug 321170): xml datasources (bug 321171) storage (sqlite) datasources (bug 321172) when loading an xslt stylesheet into an xml i get the
error: "
error loading stylesheet: an xslt stylesheet load was blocked for security reasons." that
error is from a security check that has been put up to safeguard against cross-site-scripting attacks. a scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn’t work on a mac? unfortunately, no simple solution to this was posted. a workaround is to open the content in a new window using "window.open" and send title...
...generated from the rdf datasource create the element, set the datasources attribute then add the element to the document. this should then create the database. xulrunner questions these don't really belong on this page. is there a way to check what directory "application.ini" is in? use directory service the key to the folder where application.ini resides is "resource:app". i get the
error: gecko minversion requirement not met. visit http://developer.mozilla.org/en/docs...pplication.ini to find out how to properly set up the application.ini file. how can i use other fonts on xulrunner applications which are not installed on the current machine? in order to do this, you must first attach the font file as a bundle with the xulrunner application as a bundle. you also have to writ...
XUL accessibility guidelines - Archive of obsolete content
ft-alt + left-shift + printscreen). confirm that text is emphasized correctly and that color is not used as a sole means to convey meaning. ensure that when windows are resized, the application adjusts gracefully. human computer interaction as you use an application you expect a certain amount of control and feedback. provide users with clear instruction and feedback, and allow users to correct
errors. some users with disabilities have difficulties with quick responses. allow users adequate time to perform tasks. instruction provide users with help documentation. even simple applications should include a help document or manual for user reference. describe keyboard shortcuts and any other accessibility considerations. users should be able to reference a complete description of all major fun...
...l disabilities will not be able to observe alerts that are purely visual (unless such alerts are presented in functional text that is accessible to a screen reader). interactive elements avoid small targets, which are difficult to see and click on. verify that the layout and contrast is sufficient to distinguish interactive elements one from another and from static portions of the application.
error recovery when the user causes an
error in an application allow for graceful recovery. for example, if the user provides letters where numbers are required in a form, this should not break the application. the user should be alerted to the problem and allowed to fix the
error. response time when appropriate, alert the user to time limits and allow the user to adjust a time limit or request more...
...uters. some users use mouth sticks or movement detection devices such as eye tracking to type. this process can be slow. other users need time to cognitively process what is happening in the application. testing human computer interaction ensure that help documentation is up to date. verify that alerts are displayed through appropriate xul elements. ensure the user is informed of any user based
errors and that instruction and opportunity for reperforming
error causing actions is allowed. ensure that users have control of response time. media audio informative audio files such as podcasts can be made accessible by supplying a word-for-word transcript. transcripts should identify the speakers and describe other relevant sounds such as laughing or singing. transcripts can be time consuming to...
...g the alert scripting function or the notificationbox element. alerts are conveyed visually or audibly, or use a method other than the alert scripting function or the notificationbox element. interactive elements interactive elements are sufficiently large and visible. interactive elements are too small or not sufficiently contrasted from other parts of the application.
error recovery alerts are presented when the user initiates an
error. the user has the opportunity and instruction to fix the
error. no
error alerts exist, or inadequate instruction is provided. response time user is informed of time limits and has control of response time when appropriate. user is not notified of time limits and/or has no control over response time when appropriat...
Gecko Compatibility Handbook - Archive of obsolete content
not detect other gecko-based browsers. upgrade the browser detection javascript to detect "gecko." (related article) content differs in gecko browsers and internet explorer use of proprietary or invalid markup (such as is generated by some microsoft office applications). use the w3 html and css validator tools to validate the web page. ...
... update browser sniffing to correctly detect gecko browsers. ...
... html id attributes as duplicates if they only differ due to case. there appears to be some inconsistency between the actual html 4.01 recommendation and the sgml declaration for html on whether id attributes are case sensitive or not. this is unfortunate since the html validator is one of the primary vehicles web developers have for learning about the standards. due to the common nature of this
error, netscape 6.2 began treating css id attributes as case-insensitive in quirks mode only. if you are invoking standards mode, you should still code your css to be consistent with respect to case. css class names should be case-sensitive <style type="text/css"> .class1 { font-size: 1em; } .class1 { font-size: 2em; } </style> <div> <div class="class1"> should be font-size: 1em; </div> <div cl...
...tyle> <div> <div class="class1"> should be font-size: 1em; </div> <div class="class1"> should be font-size: 2em; </div> -(example removed)- gecko implements the case sensitivity of class names correctly and will display this example correctly while internet explorer treats all css classnames's as case-insensitive and will not display this example correctly. due to the common nature of this
error by web authors, netscape 6.2 began treating css class attributes as case-insensitive in quirks mode only. if you are invoking standards mode, you should still code your css to be consistent with respect to case. incorrect relative urls a relative url is one which refers to the same web server where a web page is hosted. a relative url that refers to a path relative to the directory where a web ...
2006-10-26 - Archive of obsolete content
er to import bookmark backups user asking for thoughts about having bookmarks manager's import wizard import from backups in the bookmarkbackups folder. no repiles yet. fx 1.5.0.x (linux) not building since 20-oct-2006 17:45 pdt? tony inquires why tinderbox is showing that the fx 1.5.0.x (linux) has failed since october 20. gavin replies that "[t]he log file shows a "no space left on device"
error when trying to link the final executable." learn the traffic magic of search engine cloaking mark describes the magic of search engine cloaker. (what it is, how to use it) cross-post-and followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox newsgroup. firefox killer features suggestion john ...
...ns for "killer features" for firefox. debug minefield on intel mac an inqury about how to debug minefield on an intel mac. rebuild firefox after modifying source code an inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. ...
...no replies yet. ubuntu firefox ua string a user questions ubuntu 6.10 and their firefox's ua string, the zeros seem to be wrong. meetings none this week. ...
...nges' faq a user suggests that a faq page be made for changes, since the same two questions keep coming up. nsialertsservice under linux an inqury about why nsialertsservice is not a service found in firefox 2. is this a bug in firefox? an inqury about inaccurate layout for firefox being a bug - shaver suggests its a bug with gecko instead.
error building firefox-2.0rc3 on uclinux an
error was found about building on uclinux, user googgled the
error and suggests that the
error found in older versions. no replies yet. ubuntu firefox ua string a user questions ubuntu 6.10 and their firefox's ua string, the zeros seem to be wrong. meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
2006-10-27 - Archive of obsolete content
er to import bookmark backups user asking for thoughts about having bookmarks manager's import wizard import from backups in the bookmarkbackups folder. no repiles yet. fx 1.5.0.x (linux) not building since 20-oct-2006 17:45 pdt? tony inquires why tinderbox is showing that the fx 1.5.0.x (linux) has failed since october 20. gavin replies that "[t]he log file shows a "no space left on device"
error when trying to link the final executable." learn the traffic magic of search engine cloaking mark describes the magic of search engine cloaker. (what it is, how to use it) cross-post-and followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox newsgroup. firefox killer features suggestion john ...
...ns for "killer features" for firefox. debug minefield on intel mac an inqury about how to debug minefield on an intel mac. rebuild firefox after modifying source code an inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. ...
...no replies yet. ubuntu firefox ua string a user questions ubuntu 6.10 and their firefox's ua string, the zeros seem to be wrong. meetings none this week. ...
...nges' faq a user suggests that a faq page be made for changes, since the same two questions keep coming up. nsialertsservice under linux an inqury about why nsialertsservice is not a service found in firefox 2. is this a bug in firefox? an inqury about inaccurate layout for firefox being a bug - shaver suggests its a bug with gecko instead.
error building firefox-2.0rc3 on uclinux an
error was found about building on uclinux, user googgled the
error and suggests that the
error found in older versions. no replies yet. ubuntu firefox ua string a user questions ubuntu 6.10 and their firefox's ua string, the zeros seem to be wrong. meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
2006-11-24 - Archive of obsolete content
he is using make 3.80, working with the source tarball for xulrunner 1.8.4,running "make -f client.mk distclean" followed by "make -f client.mk build_all". ...
... he is using make 3.80, working with the source tarball for xulrunner 1.8.4,running "make -f client.mk distclean" followed by "make -f client.mk build_all". ...
...followed by "make -f client.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 ...
...luke wants to know if compiling xulrunner with a static crt is better or worse than compiling with the mscvr80.dll dependency. firefox 1.5 build on windows with gtk2 november 23rd: vin is trying to build firefox 1.5.0.3 on windows xp. the build is working properly with the default toolkit, but when he tries to add ac_add_options --enable-default-toolkit=gtk2 to his .mozconfig file he gets an
error. vin is asking for help on how to solve the
error. announcements svg build dependency on cairo gfx on 11/22 november 21st: t rowley announced that: he will be landing his patch that starts the process of switching svg over to thebes (bug 354866). if you build dependencies with non-default toolkit or on a non tier-1 platform you'll need to disable svg in your mozconfig. gecko 1.9 intl re...
The HTML5 input types - Learn web development
imes build their own custom form controls. we cover this in an advanced tutorial: how to build custom form widgets. e-mail address field this type of field is set using the value email for the type attribute: <input type="email" id="email" name="email"> when this type is used, the user is required to type a valid email address into the field. any other content causes the browser to display an
error when the form is submitted. you can see this in action in the below screenshot. you can also use the multiple attribute in combination with the email input type to allow several email addresses to be entered in the same input (separated by commas): <input type="email" id="email" name="email" multiple> on some devices — notably, touch devices with dynamic keyboards like smart phones — a d...
...yboard screenshot below for an example: note: you can find examples of the basic text input types at basic input examples (see the source code also). this is another good reason for using these newer input types — improving the user experience for users of these devices. client-side validation as you can see above, email, along with other newer input types, provides built-in client-side
error validation — performed by the browser before the data gets sent to the server. it is a helpful aid to guide users to fill out a form accurately, and it can save time — it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server. but it should not be considered an exhaustive security measure! your apps should always perform securit...
...uld happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. note that a@b is a valid email address according to the default provided constraints. this is because the email input type allows intranet email addresses by default. to implement different validation behavior, you can use the pattern attribute, and you can also custom the
error messages; we'll talk how to use these features in the client-side form validation article later on. note: if the data entered is not an email address, the :invalid pseudo-class will match, and the validitystate.typemismatch property will return true. search field search fields are intended to be used to create search boxes on pages and apps. this type of field is set by using the value searc...
... include letters, etc.). as we mentioned earlier, the pattern attribute can be used to enforce constraints, which you'll learn about in client-side form validation. url field a special type of field for entering urls can be created using the value url for the type attribute: <input type="url" id="url" name="url"> it adds special validation constraints to the field. the browser will report an
error if no protocol (such as http:) is entered, or if the url is otherwise malformed. on devices with dynamic keyboards, the default keyboard will often display some or all of the colon, period, and forward slash as default keys. see below for an example (taken on firefox for android): note: just because the url is well-formed doesn't necessarily mean that it refers to a location that actually exi...
Introduction to events - Learn web development
ent loaded in the current tab, or the entire browser window. there are many different types of events that can occur. for example: the user selects a certain element or hovers the cursor over a certain element. the user chooses a key on the keyboard. the user resizes or closes the browser window. a web page finishes loading. a form is submitted. a video is played, paused, or finishes. an
error occurs. you can gather from this (and from glancing at the mdn event reference) that there are a lot of events that can be responded to. each available event has an event handler, which is a block of code (usually a javascript function that you as a programmer create) that runs when the event fires. when such a block of code is defined to run in response to an event, we say we are registering ...
....onclick to the following different values in turn, and observing the results in the example: btn.onfocus and btn.onblur — the color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button. these are often used to display information about filling in form fields when they are focused, or displaying an
error message if a form field is filled with an incorrect value. btn.ondblclick — the color changes only when the button is double-clicked. window.onkeypress, window.onkeydown, window.onkeyup — the color changes when a key is pressed on the keyboard. the keypress event refers to a general press (button down and then up), while keydown and keyup refer to just the key down and key up parts of the k...
...some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. let's look at a simple example. first, a simple html form that requires you to enter your first and last name: <form> <div> <label for="fname">first nam...
...ubmit"> </div> </form> <p></p> div { margin-bottom: 10px; } now some javascript — here we implement a very simple check inside an onsubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. ...
Fetching data from the server - Learn web development
d idea to get into the habit of setting this in case you want to fetch other types of data in the future. add this next: request.responsetype = 'text'; fetching a resource from the network is an asynchronous operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an
error will be thrown. xhr allows you to handle this using its onload event handler — this is run when the load event fires (when the response has returned). when this has occurred, the response data will be available in the response property of the xhr request object. add the following below your last addition. you'll see that inside the onload event handler we are setting the textcontent of the p...
...as we want to return our response as structured json data, not plain text. next, we chain another .then() onto the end of our first one, the success function that contains the json returned from the response.json() promise. we set this to be the value of the products variable, then run initialize(products), which starts the process of displaying all the products in the user interface. ...
... json returned from the response.json() promise. we set this to be the value of the products variable, then run initialize(products), which starts the process of displaying all the products in the user interface. to handle
errors, we chain a .catch() block onto the end of the chain. this runs if the promise fails for some reason. inside it, we include a function that is passed as a parameter, an
error object. this
error object can be used to report the nature of the
error that has occurred, in this case we do it with a simple console.log(). however, a complete website would handle this
error more gracefully by displaying a message on the user's screen and perhaps offering options to remedy the situation, but we don't need anything more than a simple console.log(). you can test the fail case ...
... we'd like you to try converting the fetch version of the app to use xhr as a useful bit of practice. take a copy of the zip file, and try modifying the javascript as appropriate. some helpful hints: you might find the xmlhttprequest reference material useful. you will basically need to use the same pattern as you saw earlier in the xhr-basic.html example. you will, however, need to add the
error handling we showed you in the fetch version of the can store: the response is found in request.response after the load event has fired, not in a promise then(). about the best equivalent to fetch's response.ok in xhr is to check whether request.status is equal to 200, or if request.readystate is equal to 4. the properties for getting the status and status message are the same, but the...
Solve common problems in your JavaScript code - Learn web development
elementsbyclassname() getelementbyclassname() getelementbyid() getelementsbyid() semi-colon position you need to make sure you don't place any semi-colons incorrectly. for example: correct wrong elem.style.color = 'red'; elem.style.color = 'red;' functions there are a number of things that can go wrong with functions. one of the most common
errors is to declare the function, but not call it anywhere. for example: function myfunction() { alert('this is my function.'); }; this code won't do anything unless you call it with the following statement: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the vari...
...side a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function. running code after a return statement remember also that when you return from a function, the javascript interpreter exits the function — no code after the return statement will run. in fact, some browsers (like firefox) will give you an
error message in the developer console if you have code after a return statement. firefox gives you "unreachable code after return statement". object notation versus normal assignment when you assign something normally in javascript, you use a single equals sign, e.g.: const mynumber = 0; with objects, however, you need to take care to use the correct syntax. the object must be surrounded by curly ...
... making decisions in code how do you execute different bl...
...y items, or join array items into a string? debugging javascript what are the basic types of
error? what are browser developer tools, and how do you access them? how do you log a value to the javascript console? how do you use breakpoints and other javascript debugging features? for more information on javascript debugging, see handling common javascript problems. also, see other common
errors for a description of common
errors. making decisions in code how do you execute different blocks of code, depending on a variable's value or other condition? how do you use if ...else statements? how do you nest one decision block inside another? how do you use and, or, and not operators in javascript? how do you conveniently handle a large number of choices for one condition? how do yo...
Old Thunderbird build
lash, is intentional to clarify you are in the mozillabuild command prompt per windows build prerequisite). note: parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). on linux, this can manifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of os access denied
errors, where access is denied not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it close to the root of your machine and re-building.
...ude\10.0.nnnnn.0\shared respectively, where nnnnn is the highest number present on the system. check to make sure that the path in which you placed the source code has no spaces, and is not too long. searched the bug database for issues relating to your problem (e.g., platform-specific issues). ...
...clobbering (see below) will also remove those files. try with a clean obj-dir. ...
...clobbering (see below) will also remove those files. try with a clean obj-dir. ...
Simple Thunderbird build
lash, is intentional to clarify you are in the mozillabuild command prompt per windows build prerequisite). note: parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). on linux, this can manifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of os access denied
errors, where access is denied not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it closer to the root of your machine and re-building...
... code from a branch, just replace the url to the repository in the hg clone instruction). check to make sure that the path in which you placed the source code has no spaces, and is not too long. searched the bug database for issues relating to your problem (e.g., platform-specific issues). ...
...clobbering (see below) will also remove those files. try with a clean obj-dir. ...
...clobbering (see below) will also remove those files. try with a clean obj-dir. ...
mach
rived from there). mach was committed on 2012-sep-26. mach also requires python 2.7. mach itself is python 3 compliant, but modules used by mach likely are not python 3 compliant - so stick to python 2.7. running from the root of the source tree checkout, you should just be able to type: $ ./mach if all is well, you should see a help message. of course, in a random dir you just get a cryptic
error message to improve the experience. for full help: $ ./mach help try building the tree: $ ./mach build if you get
error messages, make sure that you have all of the build requisites for your system. if it works, you can look at compiler warnings: $ ./mach warnings-list try running the program: $ ./mach run try running your program in a debugger: $ ./mach run --debug try running some ...
...e "mach" may not necessarily work like a charm for everyone. why even bother with a competing build system in arch when octopi does what you want and even has a gui? those makepkg scripts named pkgbuild are (typically) simple bash scripts that are easy to maintain and modify. python based mach tends to involve more complexity and potential for breakage. another possible reason: mach gives you an
error, while running, say bootstrap.py directly (that is to type in a bash shell: python2 ./bootstrap.py enter-key ) in an otherwise empty ..../subdir/ may work for you! less may be better! and mach's
error messages tend to be cryptic and not utterly helpful. that above bootstrap.py will download and setup everything so you can build a mozilla app such as firefox etcetera, so it is a nice starting po...
...t. why should i use mach? you should use mach because it provides a better and more unified developer experience for working on mozilla projects. if you don't use mach, you have to find another solution for the following problems: discovering what commands or make targets are available (mach exposes everything through mach help while inside "mozilla-central" , else you'll just get a cryptic
error message) making more sense out of command output (mach offers terminal colorization and structured logging) getting productive tools in the hands of others (mach "advertises" tools to people through mach help (unless it actually just gives you a cryptic
error message) - in the former case, people don't need to discover your tool from a blog post, wiki page, or word of mouth). so this 3rd point ...
...re there any known issues? yes, of course several! mach is still relatively young ("born" in 2012) and there are a number of bugs and numerous areas for improvement. some larger known issues include: mintty (alternative terminal emulator on windows) doesn't work. text encoding issues (especially on windows where latin-1 is not the default system encoding). failed commands spew lots of extra
error output, e.g. you will see a big mach
error message when all that happened was an invoked command returned a non-0 exit code - possibly expectedly so in mozilla! generally, mach is known to work pretty well without issues for most people and works terribly for others with even the "basics" being quite unsatisfactory. how do i report bugs? bugs against the mach core can be filed in bugzilla in ...
AddonManager
istcallback() a callback that is passed an array of addoninstalls void installlistcallback( in addoninstall installs[] ) parameters installs the array of addoninstalls passed back from the asynchronous request addoncallback() a callback that is passed a single addon void addoncallback( in addon addon ) parameters addon the addon passed back from the asynchronous request. if an
error occurred (such as an add-on not being found), null is passed back instead. addonlistcallback() a callback that is passed an array of addons void addonlistcallback( in addon addons[] ) parameters addons the array of addons passed back from the asynchronous request constants addoninstall states constant description state_available an install that is waiting to...
...dy to install. state_download_failed an install that failed to download. state_installing an install that is in the process of being installed. state_installed an install that has successfully been installed. state_install_failed an install that has failed to install. state_cancelled an install that has been canceled. addoninstall
errors constant description
error_network_failure a network
error occurred.
error_incorrect_hash the downloaded file did not match the expected hash.
error_corrupt_file the file appears to be corrupt.
error_file_access there was an
error accessing the filesystem.
error_signedstate_required the addon must be signed and isn't. ...
...en_new_app_installed an update check performed after a new version of the application has been installed. update_when_periodic_update an update check performed automatically in the background. update_when_addon_installed an update check performed when a new add-on has been installed. update status values constant description update_status_no_
error no
error was encountered. update_status_timeout the update check timed out. update_status_download_
error there was an
error while downloading the update information. update_status_parse_
error the update information was malformed in some way. update_status_unknown_format the update was not in any known format. update_status_security_er...
... auto update values constant description autoupdate_disable indicates that the add-on should not update automatically. autoupdate_default indicates that the add-on should update automatically only if that's the global default. ...
Log.jsm
change // the log level of sets of loggers under some common root let log = log.repository.getlogger("myextension.myclass"); log.level = log.level.debug; // a console appender logs to the browser console. log.addappender(new log.consoleappender(new log.basicformatter())); // a dump appender logs to stdout. log.addappender(new log.dumpappender(new log.basicformatter())); // log some messages log.
error("oh noes!! something bad happened!"); log.debug("details about bad thing only useful during debugging", {someinfo: "nothing"}); log.warn("here is an
error", new
error("ouch")); logger levels fatal severe
errors that cause premature termination. expect these to be immediately visible on a status console.
error other runtime
errors or unexpected conditions. expect these...
...expect these to be immediately visible on a status console. info interesting runtime events (startup/shutdown). expect these to be immediately visible on a console, so be conservative and keep to a minimum. ...
...th: 2 member fields variable type description level object contains the following fields: field name value all 0 config 30 debug 20 desc { 0: "all", 10: "trace", 20: "debug", 30: "config", 40: "info", 50: "warn", 60: "
error", 70: "fatal" }
error 30 fatal 70 info 40 numbers { "all": 0, "trace": 10, "debug": 20, "config": 30, "info": 40, "warn": 50, "
error": 60, "fatal": 70 } trace 10 warn 50 repository loggerrepository...
... info 40 numbers { "all": 0, "trace": 10, "debug": 20, "config": 30, "info": 40, "warn": 50, "
error": 60, "fatal": 70 } trace 10 warn 50 repository loggerrepository logger methods void fatal(string text, [optional] object params); void
error(string text, [optional] object params); void warn(string text, [optional] object params); void info(string text, [optional] object params); void config(string text, [optional] object params); void debug(string text, [optional] object params); void trace(string text, [optional] object params); ...
Deferred
already been resolved, 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 deferr...
...is used to resolve the promise * if the value is a promise then the associated promise assumes the state * of promise passed as value. */ this.resolve = null; /* a method to reject the assocaited promise with the value passed. * if the promise is already settled it does nothing. * * @param {anything} reason: the reason for the rejection of the promise. * generally its an
error object. if however a promise is passed, then the promise * itself will be the reason for rejection no matter the state of the promise. */ this.reject = null; /* a newly created promise object. * initially in pending state. */ this.promise = new promise(function(resolve, reject) { this.resolve = resolve; this.reject = reject; }.bind(this)); object.freeze(this); } } a...
... promise(function(resolve, reject) { this.resolve = resolve; this.reject = reject; }.bind(this)); object.freeze(this); } } and use this function as would promise.defer: function funcwithdefer() { var deferred = new deferred(); var promise = deferred.promise; promise.then( function(aval) { console.log('fullfilled - ', aval); }, function(areason) { console.
error('rejected - areason:', areason) } ); //deferred.resolve('aval of resolved'); deferred.reject('reject val'); return promise; } var promise_funcwithdefer = funcwithdefer(); promise_funcwithdefer.then( function(aval) { console.log('fullfilled - promise_funcwithdefer - ', aval); }, function(areason) { var refobj = {name:'promise_funcwithdefer', areason:areason}; conso...
...ejected - areason:', areason) } ); //deferred.resolve('aval of resolved'); deferred.reject('reject val'); return promise; } var promise_funcwithdefer = funcwithdefer(); promise_funcwithdefer.then( function(aval) { console.log('fullfilled - promise_funcwithdefer - ', aval); }, function(areason) { var refobj = {name:'promise_funcwithdefer', areason:areason}; console.
error('rejected - promise_funcwithdefer - ', refobj); } ).catch( function(acatch) { console.
error('caught - promise_funcwithdefer - ', acatch); throw acatch; } ); ...
Task.jsm
e spawn( atask ); parameters atask this parameter accepts different data types: if you specify a generator function, it is called with no arguments to retrieve the associated iterator. the generator function is a task, that is can yield promise objects to wait upon. the promise returned by the task either fulfills with the returned value if generator returns or rejects with the thrown
error if the generator throws. if you specify the iterator returned by a generator function you called, the generator function is also executed as a task. this allows you to call the function with arguments. the promise returned by the task either fulfills with the returned value if generator returns or rejects with the thrown
error if the generator throws. if you specify a function that is not a g...
...if the reason for the exception is that the file doesn't exist, this is treated as an expected condition, and the task will complete succesfully. an...
... ...
....then(null, components.utils.report
error); in this example, if the promise returned by os.file.stat is rejected, an exception is thrown inside the task. if the reason for the exception is that the file doesn't exist, this is treated as an expected condition, and the task will complete succesfully. any other unhandled exception that is thrown inside the task is reported by components.utils.report
error. ...
L10n Checks
json output in all modes you can tell l10n checks to present the o...
...json output in all modes you can tell l10n checks to present the output as json by...
...json output in all modes you can tell l10n checks to present the output as json by setting the -j parameter to full_json, e.g...
...json output in all modes you can tell l10n checks to present the output as json by setting the -j parameter to full_json, e.g.: check-l10n-completeness -j full_json suite/locales/l10n.ini ../l10n/ de json output requires ...
Mozilla Web Developer FAQ
paragraph markup is called for but the default margins are unwanted, zero margins can be suggested using css. my style sheet doesn’t work! why? here’s the check list: does the html document validate? styling misnested markup may cause strange effects. the <link> and <style> elements should be inside the <head> element. does the css style sheet pass the syntax check? the css
error handling rules require erroneous parts to be ignored rather than fixed by guessing. lengths other than zero should be followed by a proper unit without a space between the number and the unit (eg. 1.2em). the character to use between the property name and the value is the colon—not the equal sign. html markup, such as <style>, does not belong in .css files. font-face is not a rea...
...ut a space between the number and the unit (eg. 1.2em). the character to use between the property name and the value is the colon—not the equal sign. html markup, such as <style>, does not belong in .css files. font-face is not a real css property. the property is font-family and @font-face is an at-rule. if @import is used, it should be the first thing in a css file. css parsing
errors are reported to the javascript console. is the server sending the proper content-type header for css style sheets? the correct type is text/css. in the standards mode and the almost standards mode only style sheets with the correct type are applied. you can see the http headers sent by the server by using the livehttpheaders extension or by using the web sniffer. class na...
...isms that ensure well-formed output include serializing from a document tree object model (eg. dom) and xslt transformations that do not disable output escaping. when xhtml output has been retrofitted to a content management system that was not designed for xml from the ground up, the system usually ends up discriminating gecko users by serving tag soup labeled as xml to gecko (leading to a parse
error) and serving the same soup labeled as text/html to ie (not leading to a parse
error). how is the treatment of application/xhtml+xml documents different from the treatment of text/html documents? an xml parser (expat) is used instead of the tag soup parser. most well-formedness constraints are enforced. despite common allegations to the contrary, the document is not checked for validity.
...re only supported if the document references a public identifier for which there is a mapping in mozilla’s pseudo-dtd catalog and the document has not been declared standalone. in older versions of mozilla as well as in old mozilla-based products, there is no pseudo-dtd catalog and the use of externally defined character entities (other than the five pre-defined ones) leads to an xml parsing
error. there are also other xhtml user agents that do not support externally defined character entities (other than the five pre-defined ones). since non-validating xml processors are not required to support externally defined character entities (other than the five pre-defined ones), the use of externally defined character entities (other than the five pre-defined ones) is inherently unsafe in xml doc...
NSS CERTVerify Log
certverifylog all the nss verify functions except, the *verifynow() functions, take a parameter called 'certverifylog'. if you supply the log parameter, nss will continue chain validation after each
error . the log tells you what the problem was with the chain and what certificate in the chain failed. to create a log: #include "secport.h" #include "certt.h" certverifylog *log; arena = port_newarena(512); log = port_arenaznew(arena,log); log->arena = arena; you can then pass this log into your favorite cert verify function. on return: log->count is the number of entries. log->head is the first entry; log->tail is the last entry. each entry is a certverifylognode. defined in certt.h: /* * this structure is used to keep a log of
errors when verifying * a cert chain. this allows mu...
...512); log = port_arenaznew(arena,log); log->arena = arena; you can then pass this log into your favorite cert verify function. on return: log->count is the number of entries. log->head is the first entry; log->tail is the last entry. each entry is a certverifylognode. defined in certt.h: /* * this structure is used to keep a log of
errors when verifying * a cert chain. this allows multiple
errors to be reported all at * once. ...
...tion. on return: log->count is the number of entries. log->head is the first entry; log->tail is the last entry. each entry is a certverifylognode. defined in certt.h: /* * this structure is used to keep a log of
errors when verifying * a cert chain. this allows multiple
errors to be reported all at * once. ...
... log->count is the number of entries. log->head is the first entry; log->tail is the last entry. each entry is a certverifylognode. defined in certt.h: /* * this structure is used to keep a log of
errors when verifying * a cert chain. this allows multiple
errors to be reported all at * once. */ struct certverifylognodestr { certcertificate *cert; /* what cert had the
error */ long
error; /* what
error was it? */ unsigned int depth; /* how far up the chain are we */ void *arg; /*
error specific argument */ struct certverifylognodestr *next; /* next in the list */ struct certverifylognodestr *prev; /* next in the list */ }; the list is a doubly linked null terminated list sorted from low to high based on depth into the cert chain. ...
NSS 3.45 release notes
p_set_long and mp_set_ulong bug 1515011 - fix a mistake with chacha20-poly1305 test code where tags could be faked. ...
...hat might have copied the unit test code verbatim bug 1550022 - ensure nssutil3 gets built on android bug 1528174 - chacha20poly1305 should no longer modify output length on failure bug 1549382 - don't leak in pkcs#11 modules if c_getslotinfo() returns
error bug 1551041 - fix builds using gcc < 4.3 on big-endian architectures bug 1554659 - add versioning to openbsd builds to fix link time
errors using nss bug 1553443 - send session ticket only after handshake is marked as finished bug 1550708 - fix gyp scripts on solaris sparc so that libfreebl_64fpu_3.so builds bug 1554336 - optimize away unneeded loop in mpi.c bug 1559906 - fipstest: use ckm_tls12_master_key_derive instead of vendor specific mechanism bug 1558126 - tls_aes_256_gcm_sha384 should be marked as fips compatible bug...
...a program linked with older nss 3.x share...
...a program linked with older nss 3.x shared librarie...
NSS Sample Code sample2
i, result_len, tmp1_outlen, tmp2_outlen; /* initialize nss * if your application code has already initialized nss, you can skip it * here. * this code uses the simplest of the init functions, which does not * require a nss database to exist */ rv = nss_nodb_init("."); if (rv != secsuccess) { fprintf(stderr, "nss initialization failed (err %d)\n", pr_get
error()); goto out; } /* choose mechanism: ckm_des_cbc_pad, ckm_des3_ecb, ckm_des3_cbc..... * note that some mechanisms (*_pad) imply the padding is handled for you * by nss. if you choose something else, then data padding is the * application's responsibility */ ciphermech = ckm_des_cbc_pad; slot = pk11_getbestslot(ciphermech, null); /* slot = pk11_getinternalkeyslot(); is a...
...lity */ ciphermech = ckm_des_cbc_pad; slot = pk11_getbestslot(ciphermech, null); /* slot = pk11_getinternalkeyslot(); is a simpler alternative but in * theory, it *may not* return the optimal slot for the operation. for * des ops, internal slot is typically the best slot */ if (slot == null) { fprintf(stderr, "unable to find security device (err %d)\n", pr_get
error()); goto out; } /* nss passes blobs around as secitems. these contain a pointer to * data and a length. turn the raw key into a secitem. */ keyitem.type = sibuffer; keyitem.data = gkey; keyitem.len = sizeof(gkey); /* turn the raw key into a key object. we use pk11_originunwrap * to indicate the key was unwrapped - which is what should be done * normally anyway - using r...
...key object. we use pk11_originunwrap * to indicate the key was unwrapped - which is what should be done * normally anyway - using raw keys isn't a good idea */ symkey = pk11_importsymkey(slot, ciphermech, pk11_originunwrap, cka_encrypt, &keyitem, null); if (symkey == null) { fprintf(stderr, "failure to import key into nss (err %d)\n", pr_get
error()); goto out; } /* set up the pkcs11 encryption paramters. * when not using cbc mode, ivitem.data and ivitem.len can be 0, or you * can simply pass null for the iv parameter in pk11_paramfromiv func */ ivitem.type = sibuffer; ivitem.data = giv; ivitem.len = sizeof(giv); secparam = pk11_paramfromiv(ciphermech, &ivitem); if (secparam == null) { fprintf(stderr, "fai...
...aramters. ...
NSS Sample Code sample5
*slot = null; /* initialize nss * you need to explicitly authenticate to the internal token if you use * nss_init insteadf of nss_nodb_init * invoke this after getting the internal token handle * pk11_authenticate(slot, pr_false, null); */ rv = nss_nodb_init("."); if (rv != secsuccess) { fprintf(stderr, "nss initialization failed (err %d)\n", pr_get
error()); goto cleanup; } /* get internal slot */ slot = pk11_getinternalkeyslot(); if (slot == null) { fprintf(stderr, "couldn't find slot (err %d)\n", pr_get
error()); goto cleanup; } rv = atob_convertasciitoitem(&der, pubkstr); if (rv!= secsuccess) { fprintf(stderr, "atob_convertasciitoitem failed %d\n", pr_get
error()); goto cleanup; } spki = seckey_decoded...
...} rv = atob_convertasciitoitem(&der, pubkstr); if (rv!= secsuccess) { fprintf(stderr, "atob_convertasciitoitem failed %d\n", pr_get
error()); goto cleanup; } spki = seckey_decodedersubjectpublickeyinfo(&der); secitem_freeitem(&der, pr_false); pubkey = seckey_extractpublickey(spki); if (pubkey == null) { fprintf(stderr, "couldn't extract public key (err %d)\n", pr_get
error()); goto cleanup; } modulus_len = seckey_publickeystrength(pubkey); fprintf(stderr, "public key modulus %d bytes\n", modulus_len); buf1 = (char *)malloc(modulus_len); buf2 = (char *)malloc(modulus_len); /* initialize buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= (i %26) + 'a'; } buf1[modulus_len-1] = '\0'; fprintf(stderr, "buffer being encrypted = \n%s\n", buf1); ...
...* initialize buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= (i %26) + 'a'; } buf1[modulus_len-1] = '\0'; fprintf(stderr, "buffer being encrypted = \n%s\n", buf1); /* encrypt buf1, result will be in buf2 */ rv = pk11_pubencryptraw(pubkey, buf2, buf1, modulus_len, null); if (rv != secsuccess) { fprintf(stderr, "encrypt with public key failed (err %d)\n", pr_get
error()); goto cleanup; } nickname.type = sibuffer; nickname.data = "pvtkeynickname"; nickname.len = strlen("pvtkeynickname"); rv = atob_convertasciitoitem(&der, pvtkstr); if (rv!= secsuccess) { fprintf(stderr, "atob_convertasciitoitem failed %d\n", pr_get
error()); goto cleanup; } /* ku_all includes a lot of different key usages, ku_data_encipherment * is enough for j...
...g (4th) can be null for rsa key - i think it is even * ignored */ pk11_importderprivatekeyinfoandreturnkey(slot, &der, null, null, pr_false, pr_true, ku_all, &pvtkey, null); secitem_freeitem(&der, pr_false); if (pvtkey == null) { fprintf(stderr, "couldn't extract private key (err %d)\n", pr_get
error()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } /* decrypt buf2, result will be in buf1 */ rv = pk11_pubdecryptraw(pvtkey, buf1, &outlen, modulus_len, buf2, modulus_len); if (rv != secsuccess) { fprintf(stderr, "decrypt with private key failed (err %d)\n", pr_get
error()); goto cleanup; ...
NSS Sample Code sample6
{ secstatus rv; /* initialize nss */ pk11_setpasswordfunc(passwdcb); /* the nss db must be initialized read-write since we'll be creating * keys in it. once keys are generated, it can be opened without read-write * subsequently (nss_init). */ rv = nss_initreadwrite("."); if (rv != secsuccess) { fprintf(stderr, "nss initialization failed (err %d)\n", pr_get
error()); exit(1); } /* generate a key with id 1. should succeed on first run on a fresh db, * should fail on successive runs because key with that id already exists */ genkey(1); /* generate a key with id 2. should succeed on first run on a fresh db, * should fail on successive runs because key with that id already exists */ genkey(2); /* generate a key with id 1 - this will f...
...id * already exists */ genkey(1); } void genkey(int id) { pk11slotinfo* slot = null; pk11symkey* key = null; secitem keyiditem; int keyid[1]; ck_mechanism_type ciphermech; /* using ckm_aes_cbc_pad mechanism for example */ ciphermech = ckm_aes_cbc_pad; slot = pk11_getinternalkeyslot(); /* slot = pk11_getbestslot(ciphermech, null); didn't work. *
error code: token is read-only. ?? */ if (slot == null) { fprintf(stderr, "unable to find security device (err %d)\n", pr_get
error()); return; } keyid[0] = id; keyiditem.type = sibuffer; keyiditem.data = (void *)keyid; keyiditem.len = sizeof(keyid[0]); /* note: keysize must be 0 for fixed key-length algorithms like des. * since we're using aes in this e...
...note: keysize must be 0 for fixed key-length algorithms like des. ...
...return; } fprintf(stderr, "key length of generated key is %d\n", pk11_getkeylength(key)); fprintf(stderr, "mechanism of key is %d (asked for %d)\n", pk11_getmechanism(key), ciphermech); pk11_freesymkey(key); key = pk11_findfixedkey(slot, ciphermech, &keyiditem, 0); if (key == null) { fprintf(stderr, "pk11_findfixedkey failed (err %d)\n", pr_get
error()); pk11_freeslot(slot); return; } fprintf(stderr, "found key!\n"); fprintf(stderr, "key length of generated key is %d\n", pk11_getkeylength(key)); fprintf(stderr, "mechanism of key is %d (asked for %d)\n", pk11_getmechanism(key), ciphermech); pk11_freesymkey(key); pk11_freeslot(slot); } char *passwdcb(pk11slotinfo *info, prbool retry, void *arg) { if...
NSPR functions
ternally as the porting layer. however, a small number of nspr functions are required for using the certificate verification and ssl functions in nss. these nspr functions are listed in this section. nspr initialization and shutdown nspr is automatically initialized by the first nspr function called by the application. call pr_cleanup to shut down nspr and clean up its resources. ...
... number of nspr functions are required for using the certificate verification and ssl functions in nss. these nspr functions are listed in this section. nspr initialization and shutdown nspr is automatically initialized by the first nspr function called by the application. call pr_cleanup to shut down nspr and clean up its resources. pr_cleanup
error reporting nss uses nspr's thread-specific
error code to report
errors. ...
...r using the certificate verification and ssl functions in nss. these nspr functions are listed in this section. nspr initialization and shutdown nspr is automatically initialized by the first nspr function called by the application. call pr_cleanup to shut down nspr and clean up its resources. pr_cleanup
error reporting nss uses nspr's thread-specific
error code to report
errors. call pr_get
error to get the
error code of the last failed nss or nspr function. ...
...ons are listed in this section. nspr initialization and shutdown nspr is automatically initialized by the first nspr function called by the application. call pr_cleanup to shut down nspr and clean up its resources. pr_cleanup
error reporting nss uses nspr's thread-specific
error code to report
errors. call pr_get
error to get the
error code of the last failed nss or nspr function. call pr_set
error to set the
error code, which can be retrieved with pr_get
error later. the nss functions port_get
error and port_set
error are simply wrappers of pr_get
error and pr_set
error. pr_get
error pr_set
error calendar time nss certificate verification functions take a prtime parameter that specifies the time instant at which the validity of the certificate should verified. the nspr function pr_now returns ...
SpiderMonkey Build Documentation
uild_opt.obj /bin/sh ../configure.in # use "mozmake" on windows make a few notes about this: the most common build problems are dependency problems. see the build prerequisites page for your platform. spidermonkey does not support building in your source directory. you must configure and build in a separate build directory, as shown above. ...
...t this: the most common build problems are dependency problems. see the build prerequisites page for your platform. spidermonkey does not support building in your source directory. you must configure and build in a separate build directory, as shown above. note: if you are on mac and getting an
error similar to "checking whether the c compiler (gcc-4.2 ) works... ...
...ac and getting an
error similar to "checking whether the c compiler (gcc-4.2 ) works... no configure:
error: installation or configuration problem: c compiler cannot create executables." you can try configuring like so: cc=clang cxx=clang++ ../configure it is also possible that baldrdash may fail to compile with /usr/local/cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal
error: 'inttypes.h' file not found /usr/local/cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal
error: 'inttypes.h' file not found, err: true this is because, starting from mohave, headers are no longer installed in /usr/include. refer the release notes under command line tools -> new features the release notes also states that this compatibility package will no longer be provided i...
...you can override this by passing options to the configure script: what it is where it gets put configure option executables, shell scripts /usr/local/bin --bindir ...
GC Rooting Guide
dle<jsobject*> js::mutablehandleobject js::mutablehandle<jsstring*> js::mutablehandlestring js::mutablehandle<jsscript*> js::mutablehandlescript js::mutablehandle<jsid> js::mutablehandleid js::mutablehandle<t> should be used for all out-parameters, for example instead of: bool maybegetvalue(jscontext *cx, js::value* valueout) { // ... ...
...:mutablehandle<jsstring*> js::mutablehandlestring js::mutablehandle<jsscript*> js::mutablehandlescript js::mutablehandle<jsid> js::mutablehandleid js::mutablehandle<t> should be used for all out-parameters, for example instead of: bool maybegetvalue(jscontext *cx, js::value* valueout) { // ... ...
..., for example instead of: bool maybegetvalue(jscontext *cx, js::value* valueout) { // ... if (!was
error) *valueout = resultvalue; return was
error; } void otherfunction(jscontext *cx) { js::value value; bool success = maybegetvalue(cx, &value); // ... } you should write: bool maybegetvalue(jscontext *cx, js::mutablehandlevalue valueout) { // ... if (!was
error) valueout.set(resultvalue); return was
error; } void otherfunction(jscontext *cx) { js::rootedvalue value(cx); bool success = maybegetvalue(cx, &value); // ... } return values it's ok to return raw pointers! these do not need to be wrapped in any of rooting classes, but they should be immediately used to initialize a js::rooted<t> if there is any code that could gc befo...
...very difficult to notice manually, and will probably be caught by the static rooting hazard analysis. there are two different approaches to resolving this; use whichever better fits your situation: void somefunction(jscontext* cx, js::mutablehandleobject obj) { eventlogger(cx); ...code... obj.set(foo()); } (note that the above should probably check the return value and propagate an
error on null), or: jsobject* somefunction(jscontext* cx) { js::rooted<jsobject*> obj(cx, foo()); { // make a scope to force the destructor to run before obj is unwrapped. eventlogger(cx); ...code... } return obj; } autorooters gc thing pointers that appear as part of a stack-allocated aggregates (array, structure, class, union) should use js::rooted<t> when possible...
Hacking Tips
set dot-bin <path>, set pngviewer-bin <path>) within gdb. enabling gdb instrumentation may require launching a js shell executable that shares a directory with a file name "js-gdb.py". if js/src/js does not provide the "iongraph" command, try js/src/shell/js. gdb may complain that ~/.gdbinit requires modification to authorize user scripts, and if so will print out directions. ...
...be aware that functions which are usually dumping some output will do it in the shell where valgrind is started and not in the shell where gdb is started. thus functions such as js::dumpbacktrace, when called from gdb, will print their output in the shell containing valgrind. ...
... use 'run z' where z is the mark in the log for test-start. for example in '[rr 28496 607198]reftest test-start | file:///home/bgirard/mozilla-central/tree/image/test/reftest/bmp/bmpsuite/b/wrapper.html?badpalettesize.bmp' z would be 607198. ...
...we can allocate 2 cores by doing 0-1 instead of 0. $ cgset -r cpuset.cpus=0 /benchmarks $ cgset -r cpuset.cpus=0 /benchmarks/mask $ cgset -r cpuset.cpus=0 /benchmarks/negate-mask then we restrict programs of these groups to the first memory node. most of the time you will only have one, otherwise you should read what is the best setting to set here. if this is not set, you will have some
error when you will try to write a pid in /sys/fs/cgroup/cpuset/benchmarks/mask/tasks while running cgexec. $ cgset -r cpuset.mems=0 /benchmarks $ cgset -r cpuset.mems=0 /benchmarks/mask $ cgset -r cpuset.mems=0 /benchmarks/negate-mask then we limit the performance of the cpu, as a proportion such as the result approximately correspond to what you might have if you were running on a phone. for...
SpiderMonkey Internals
r consists of: a random-logic rather than table-driven lexical scanner, a recursive-descent parser that produces an ast, and a tree-walking code generator. semantic and lexical feedback are used to disambiguate hard cases such as missing semicolons, assignable expressions ("lvalues" in c parlance), and whether / is the division symbol or the start of a regular expression. the compiler attempts no
error recovery; it bails out on the first
error. the emitter does some constant folding and a few codegen optimizations; about the fanciest thing it does is to attach source notes to the script for the decompiler's benefit. the decompiler implements function.tosource(), which reconstructs a function's source code. it translates postfix bytecode into infix source by consulting a separate byte-sized cod...
...as members of the root gc set for exact gc. standard library the methods for arrays, 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. ...
...d library the methods for arrays, 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_report
error or one of its variants, or js_setpendingexception, and returning js_false or null. public apis the public c/c++ inter...
...msg the "js shell", a simple interpreter program that uses the js api and more than a few internal interfaces (some of these internal interfaces could be replaced by jsapi.h calls). the js program built from this source provides a test vehicle for evaluating scripts and calling functions, trying out new debugger primitives, etc. a look at the places where jsshell.msg is used in js.cpp shows how
error messages can be handled in jsapi applications. these messages can be localized at compile time by replacing the .msg file; or, with a little modification to the source, at run time. more information on the javascript shell. js.msg spidermonkey
error messages. jsarray.*, jsbool.*, jsdate.*, jsfun.*, jsmath.*, jsnum.*, jsstr.* these file pairs implement the standard classes and (where they exi...
Introduction to the JavaScript shell
d get instant gratification, which is handy for experimenting or testing new features. you can also pass in, on the command line, a javascript program file to run, in which case the program is run automatically. after following the build documentation and installing the built shell using make install, you can run the shell in interactive mode using the command: js [ if you get " symbol lookup
error: ./js: undefined symbol: pr_setcurrentthreadname" e.g. from a bash console when using a pre-compiled binary, try <path to your firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me] if you'd like to run the javascript code in the file foo.js, you can use this command: js foo.js to run foo.js then drop into the interactive shell, do this: js -f foo.js -i reference note: b...
...le options and built-in functions can change over time. command line options there are a number of command line options you can specify to control the shell. these are summarized below. be sure to use -h with your own jsshell to see if there is anything undocumented. -c, --compileonly tells the shell to compile the program but not run it. this is a convenient way to quickly check for syntax
errors in your program without actually running it. -e script runs the specified script, which is a literal string containing the code to execute. -f filename runs the javascript program specified by filename. -i enables interactive mode. (default if no filename is provided.) --no-ion disables the optimizing jit compiler. --no-baseline disables the baseline jit compiler. -p if the first lin...
...ecified names. note: for loading non-javascript files, use read(). options([option ...]) lets you set or get options. if you specified options on the command line, the results of calling options will indicate which options you requested. you can also pass in new options to set. the available options are: option name description strict strict mode is enabled. w
error warnings should be treated as
errors. atline when atline is enabled, comments of the form //@line num set the number of the following line to num. pc2line(function, [pc]) returns the line number of the javascript code that corresponds to the first line of the specified function. if you specify a program counter offset into the function, the line number of the line of code c...
... seals the specified object, or an object graph if deep is true. by sealing an object or object graph, you disable modification of those objects. sleep(dt) added in spidermonkey 1.8 only in js_threadsafe builds. sleep for dt seconds. fractions of a second are supported. returns true on success, false if the sleep was interrupted. stackquota([number]) get or set the script stack quota. throw
error() throws an
error from the js_report
error() function. note: this function is intended only for use when testing the javascript engine. trap([function, [pc,]] expression) sets a trap at the specific point in the javascript code. when the bytecode at the offset specified by pc in the function function is about to be executed, the expression is evaluated. this is a powerful debugging mechanism ...
JSDeletePropertyOp
ption jsdeletepropertyop callback is a hook that applications may install to be called at some point during property access. a jsdeletepropertyop may be installed on a jsclass to hook property deletes. if a jsdeletepropertyop does nothing and returns true, then property delete is unaffected. it proceeds as normal. ...
... 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. ...
...n 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 practice. if no
error occurred, but the deletion attempt wasn't allowed (perhaps because the property was non-configurable), set *succeeded to false and return true. this will cause delete obj[id] to evaluate to false in non-strict mode code, and to throw a type
error in strict mode code. ...
...when obj has no property named id. if an
error occurred, return false as per normal jsapi
error practice. if no
error occurred, but the deletion attempt wasn't allowed (perhaps because the property was non-configurable), set *succeeded to false and return true. this will cause delete obj[id] to evaluate to false in non-strict mode code, and to throw a type
error in strict mode code. if no
error occurred and the deletion wasn't disallowed (this is *not* the same as saying that a deletion actually occurred -- deleting a non-existent property, or an inherited property, is allowed -- it's just pointless), set *succeeded to true and return true. this hook is not called when the target property is jsprop_permanent and is an own property of the target object. an attempt to delete such a pro...
JS_GetInstancePrivate
> obj, const jsclass *clasp, jsval *argv); // obsolete since jsapi 32 name type description cx jscontext * a context. obj js::handle<jsobject*> the object for which to retrieve private data. clasp jsclass * class against which to test the object. args js::callargs * optional argument, used for
error reporting. added in spidermonkey 32 argv jsval * optional argument vector, used for
error reporting. obsolete since jsapi 32 this must be one of the following: an argv pointer created by the javascript engine and passed to a jsnative callback; js_argv(cx, vp) where vp is a pointer created by the engine and passed to a jsfastnative callback; or null. ...
...nter to the object's private data. otherwise it returns null. note that if obj is an instance of clasp, but there is no private data currently associated with the object, or the object cannot have private data, js_getinstanceprivate also returns null. ...
...not have private data, js_getinstanceprivate also returns null. if you pass a non-null argument vector, argv, to js_getinstanceprivate, and obj is not an instance of clasp, this function reports a class mismatch
error before returning null. in this case, js_getinstanceprivate tests whether or not there is a function name associated with the argument vector, and if there is, reports the name in an
error message using the js_report
error function. ...
... reports a class mismatch
error before returning null. in this case, js_getinstanceprivate tests whether or not there is a function name associated with the argument vector, and if there is, reports the name in an
error message using the js_report
error function. ...
JS_InitStandardClasses
object*> the global object to initialize. this object must be of a jsclass that has the jsclass_global_flags bits set. description js_initstandardclasses initializes the built-in javascript global properties. ...
...e global object to initialize. this object must be of a jsclass that has the jsclass_global_flags bits set. description js_initstandardclasses initializes the built-in javascript global properties. ...
...bits set. description js_initstandardclasses initializes the built-in javascript global properties. these include all the standard ecmascript global properties defined in ecma 262-3 §15.1: array, boolean, date, decodeuri, decodeuricomponent, encodeuri, encodeuricomponent,
error, eval, eval
error, function, infinity, isnan, isfinite, math, nan, number, object, parseint, parsefloat, range
error, reference
error, regexp, string, syntax
error, type
error, undefined, and uri
error as well as a few spidermonkey-specific globals, depending on compile-time options: escape, unescape, uneval, internal
error, script, xml, namespace, qname, file, generator, iterator, and stopiteration, as of spidermonkey 1.7. these global objects, functions, constructors, and constants are created as properties...
...erties of obj. as a side effect, js_initstandardclasses establishes obj as the global object for cx, if one is not already established. this means that scripts executed in cx will see the properties of obj as global variables. see js_setglobalobject for details. obj must be of a jsclass that has the jsclass_global_flags flag. js_initstandardclasses returns js_true on success, and js_false if an
error occurs. to initialize custom classes, use js_initclass. see also mxr id search for js_initstandardclasses ...
JS_ReportOutOfMemory
call js_reportallocationoverflow if an operation fails because it tries to use more memory (or more of some other resource) than the application is designed to handle. ...
... call js_reportallocationoverflow if an operation fails because it tries to use more memory (or more of some other resource) than the application is designed to handle. ...
...x); void js_reportallocationoverflow(jscontext *cx); // added in spidermonkey 1.8 name type description cx jscontext * the context in which to report the
error. description call js_reportoutofmemory to report that an operation failed because the system is out of memory. when the javascript engine tries to allocate memory and allocation fails, it reports an
error as though by calling this function. call js_reportallocationoverflow if an operation fails because it tries to use more memory (or more of some other resource) than the application is designed to handle. ...
...an
error as though by calling this function. call js_reportallocationoverflow if an operation fails because it tries to use more memory (or more of some other resource) than the application is designed to handle. when a script tries to grow an array beyond 230-1 elements, for example, or concatenate strings such that the result is more than 229-1 characters long, the javascript engine reports an
error as though by calling this function. see js_report
error and js_set
errorreporter for more information about
error handling in the jsapi. see also mxr id search for js_reportoutofmemory mxr id search for js_reportallocationoverflow bug 422348 ...
NS_ConvertASCIItoUTF16
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
NS_ConvertUTF16toUTF8
recase(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...@param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
NS_ConvertUTF8toUTF16
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
NS_LossyConvertUTF16toASCII
recase(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...@param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsAdoptingCString
recase(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...@param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsAdoptingString
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsAutoString
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsCAutoString
har*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ompare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsCString
recase(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...@param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsDependentCString
recase(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...@param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsDependentString
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsFixedCString
recase(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...@param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsFixedString
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsPromiseFlatCString
recase(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...@param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsPromiseFlatString
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsString
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsXPIDLCString
recase(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...@param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsXPIDLString
tfound parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...ichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...nt32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...lsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
jsdIStackFrame
opt_* values above, or'd together. last version set on this context. ...
...opt_* values above, or'd together. last version set on this context. scripts typically select this with the "language" attribute. see the version_* consts on jsdidebuggerservice. ...
... private data for this context, if it is an nsisupports, |null| otherwise. retrieve the underlying context wrapped by this jsdicontext. top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. this attribute is only valid for contexts which implement nsiscriptcontext. setting or getting this attribute on any other context will throw a ns_
error_no_interface exception. stack frame objects. these are only valid inside the jsdiexecutionhook which gave it to you. after you return from that handler the bottom frame, and 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 overv...
...tive frames. read only. thisvalue jsdivalue |this| object for this stack frame. read only. methods eval() evaluate arbitrary javascript in this stack frame. boolean eval( in astring bytes, in autf8string filename, in unsigned long line, out jsdivalue result ); parameters bytes script to be evaluated. filename filename to compile this script under. this is the filename you'll see in
error messages, and so on. line result return value ...
nsIAccessibleEditableText
or 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. ...
...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() inserts text at ...
...tart 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() sets the attribu...
... 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
ateinstance.) 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 object instance that is ...
...ateinstancebycontractid( 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 be returned. result...
...s 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 requested. aiid the ...
...ntractid() 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 examples using addboo...
nsICryptoHMAC
y 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 ); parameters aalgorithm ...
... 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 over. alen the...
...sed. 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 available will be used to ...
...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
cookies to be sent with this load even if normally they would not be. localaddress autf8string the local ip address to which the channel is bound, in the same format produced by pr_netaddrtostring(). 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. ...
...etermined yet, or any 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. ...
nsIInputStream
m 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 none. isnonblocking() boo...
...ong 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 this method. in some cont...
...ed 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 input stream using read().
...e calling thread for indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. example consume all data from an input stream using read(). nsresult consumestream(nsiinputstream* astream) { nsresult rv; uint32_t numread; char buf[512]; while (1) { rv = astream->read(buf, sizeof(buf), &numread); if (ns_failed(rv)) { printf("###
error reading stream: %x\n", rv); break; } if (numread == 0) break; // buf now contains numread bytes of data } return rv; } consume all data from an input stream using readsegments(). static ns_method appendsegment(nsiinputstream* astream, void* aclosure, const char* afromsegment, ...
nsIJumpListBuilder
n gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) jump lists are built and then applied. modifying an applied jump list is not permitted. callers should begin the creation of a new jump list using initlistbuild(), add sub lists using addlisttobuild(), then commit the jump list using commitlistbuild(). lists are built in real-time during the sequence of build calls, make sure to check for
errors on each individual step. the default number of allowed items in a jump list is ten. users can change the number through system preferences. user may also pin items to jump lists, which take up additional slots. applications do not have control over the number of items allowed in jump lists; excess items added are dropped by the system. item insertion priority is defined as first to last added. u...
...ommitlistbuild(); 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 application shortcut and ass...
...uired, 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 successfully. deleteactiveli...
...askbar. 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 that were removed b...
nsIMutableArray
earray unless they own the array. as above, it is legal to add null elements to the array. note also that null elements can be created as a side effect of insertelementat(). conversely, if insertelementat() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsiarray.queryelementat() will never return a null value. any of these methods may throw ns_
error_out_of_memory when the array must grow to complete the call, but the allocation fails. method overview void appendelement(in nsisupports element, in boolean weak); void clear(); void insertelementat(in nsisupports element, in unsigned long index, in boolean weak); void removeelementat(in unsigned long index); void replaceelementat(in nsisupports elemen...
...g 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( in nsisupports elem...
... 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 ); parameters index ...
...ced. 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 ...
nsIPushService
subscription.endpoint; subscription.getkey("p256dh"); subscription.getkey("auth"); } ); getsubscription() fetches an existing subscription. void getsubscription( in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback ); para...
... subscription.endpoint; subscription.getkey("p256dh"); subscription.getkey("auth"); } ); getsubscription() fetches an existing subscription. void getsubscription( in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback ); parameters ...
...rl, as passed to nsipushservice.subscribe(). principal the subscription nsiprincipal, as passed to nsipushservice.subscribe(). callback the callback to call with the fetched nsipushsubscription. example pushservice.getsubscription( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.report
error("
error fetching subscription: " + code); return; } // `subscription == null` if the `(scope, principal)` pair doesn't have a // push subscription. otherwise, it's an instance of `nsipushsubscription`. } ); unsubscribe() drops an existing push subscription. void unsubscribe( in domstring scope, in nsiprincipal principal, in nsiunsubscriberesultcallback callback ); p...
...que scope url, as passed to nsipushservice.subscribe(). principal the subscription nsiprincipal, as passed to nsipushservice.subscribe(). callback the callback to call when the nsipushsubscription is dropped. example pushservice.unsubscribe( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, ok) => { if (!components.issuccesscode(code)) { cu.report
error("
error unsubscribing: " + code); return; } // `ok === true` if the subscription was removed, or `false` if the // `(scope, principal)` pair didn't have a subscription. } ); receiving push messages subscriptions created from privileged code use xpcom observer notifications instead of service worker events. you can use the global nsiobserverservice to listen for these notific...
nsIServiceManager
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 service that is bei...
...ns 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 be tested. return ...
... 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 ); parameters acontractid th...
... 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. users of the service...
nsIUpdate
ilsurl astring the url to a page which offers details about the content of this update. ideally, this page is not the release notes but some other page that summarizes the differences between this update and the previous, which also links to the release notes. displayversion astring the string to display in the user interface for the version. if you want a real version number use appversion. ...
... a page which offers details about the content of this update. ideally, this page is not the release notes but some other page that summarizes the differences between this update and the previous, which also links to the release notes. displayversion astring the string to display in the user interface for the version. if you want a real version number use appversion. ...
...e release notes. displayversion astring the string to display in the user interface for the version. if you want a real version number use appversion.
errorcode long a numeric
error code that conveys additional information about the state of a failed update or failed certificate attribute check during an update check. if the update is not in the "failed" state, this value is zero. ok (0) no
error. mem_
error (1) a memory
error occurred. usage_
error (3) a usage
error occurred; this needs to be described in more detail. crc_
error (4) a checksum
error occurred. parse_
error (5) an
error occurred while parsing the patch. ...
...the state of a failed update or failed certificate attribute check during an update check. if the update is not in the "failed" state, this value is zero. ok (0) no
error. mem_
error (1) a memory
error occurred. usage_
error (3) a usage
error occurred; this needs to be described in more detail. crc_
error (4) a checksum
error occurred. parse_
error (5) an
error occurred while parsing the patch. read_
error (6) an
error occurred while reading the patch. write_
error (7) an
error occurred while writing the patched application. unexpected_
error (8) an unanticipate type of
error occurred. extensionversion astring the add-on version of this update. used by the extension system to track compatibility of installed add-ons with this update. obsolete since gecko 2.0 installdate long long the date and t...
nsIUpdatePrompt
show various update-related notifications to the user. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void checkforupdates(); void showupdateavailable(in nsiupdate update); void showupdatedownloaded(in nsiupdate update, [optional] in boolean background); void showupdate
error(in nsiupdate update); void showupdatehistory(in nsidomwindow parent); void showupdateinstalled(); methods checkforupdates() presents a user interface that checks for and displays the available updates. void checkforupdates(); parameters none. showupdateavailable() shows a message advising the user that an update is available to be downloaded and installed. if the app.update.silent prefere...
...oad was not user initiated) and the app.update.silent preference is true the call will be a no-op. void showupdatedownloaded( in nsiupdate update, in boolean background optional ); parameters update an nsiupdate describing the update that was downloaded. background optional an optional parameter that, if provided and true, presents a less-obtrusive, non-modal notification alert. ...
...tiated) and the app.update.silent preference is true the call will be a no-op. void showupdatedownloaded( in nsiupdate update, in boolean background optional ); parameters update an nsiupdate describing the update that was downloaded. background optional an optional parameter that, if provided and true, presents a less-obtrusive, non-modal notification alert. ...
...iupdate describing the update that was downloaded. background optional an optional parameter that, if provided and true, presents a less-obtrusive, non-modal notification alert. showupdate
error() displays an
error message telling the user about an update failure, such as a failure to successfully apply a patch. if the app.update.silent preference is true the call will be a no-op. void showupdate
error( in nsiupdate update ); parameters update an nsiupdate describing the update that failed to install. the nsiupdate object will not be the actual update when the
error occurred during an update check and will instead be an nsiupdate object with the
error information for the update check. showupdatehistory() shows a list of all updates that have been installed to date. void showupdatehistory( ...
nsIXULTemplateBuilder
parameter. the builder will apply the rules associated with the query to the new result, unless a result with the same id from an earlier query supersedes it, and the result's rulematched() method will be called if it matches. void addresult( in nsixultemplateresult aresult, in nsidomnode aquerynode ); parameters aresult the result to add. aquerynode the query to which the result applies.
errors throws ns_
error_null_pointer if aresult or aquerynode is null. removeresult() informs the template builder that a result no longer applies. the builder will call the remove content generated for the result, if any. if a different query would then match instead, it will become the active match. this method will have no effect if the result isn't known to the builder. void removeresult( in nsi...
...veresult() informs the template builder that a result no longer applies. the builder will call the remove content generated for the result, if any. if a different query would then match instead, it will become the active match. this method will have no effect if the result isn't known to the builder. void removeresult( in nsixultemplateresult aresult ); parameters aresult the result to remove
errors throws ns_
error_null_pointer if aresult is null replaceresult() inform the template builder that one result should be replaced with another. both the old result (aoldresult) and the new result (anewresult) must have the same id. the query node that the new result applies to must be specified using the aquerynode parameter. this method is expected to have the same effect as calling both remover...
...e aquerynode parameter. this method is expected to have the same effect as calling both removeresult for the old result and addresult for the new result. void replaceresult( in nsixultemplateresult aoldresult, in nsixultemplateresult anewresult, in nsidomnode aquerynode ); parameters aoldresult the old result. anewresult the new result. aquerynode the query that the new result applies to.
errors throws ns_
error_null_pointer if either argument is null, or ns_
error_invalid_arg if the ids don't match resultbindingchanged() informs the template builder that one or more of the optional bindings for a result has changed. in this case, the rules are not reapplied as it is expected that the same rule will still apply. the builder will resynchronize any variables that are referenced in the act...
...ndingchanged() informs the template builder that one or more of the optional bindings for a result has changed. in this case, the rules are not reapplied as it is expected that the same rule will still apply. the builder will resynchronize any variables that are referenced in the action body. void resultbindingchanged( in nsixultemplateresult aresult ); parameters aresult the result to change
errors throws ns_
error_null_pointer if aresult is null getresultforid() returns the result for a given id. only one such result is returned and is always the result with that id associated with the active match. this method will return null is there is no result for the id. nsixultemplateresult getresultforid( in astring aid ); parameters aid the id to return the result for return value the resul...
nsIXULTemplateQueryProcessor
result's rulematched method is called, since the bindings are different for each rule. the reference aref may be used to determine the reference when calculating the value for the binding, for example when a value should depend on the value of another variable. the syntax of the expression aexpr is defined by the query processor. if the syntax is invalid, the binding should be ignored. only fatal
errors should be thrown, or ns_
error_unexpected if generateresults() has already been called. as an example, if the reference aref is the variable ?count which holds the value 5, and the expression aexpr is the string '+2', the value of the variable 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 ...
...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 comparison variable is n...
...s 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 method may return ...
... 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 reference so a tra...
XPCOM Interface Reference
derimgirequestinidomutilsjsdistackframemoziasyncfaviconsmoziasynchistorymozicoloranalyzermozijssubscriptloadermozipersonaldictionarymoziplaceinfomoziplacesautocompletemoziregistrymozirepresentativecolorcallbackmozispellcheckingenginemozistorageaggregatefunctionmozistorageasyncstatementmozistoragebindingparamsmozistoragebindingparamsarraymozistoragecompletioncallbackmozistorageconnectionmozistorage
errormozistoragefunctionmozistoragependingstatementmozistorageprogresshandlermozistorageresultsetmozistoragerowmozistorageservicemozistoragestatementmozistoragestatementcallbackmozistoragestatementparamsmozistoragestatementrowmozistoragestatementwrappermozistoragevacuumparticipantmozistoragevaluearraymozitxttohtmlconvmozithirdpartyutilmozivisitinfomozivisitinfocallbackmozivisitstatuscallbacknsiabcardns...
...toragensicrashreporternsicryptohmacnsicryptohashnsicurrentcharsetlistenernsicyclecollectorlistenernsidbchangelistenernsidbfolderinfonsidnslistenernsidnsrecordnsidnsrequestnsidnsservicensidomcanvasrenderingcontext2dnsidomchromewindownsidomclientrectnsidomdesktopnotificationnsidomdesktopnotificationcenternsidomelementnsidomeventnsidomeventgroupnsidomeventlistenernsidomeventtargetnsidomfilensidomfile
errornsidomfileexceptionnsidomfilelistnsidomfilereadernsidomfontfacensidomfontfacelistnsidomgeogeolocationnsidomgeopositionnsidomgeopositionaddressnsidomgeopositioncallbacknsidomgeopositioncoordsnsidomgeoposition
errornsidomgeoposition
errorcallbacknsidomgeopositionoptionsnsidomglobalpropertyinitializernsidomhtmlaudioelementnsidomhtmlformelementnsidomhtmlmediaelementnsidomhtmlsourceelementnsidomhtmltimer...
...nloadhistorynsidownloadmanagernsidownloadmanageruinsidownloadobservernsidownloadprogresslistenernsidownloadernsidragdrophandlernsidragservicensidragsessionnsidroppedlinkhandlernsidroppedlinkitemnsidynamiccontainernsieditornsieditorboxobjectnsieditordocshellnsieditorimesupportnsieditorloggingnsieditormailsupportnsieditorobservernsieditorspellchecknsieffectivetldservicensienumeratornsienvironmentnsi
errorservicensieventlistenerinfonsieventlistenerservicensieventsourcensieventtargetnsiexceptionnsiextensionmanagernsiexternalhelperappservicensiexternalprotocolservicensiexternalurlhandlerservicensiftpchannelnsiftpeventsinknsifactorynsifavicondatacallbacknsifaviconservicensifeednsifeedcontainernsifeedelementbasensifeedentrynsifeedgeneratornsifeedpersonnsifeedprocessornsifeedprogresslistenernsifeedresul...
...romptnsipromptservicensipropertiesnsipropertynsipropertybagnsipropertybag2nsipropertyelementnsiprotocolhandlernsiprotocolproxycallbacknsiprotocolproxyfilternsiprotocolproxyservicensiproxyinfonsipushmessagensipushservicensipushsubscriptionnsiradiointerfacelayernsirandomgeneratornsirequestnsirequestobservernsiresumablechannelnsirunnablensishentrynsishistorynsishistorylistenernsisockssocketinfonsissl
errorlistenernsisslsocketcontrolnsiscreennsiscreenmanagernsiscript
errornsiscript
error2nsiscriptableionsiscriptableinputstreamnsiscriptableunescapehtmlnsiscriptableunicodeconverternsiscrollablensisearchenginensisearchsubmissionnsisecuritycheckedcomponentnsiseekablestreamnsiselectionnsiselection2nsiselection3nsiselectioncontrollernsiselectionimageservicensiselectionprivatensiserversocketnsiserversocketli...
NS ENSURE TRUE
summary macro returns return-value if expr evaluates to false. ...
... summary macro returns return-value if expr evaluates to false. ...
... summary macro returns return-value if expr evaluates to false. ...
...cro returns return-value if expr evaluates to false. syntax ns_ensure_true( expr, return-value ); usage nsresult mozmyclass::mozstringmucking() { char *foo = new char[123]; ns_ensure_true(foo, ns_
error_out_of_memory); // this is equivalent to doing: if (!foo) return ns_
error_out_of_memory; // thou shalt not return ns_
error_failure.. ...
nsIAbCard/Thunderbird3
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); [noscript] pruint32 getprop...
..., 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 string name); setproper...
...int32 value); [noscript] void setpropertyasbool(in string name, in boolean value); parameters name the case-sensitive name of the property to set. value the new value of the property. deleteproperty() deletes the property with the given name. some properties may not be deleted. however, the implementation will not check this constraint at this method. if such a property is deleted, an
error may be thrown when the card is modified at the database level. void deleteproperty(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 ...
...ing 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 implementation defines it as eq...
Getting Started Guide
the correct order to do assign raw pointers anyway (see comparison 1) but i need it for this comparison. */ ns_if_release(mfooptr); mfooptr = afooptr; ns_if_addref(mfooptr); // |nscomptr|... // given: |nscomptr<nsifoo> mfooptr;| /* you no longer need, nor will the compiler let you, call |addref|, or |release|. */ ns_if_release(mfooptr); //
error: |release| is private mfooptr = afooptr; ns_if_addref(mfooptr); //
error: |addref| is private second: you can't just pass the address of an nscomptr to a getter expecting to return a result through a raw xpcom interface pointer parameter. you have to `annotate' the nscomptr with the getter_addrefs directive. comparison 4. differences: apply getter_addrefs when using an nscomptr a...
...be aware that if you should have queried but didn't, e.g., when assigning in a raw pointer where c++ allows the assignment, but xpcom wouldn't, nscomptr will assert at runtime. use do_queryinterface whenever you assign in a pointer to a xpcom interface of a different type, even if that type happens to derive from the base type of the nscomptr comparison 6. do_queryinterface prevents xpcom type
errors. class nsibar : public nsifoo ... { ... }; nsibar* p = ...; // c++ thinks every |nsibar*| is an // |nsifoo*|, therefore, c++ allows // this... nscomptr<nsifoo> foo = p; // ...even though it is an xpcom // type
error class nsibar : public nsifoo ... { ... }; nsibar* p = ...; // no type
error here... nscomptr<nsifoo> foo(do_queryinterface(p)); ...
... any place you use an interface pointer as an owning reference, i.e., where you call addref and release on it. you should use nscomptr as a member variable, where it will simplify setters, and eliminate constructors, destructors, and assignment operators. 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.
...al, you won't want to use nscomptr in the signature of xpcom (i.e., `scriptable') functions. nscomptr is not currently directly supported by idl. however, you may sometime be tempted to use an nscomptr in a non-scriptable function. nscomptr<t> f() don't return an nscomptr this practice is dangerous. returning an addrefed pointer in almost any form as a function result leads to several potential
errors, some of which are leaks, some of which are dangling pointers. returning an nscomptr may seem like a good idea (since it tells clients you are giving them ownership), however it can be the cause of an dangling pointer. consider: // don't return |nscomptr|s... nscomptr<nsifoo> createfoo(); // ... nsifoo* myfoo = createfoo(); // oops: |myfoo| now dangles! // |createfoo| returns ...
The Valgrind Test Job
the valgrind test job builds the browser and runs it under valgrind, which can detect various common memory-related
errors. this job only runs on linux64, which is the platform best suited to running valgrind. running the valgrind test job locally valgrind works best on linux. it also works on mac, though sometimes not as well. building you need a valgrind-enabled build of firefox. add the following lines to your mozconfig file. ac_add_options --enable-valgrind ac_add_options --disable-jemalloc running to run the valgrind test job locally, run the following command. mach valgrind-test see also the general instructions for using valgrind with mozilla code. ...
...rks on mac, though sometimes not as well. building you need a valgrind-enabled build of firefox. add the following lines to your mozconfig file. ac_add_options --enable-valgrind ac_add_options --disable-jemalloc running to run the valgrind test job locally, run the following command. mach valgrind-test see also the general instructions for using valgrind with mozilla code. understanding
errors for each problem that valgrind finds, it emits a message describing the problem, along with a stack trace indicating where the problem occurs. it also prints a suppression, which is a sequence of text that can be put in a suppression file (and specified via valgrind's --suppressions option) if you want valgrind to ignore such
errors in future runs. for example, we have a small number of delib...
... indicating where the problem occurs. it also prints a suppression, which is a sequence of text that can be put in a suppression file (and specified via valgrind's --suppressions option) if you want valgrind to ignore such
errors in future runs. for example, we have a small number of deliberate but inconsequential memory leaks in the codebase that have corresponding suppressions. but generally
errors should be fixed rather than suppressed. when running locally, you may see
errors that do not occur on the test machines. ...
...file (and specified via valgrind's --suppressions option) if you want valgrind to ignore such
errors in future runs. for example, we have a small number of deliberate but inconsequential memory leaks in the codebase that have corresponding suppressions. but generally
errors should be fixed rather than suppressed. when running locally, you may see
errors that do not occur on the test machines.
errors in system libraries can generally be ignored, because they are out of our control and the kind of thing we suppress on the test machines.
errors in mozilla code should probably be reported in bugs! if you need help or experience problems if you need help with the valgrind test job, please contact nicholas nethercote or gary kwong. julian seward can also help with valgrind issues. alternativ...
Testing Mozilla code
et your code committed into the source tree, you have to test it, and larger patches have to have automated tests. these articles will help you master (and continue to excel at) testing mozilla code. ...
...it uses a compile-time instrumentation to check all reads and writes during the execution. ...
...ected.clang static analysisthis document is split in two parts. the first part will focus on the modern and robust way of static-analysis and the second part will present the build-time static-analysis.debugging mozilla with valgrindthis page describes how to use valgrind (specifically, its memcheck tool) to find memory
errors.firefox and address sanitizeraddress sanitizer (asan) is a fast memory
error detector that detects use-after-free and out-of-bound bugs in c/c++ programs. it uses a compile-time instrumentation to check all reads and writes during the execution. in addition, the runtime part replaces the malloc and free functions to check dynamically allocated memory. more information on how asan works can be found on the address sanitizer wiki. fuzzing interfacethe fuzzing interface ...
...st that you run on it. there are different types of coverage metrics (see also the wikipedia entry), but when we speak of code coverage here, we usually mean line and branch coverage. this type of coverage is only concerned with hit counts for lines and branches.the valgrind test jobthe valgrind test job builds the browser and runs it under valgrind, which can detect various common memory-related
errors. this job only runs on linux64, which is the platform best suited to running valgrind. ...
ArrayType
ters 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 type
error 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 range
error 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 only. lengt...
...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 type
error 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 property typ...
...t notation, 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 type
error 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 o...
...ssofelement() 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 type
error 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 ...
CData
string 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 type
error 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 v...
...ue a 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 type
error 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(); ...
...are assumed to be encoded as utf-8. if the 8-bit string contains invalid encoded character, no exception is thrown. string readstringreplacemalformed(); parameters none. return value a new string object that is a copy of the original string contents. invalid encoded characters will be replaced by �(u+fffd). ...
...nsole.info('char16_val:', char16_val); return char16_val; } if (!jschar) { try { var char8_val = stringptr.readstring(); console.info('stringptr.readstring():', char8_val); return char8_val; } catch (ex if ex.message.indexof('malformed utf-8 character sequence at offset ') == 0) { console.warn('ex of offset utf8 read
error when trying to do readstring so using alternative method, ex:', ex); return readjscharstring(); } } else { return readjscharstring(); } } ...
Int64
st 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 type
error 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. method overview ...
... 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. exceptions thrown type
error 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 type
error num is not a 64-bit integer object. lo() ...
... join() 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. ...
...ger 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 type
error 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. string tostring( [...
StructType
cribing 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 type
error the name is not a string, or one or more of the fields does not have a defined size. range
error 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, such as {'serialnumber':...
...ods 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 unspecified length...
...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 unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a type
error 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 str...
...pecified 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 type
error name is not a javascript string, or doesn't name a member field of the structure. see also ctype cdata type conversion ...
URLs - Plugins
h requests url objects. note that npn_geturl is typically asynchronous: it returns immediately and only later handles the request, such as displaying the url or creating the stream for the instance and writing the data. for this reason as well, calling npn_geturlnotify may be more useful than npn_geturl; the plug-in is notified upon either successful or unsuccessful completion of the request. np
error npn_geturl(npp instance, const char *url, const char *target); the instance parameter represents the current plug-in instance. the url parameter is the url of the request, which can be of any type, including http, ftp, news, or mailto. the target parameter represents the destination where the url will be displayed, a window or frame. if target refers to the window or frame containing the plug-i...
...n's npp_urlnotify function and passing it the notifydata value, which may be used to track multiple requests. npn_geturlnotify handles the url request asynchronously. it returns immediately and only later handles the request and calls npp_urlnotify. without this notification, the plug-in cannot tell whether a request with a null target failed or a request with a non-null target was completed. np
error npn_geturlnotify(npp instance, const char* url, const char* target, void* notifydata); the instance, url, and target parameters have the same definitions as those of npn_geturl. the notifydata parameter contains private plug-in data that can be used to associate the request with the subsequent npp_urlnotify call (which returns this value) and/or to pass a pointer to some...
...ther in a local temporary file or a new memory buffer. to post a file, set the flag file to true, the buffer buf to the path name string for a file, and len to the length of the path string. the file-type url prefix "file://" is optional. npn_posturl is typically asynchronous: it returns immediately and only later handles the request and calls npp_notify (which, in turn, calls npp_urlnotify). np
error npn_posturl(npp instance, const char *url, const char *target, uint32 len, const char *buf, npbool file); the instance, url, and target parameters have the same definitions as those of npn_geturl. the buf parameter identifies a local temporary file or data buffer that contains the data to post. windows and mac if a file is posted with any protocol other than ftp, the file must be text with ...
... the npn_posturlnotify function has all the same capabilities and works like npn_posturl in most ways except that (1) it supports specifying headers when posting a memory buffer, and (2) it calls npp_urlnotify upon successful or unsuccessful completion of the request. npn_posturlnotify is typically asynchronous: it returns immediately and only later handles the request and calls npp_urlnotify. np
error npn_posturlnotify( npp instance, const char *url, const char *target, uint32 len, const char *buf, npbool file, void* notifydata ); the parameters of this function have the same definitions as those of npn_posturl. the notifydata parameter contains plug-in-private data passed by npp_urlnotify and may be used for tracking multiple posts. posting data to an http server the following co...
Debugger.Object - Firefox Developer Tools
ompletion value describing how the call completed.this should be a debuggee value, or { asconstructor: true } to invoke the referent as a constructor, in which case spidermonkey provides an appropriate this value itself. eachargument must be a debuggee value. all extant handler methods, breakpoints, watchpoints, and so on remain active during the call. if the referent is not callable, throw a type
error. this function follows the invocation function conventions. apply(this,arguments) if the referent is callable, call it with the giventhis value and the argument values inarguments, and return a completion value describing how the call completed.this should be a debuggee value, or { asconstructor: true } to invokefunction as a constructor, in which case spidermonkey provides an appropriate t...
...{ asconstructor: true } to invokefunction as a constructor, in which case spidermonkey provides an appropriate this value itself.arguments must either be an array (in the debugger) of debuggee values, or null or undefined, which are treated as an empty array. all extant handler methods, breakpoints, watchpoints, and so on remain active during the call. if the referent is not callable, throw a type
error. this function follows the invocation function conventions. 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 conventio...
...ons. 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 type
error 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. ...
...referent, and thebindings appear in a new declarative environment, which is the eval code's lexicalenvironment.) theoptions argument is as for debugger.frame.prototype.eval. asenvironment() if the referent is a global object, return the debugger.environment instance representing the referent as a variable environment for evaluating code. if the referent is not a global object, throw a type
error. setobjectwatchpoint(handler)(future plan) set a watchpoint on all the referent's own properties, reporting events by callinghandler's methods. any previous watchpoint handler on this debugger.object instance is replaced. ifhandler is null, the referent is no longer watched.handler may have the following methods, called under the given circumstances: add(frame,name,descriptor) a p...
Cache - Web APIs
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 shorthand identifier for a cache to a specific, versioned cache nam...
...http status code of 4xx or 5xx). // we also only want to cache responses that correspond to fonts, // i.e. have a content-type response header that starts with "font/". // note that for opaque filtered responses (https://fetch.spec.whatwg.org/#concept-filtered-response-opaque) // we can't access to the response headers, so this check will alw...
... console.log(' caching the response 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. ...
... } 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 headers to be stripped before returning a response object from fetch(). so a response s...
Element.requestFullscreen() - Web APIs
make the element be displayed in full-screen mode. it's not guaranteed that the element will be put into full screen mode. if permission to enter full screen mode is granted, the returned promise will resolve and the element will receive a fullscreenchange event to let it know that it's now in full screen mode. if permission is denied, the promise is rejected and the element receives a fullscreen
error event instead. if the element has been detached from the original document, then the document receives these events instead. earlier implementations of the fullscreen api would always send these events to the document rather than the element, and you may need to be able to handle that situation. check browser compatibility in fullscreen for specifics on when each browser made this change. note...
...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: type
error the type
error 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 contained by a document. the element is not permitted t...
...een mode, or when the user switches applications, causing your application to temporarily exit full-screen mode. examples this function toggles the first <video> element found in the document into and out of full-screen mode. function togglefullscreen() { let elem = document.queryselector("video"); if (!document.fullscreenelement) { elem.requestfullscreen().catch(err => { alert(`
error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitfullscreen(); } } if the document isn't already in full-screen mode—detected by looking to see if document.fullscreenelement has a value—we call the video's requestfullscreen() method. we don't need to do anything special if successful, but if the request fails, our promise's catch() ...
...message} (${err.name})`); }); } else { document.exitfullscreen(); } } if the document isn't already in full-screen mode—detected by looking to see if document.fullscreenelement has a value—we call the video's requestfullscreen() method. we don't need to do anything special if successful, but if the request fails, our promise's catch() handler presents an alert with an appropriate
error message. if, on the other hand, full-screen mode is already in effect, we call document.exitfullscreen() to disable full-screen mode. you can see this example in action or view or remix the code on glitch. specifications specification status comment fullscreen apithe definition of 'element.requestfullscreen()' in that specification. living standard initial de...
GlobalEventHandlers.oninvalid - Web APIs
or after the checkvalidity() method of the element or its owner form is called. syntax target.oninvalid = functionref; var functionref = target.oninvalid; value functionref is a function name or a function expression. the function receives a event object as its sole argument. example this example demonstrates oninvalid and onsubmit event handlers on a form. ...
...xample demonstrates oninvalid and onsubmit event handlers on a form. html <form id="form"> <p id="
error" hidden>please fill out all fields.</p> <label for="city">city</label> <input type="text" id="city" required> <button type="submit">submit</button> </form> <p id="thanks" hidden>your data has been received. ...
... onsubmit event handlers on a form. html <form id="form"> <p id="
error" hidden>please fill out all fields.</p> <label for="city">city</label> <input type="text" id="city" required> <button type="submit">submit</button> </form> <p id="thanks" hidden>your data has been received. ...
...red> <button type="submit">submit</button> </form> <p id="thanks" hidden>your data has been received. thanks!</p> javascript const form = document.getelementbyid('form'); const
error = document.getelementbyid('
error'); const city = document.getelementbyid('city'); const thanks = document.getelementbyid('thanks'); city.oninvalid = invalid; form.onsubmit = submit; function invalid(event) {
error.removeattribute('hidden'); } function submit(event) { form.setattribute('hidden', ''); thanks.removeattribute('hidden'); // for this example, don't actually submit the form event.preventdefault(); } result specification specification status comment html living standardthe definition of 'oninvalid' in that specification. living standard ...
GlobalEventHandlers.onsubmit - Web APIs
rs mixin is an eventhandler that processes submit events. the submit event fires when the user submits a form. syntax target.onsubmit = functionref; value functionref is a function name or a function expression. the function receives a focusevent object as its sole argument. example this example demonstrates oninvalid and onsubmit event handlers on a form. ...
...xample demonstrates oninvalid and onsubmit event handlers on a form. html <form id="form"> <p id="
error" hidden>please fill out all fields.</p> <label for="city">city</label> <input type="text" id="city" required> <button type="submit">submit</button> </form> <p id="thanks" hidden>your data has been received. ...
... onsubmit event handlers on a form. html <form id="form"> <p id="
error" hidden>please fill out all fields.</p> <label for="city">city</label> <input type="text" id="city" required> <button type="submit">submit</button> </form> <p id="thanks" hidden>your data has been received. ...
...red> <button type="submit">submit</button> </form> <p id="thanks" hidden>your data has been received. thanks!</p> javascript const form = document.getelementbyid('form'); const
error = document.getelementbyid('
error'); const city = document.getelementbyid('city'); const thanks = document.getelementbyid('thanks'); city.oninvalid = invalid; form.onsubmit = submit; function invalid(event) {
error.removeattribute('hidden'); } function submit(event) { form.setattribute('hidden', ''); thanks.removeattribute('hidden'); // for this example, don't actually submit the form event.preventdefault(); } result specifications specification status comment html living standardthe definition of 'onsubmit' in that specification. living standard ...
HTMLMediaElement.play() - Web APIs
ay(); 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). ...
...urn 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). ...
... other exceptions may be reported, depending on browser implementation details, media player implementation, and so forth. ...
... is usually thought of as referring to pages that immediately begin playing media upon being loaded, web browsers' autoplay policies also apply to any script-initiated playback of media, including calls to play(). if the user agent is configured not to allow automatic or script-initiated playback of media, calling play() will cause the returned promise to be immediately rejected with a notallowed
error. web sites should be prepared to handle this situation. for example, a site should not present a user interface that assumes playback has begun automatically, but should instead update their ui based on whether the returned promise is resolved or rejected. see the example below for more information. note: the play() method may cause the user to be asked to grant permission to play the media, re...
HTMLTableElement - Web APIs
eelement</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 domexception with the hierarchyrequest
error 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...
...t 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 domexception with the hierarchyrequest
error 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 first <tfoot> that is a child of ...
...ption>, 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 domexception with the hierarchyrequest
error 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 htmlcollection containing all the rows of th...
...row() returns an htmltablerowelement representing a new row of the table. it inserts it in the rows collection immediately before the <tr> element at the given index position. if necessary a <tbody> is created. if the index is -1, the new row is appended to the collection. if the index is smaller than -1 or greater than the number of rows in the collection, a domexception with the value indexsize
error is raised. htmltableelement.deleterow() removes the row corresponding to the index given in parameter. if the index value is -1 the last row is removed; if it smaller than -1 or greater than the amount of rows in the collection, a domexception with the value indexsize
error is raised. specifications specification status comment html living standardthe definition of...
IDBCursor.continuePrimaryKey() - Web APIs
key parameter as well as whose primary key matches the primary key parameter. a typical use case, is to resume the iteration where a previous cursor has been closed, without having to compare the keys one by one. calling this method more than once before new cursor data has been loaded - for example, calling continueprimarykey() twice from the same onsuccess handler - results in an invalidstate
error being thrown on the second call 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 ...
... the key is less than or equal to this cursor's position and the cursor's direction is next or nextunique. ...
...ilable 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 domexception of one of the following types: exception description transactioninactive
error this idbcursor's transaction is inactive. ...
...tion is inactive. data
error 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 direction is next or nextunique. the key is greater than or equal to this cursor's position and this cursor's direction is prev or prevunique. invalidstate
error the cursor is currently being iterated or has iterated past its end. invalidaccess
error the cursor's direction is not prev or next. example here’s how you can resume an iteration of all articles tagged with "javascript" since your last visit: let request = articlestore.index("tag").opencursor(); let count = 0; let unreadlist = []; request.onsuccess = (event) => { let...
IDBCursor.update() - Web APIs
lable 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. ...
...(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 domexception of one of the following types: exception description transactioninactive
error this idbcursor's transaction is inactive. readonly
error the transaction mode is read only. ...
...current position. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactive
error this idbcursor's transaction is inactive. readonly
error the transaction mode is read only. invalidstate
error the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end. ...
...is method may raise a domexception of one of the following types: exception description transactioninactive
error this idbcursor's transaction is inactive. readonly
error the transaction mode is read only. invalidstate
error the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end. data
error the underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this cursor's position. dataclone
error the data being stored could not be cloned by the internal structured cloning algorithm. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to ite...
IDBDatabase.createObjectStore() - Web APIs
he new object store. if empty or not specified, the object store is created without a key path and uses out-of-line keys. you can also pass in an array as a keypath. autoincrement if true, the object store has a key generator. defaults to false. unknown parameters are ignored. returns a new idbobjectstore. exceptions this method may raise a domexception with a dom
error of one of the following types: exception description invalidstate
error occurs if the method was not called from a versionchange transaction callback. for older webkit browsers, you must call first. transactioninactive
error occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) in firefox previous to version...
...wing types: exception description invalidstate
error occurs if the method was not called from a versionchange transaction callback. for older webkit browsers, you must call first. transactioninactive
error occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstate
error was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) constraint
error an object store with the given name (based on case-sensitive comparison) already exists in the connected database. invalidaccess
error if autoincrement is set to true and keypath is either an empty string or an array containing an empty string. example /...
...base var request = window.indexeddb.open("todolist", 4); // this handler is called when a new version of the database // is created, either when one has not been created before // or when a new version number is submitted by calling // window.indexeddb.open(). // this handler is only supported in recent browsers. ...
...4); // this handler is called when a new version of the database // is created, either when one has not been created before // or when a new version number is submitted by calling // window.indexeddb.open(). // this handler is only supported in recent browsers. ...
IDBFactory.open() - Web APIs
he open() method of the idbfactory interface requests opening a connection to a database. the method returns an idbopendbrequest object immediately, and performs the open operation asynchronously. if the operation is successful, a success event is fired on the request object that is returned from this method, with its result attribute set to the new idbdatabase object for the connection. if an
error occurs while the database connection is being opened, then an
error event is fired on the request object returned from this method. may trigger upgradeneeded, blocked or versionchange events. note: this feature is available in web workers. syntax for the current standard: var idbopendbrequest = indexeddb.open(name); var idbopendbrequest = indexeddb.open(name, version); parameters name ...
...an 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 domexception of the following types: exception description type
error 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 database, and include handlers for the success and
error cases. for a full working example, see our to-do notifications app ...
...this is used a lot later on, for opening // transactions and suchlike. db = dbopenrequest.result; }; specifications specificatio...
...this is used a lot later on, for opening // transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database ap...
IDBFactory - Web APIs
e a method to request the deletion of a database. idbfactory.cmp a method that compares two keys and returns a result indicating which one is greater in value. idbfactory.databases a method that returns a list of all available databases, including their names and versions. example in the following code snippet, we make a request to open a database, and include handlers for the success and
error cases. for a full working example, see our to-do notifications app (view example live.) // in the following line, you should include the prefixes of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use "var indexeddb = ..." if you're not in a function. // moreover, you may need references to som...
...this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment ind...
...this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the definition ...
...this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the definition of 'idb...
IDBObjectStore.deleteIndex() - Web APIs
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. ...
...syntax objectstore.deleteindex(indexname); parameters indexname the name of the existing index to remove. return value undefined exceptions this method may raise a domexception of one of the following types: exception description invalidstate
error occurs if the method was not called from a versionchange transaction mode callback. transactioninactive
error occurs if the transaction this idbobjectstore belongs to is not active (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstate
error was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) notfound
error occurs if there is no index with the given name (case-sensitive) in the database. example in th...
...ndex is used to create new indexes on the object store, after which we delete the unneeded old indexes with deleteindex(). for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not dbopenrequest.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. this is used a lot below db = this.result; // run the displaydata() function to populate the task list with all the to-do list data already in the id...
...-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of the database needs to be created // either one has not been created before, or a new version number has been submitted via the // window.indexeddb.open line above //it is only implemented in recent browsers dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false...
IDBObjectStore - Web APIs
// store the result of opening the database in db. ...
... db = dbopenrequest.result; }; // this event handles the event whereby a new version of // the database needs to be created either one has not // been created before, or a new version number has been // submitted via the window.indexeddb.open line above dbopenrequest.onupgradeneeded = function(event) { var db = event.target.result; db.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: f...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { note.in...
... open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { note.innerhtml += '<li>request successful .</li>'; } specifications specifica...
IDBTransaction: abort event - Web APIs
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 dbopenrequest = window.indexeddb.open...
...dware 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. ...
... 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. ...
...t` transaction.addeventlistener('abort', () => { console.log('transaction was aborted'); }); // abort the transaction transaction.abort(); }; the same example, but assigning the event handler to the onabort property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.on
error = () => { console.log('
error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createinde...
Basic concepts - Web APIs
hes, and the type of event you get lets you know if the operation succeeded or failed. this sounds a little complicated at first, but there are sanity measures baked in. it's not that different from the way that xmlhttprequest works. indexeddb uses a lot of requests. requests are objects that receive the success or failure dom events that were mentioned previously. they have onsuccess and on
error properties, and you can call addeventlistener() and removeeventlistener() on them. they also have readystate, result, and
errorcode properties that tell you the status of the request. the result property is particularly magical, as it can be many different things, depending on how the request was generated (for example, an idbcursor instance, or the key for a value that you just inserted into the...
...st. the result property is particularly magical, as it can be many different things, depending on how the request was generated (for example, an idbcursor instance, or the key for a value that you just inserted into the database). indexeddb uses dom events to notify you when results are available. ...
... indexeddb is object-oriented. ...
... indexeddb is object-oriented. indexeddb is not a relational database with tables representing collections of rows and columns. this important and fundamental difference affects the way you design and build your applications. ...
MediaDevices - Web APIs
permission through a prompt, turns on a camera and/or a microphone on the system and provides a mediastream containing a video track and/or an audio track with the input. example 'use strict'; // put variables in global scope to make them available to the browser console. ...
...camera and/or a microphone on the system and provides a mediastream containing a video track and/or an audio track with the input. example 'use strict'; // put variables in global scope to make them available to the browser console. ...
...constraints) .then(function(stream) { var videotracks = stream.getvideotracks(); console.log('got stream with constraints:', constraints); console.log('using video device: ' + videotracks[0].label); stream.onremovetrack = function() { console.log('stream ended'); }; window.stream = stream; // make variable available to browser console video.srcobject = stream; }) .catch(function(
error) { if (
error.name === 'constraintnotsatisfied
error') {
errormsg('the resolution ' + constraints.video.width.exact + 'x' + constraints.video.height.exact + ' px is not supported by your device.'); } else if (
error.name === 'permissiondenied
error') {
errormsg('permissions have not been granted to use your camera and ' + 'microphone, you need to allow the page access to you...
...
errormsg('the resolution ' + constraints.video.width.exact + 'x' + constraints.video.height.exact + ' px is not supported by your device.'); } else if (
error.name === 'permissiondenied
error') {
errormsg('permissions have not been granted to use your camera and ' + 'microphone, you need to allow the page access to your devices in ' + 'order for the demo to work.'); }
errormsg('getusermedia
error: ' +
error.name,
error); }); function
errormsg(msg,
error) {
errorelement.innerhtml += '<p>' + msg + '</p>'; if (typeof
error !== 'undefined') { console.
error(
error); } } specifications specification status comment media capture and streamsthe definition of 'mediadevices' in that specification. candidate recommendation initial ...
MediaSource.addSourceBuffer() - Web APIs
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. ...
...ourcebuffer(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 invalidaccess
error the value specified for mimetype is an empty string rather than a valid mime type. invalidstate
error the mediasource is not in the "open" readystate. ...
...g 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 invalidaccess
error the value specified for mimetype is an empty string rather than a valid mime type. invalidstate
error the mediasource is not in the "open" readystate. notsupported
error 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. quotaexceeded
error the user agent can't handle any more sourcebuffer objects, or creating a new sourcebuffer using the given mimetype would result in an unsupported configuration of sourcebuffers. ...
...ng codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.
error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystat...
Node.removeChild() - Web APIs
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. 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 notfound
error: 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 ...
...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 notfound
error: 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 type
error: failed to execute 'removechild' on 'node': parameter 1 is not of type 'node'. examples simple examples given this html: <div id="top"> <div id="nested"></div> </div> to remove a specified element when knowing its parent node: let d = document.getelementbyid("top"); let d_nested = document.getelementbyid("nested"); let throwawaynode = d.removechild(d_nested); to remove a specified e...
...wawaynode = d.removechild(d_nested); to remove a specified element without having to specify its parent node: let node = document.getelementbyid("nested"); if (node.parentnode) { node.parentnode.removechild(node); } to remove all children from an element: let element = document.getelementbyid("top"); while (element.firstchild) { element.removechild(element.firstchild); } causing a type
error <!--sample html code--> <div id="top"> </div> <script type="text/javascript"> let top = document.getelementbyid("top"); let nested = document.getelementbyid("nested"); // throws uncaught type
error let garbage = top.removechild(nested); </script> causing a notfound
error <!--sample html code--> <div id="top"> <div id="nested"></div> </div> <script type="text/javascript"> let top ...
... living standard ...
PaymentDetailsUpdate - Web APIs
on before the user interface is even enabled for the first time. properties the paymentdetailsupdate dictionary is based on the paymentdetailsbase dictionary, and inherits its properties, which are included in the list below. displayitems optional an array of paymentitem objects, each describing one line item for the payment request. these represent the line items on a receipt or invoice.
error optional a domstring specifying an
error message to present to the user. when calling updatewith(), including
error in the updated data causes the user agent to display the text as a general
error message. for address field specific
errors, use shippingaddress
errors. modifiers optional an array of paymentdetailsmodifier objects, each describing a modifier for particular payment method identifi...
... shippingoptions optional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose. ...
... shippingoptions optional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose. total optional a paymentitem providing an updated total for the payment. ...
... shippingoptions optional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose. total optional a paymentitem providing an updated total for the payment. make sure this equals the sum of all of the items in displayitems. ...
PaymentRequestUpdateEvent.updateWith() - Web APIs
t interface updates the details of an existing paymentrequest. syntax paymentrequestupdateevent.updatewith(details); parameters details a paymentdetailsupdate object specifying the changes applied to the payment request: displayitems optional an array of paymentitem objects, each describing one line item for the payment request. these represent the line items on a receipt or invoice.
error optional a domstring specifying an
error message to present to the user. when calling updatewith(), including
error in the updated data causes the user agent to display the text as a general
error message. for address field specific
errors, use shippingaddress
errors. modifiers optional an array of paymentdetailsmodifier objects, each describing a modifier for particular payment method identifi...
... shippingoptions optional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose. ...
... shippingoptions optional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose. total optional a paymentitem providing an updated total for the payment. ...
... shippingoptions optional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose. total optional a paymentitem providing an updated total for the payment. make sure this equals the sum of all of the items in displayitems. ...
PushManager.subscribe() - Web APIs
applicationserverkey: applicationserverkey }; serviceworkerregistration.pushmanager.subscribe(options).then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest. ...
...erviceworkerregistration.pushmanager.subscribe(options).then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest. }, function(
error) { // during development it often helps to log
errors to the // console. ...
...ription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest. }, function(
error) { // during development it often helps to log
errors to the // console. in a production environment it might make sense to // also report information about
errors back to the // application server. ...
...the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest. }, function(
error) { // during development it often helps to log
errors to the // console. in a production environment it might make sense to // also report information about
errors back to the // application server. ...
RTCPeerConnection.peerIdentity - Web APIs
tcidentityassertion which contains a domstring identifying the remote peer. once this promise resolves successfully, the resulting identity is the target peer identity and cannot change for the duration of the connection. syntax var identity = rtcpeerconnection.peeridentity; value a javascript promise which resolves to an rtcidentityassertion that describes the remote peer's identity. if an
error occcurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. if there isn't already a target peer identity, peeridentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur. note: the promise returned by setremotedescription...
...t been validated yet, the promise returned by setremotedescription() will be rejected. if there's no target peer identity, setremotedescription() doesn't need to wait for validation to occur before it resolves. example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller. ...
...escription() will be rejected. if there's no target peer identity, setremotedescription() doesn't need to wait for validation to occur before it resolves. example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller. if an
error occurs and the promise is rejected, this logs the
error to the console and returns null to the caller. ...
...y waits for the peer's identity to be verified, then returns the identity to the caller. if an
error occurs and the promise is rejected, this logs the
error to the console and returns null to the caller. let pc = new rtcpeerconnection(); /* ... */ async function getidentityassertion(pc) { try { const identity = await pc.peeridentity; return identity; } catch(err) { console.log("
error identifying remote peer: ", err); return null; } } specifications specification status comment identity for webrtc candidate recommendation initial specification. ...
RTCPeerConnection.setConfiguration() - Web APIs
, 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. ...
...hanges are not additive; instead, the new values completely replace the existing ones. exceptions invalidaccess
error 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. invalidmodification
error the configuration includes changed identity information, but the connection already has identity information specified. this happens if configuration.peeridentity or configuration.certificates is set and their values differ from the current configuration. ...
...eserver.username or rtciceserver.credentials is missing). this prevents successful login to the server. invalidmodification
error the configuration includes changed identity information, but the connection already has identity information specified. this happens if configuration.peeridentity or configuration.certificates is set and their values differ from the current configuration. invalidstate
error the rtcpeerconnection is closed. syntax
error one or more of the urls provided in the configuration.iceservers list is invalid. example in this example, it has already been determined that ice restart is needed, and that negotiation needs to be done using a different ice server. var restartconfig = { iceservers: [{ urls: "turn:asia.myturnserver.net", ...
...this is then passed into setconfiguration(). ice negotiation is restarted by calling createoffer(), specifying true as the value of the icerestart option. from there, we handle the process as usual, by setting the local description to the returned offer and then sending that offer to the...
RTCRtpSender.setParameters() - Web APIs
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. invalidmodification
error 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 sender has be...
...meters 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 sender has been created. the order of the specified encodings has changed from the current list's order. an attempt has been made to alter a property that cannot be changed after the sender is first created. ...
...ou cannot change the number of encoding options once the sender has been created. the order of the specified encodings has changed from the current list's order. an attempt has been made to alter a property that cannot be changed after the sender is first created. invalidstate
error the transceiver of which the rtcrtpsender is a part is not running, or has no parameters to set. operation
error any
error condition which occurs that isn't covered by one of the other
error codes results in an operation
error. ...
...anged from the current list's order. an attempt has been made to alter a property that cannot be changed after the sender is first created. invalidstate
error the transceiver of which the rtcrtpsender is a part is not running, or has no parameters to set. operation
error any
error condition which occurs that isn't covered by one of the other
error codes results in an operation
error. range
error the value specified for scaleresolutiondownby is less than 1.0, which would result in scaling up rather than down, which is not allowed; or one or more of the specified encodings' maxframerate values is less than 0.0. in addition, if a webrtc
error occurs while configuring or accessing the media, an rtc
error is thrown with its
errordetail set to hardware-encoder-
error. specifications ...
ReadableStream.pipeTo() - Web APIs
piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. syntax var promise = readablestream.pipeto(destination[, options]); parameters destination a writablestream that acts as the final destination for the readablestream. ...
...stream that acts as the final destination for the readablestream. options optional the options that should be used when piping to the writable stream. available options are: preventclose: if this is set to true, the source readablestream closing will no longer cause the destination writablestream to be closed. the method will return a fulfilled promise once this process completes, unless an
error is encountered while closing the destination in which case it will be rejected with that
error. preventabort: if this is set to true,
errors in the source readablestream will no longer abort the destination writablestream. the method will return a promise rejected with the source’s
error, or with any
error that occurs during aborting the destination. preventcancel: if this is set to true, e...
...lestream will no longer abort the destination writablestream. the method will return a promise rejected with the source’s
error, or with any
error that occurs during aborting the destination. preventcancel: if this is set to true,
errors in the destination writablestream will no longer cancel the source readablestream. in this case the method will return a promise rejected with the source’s
error, or with any
error that occurs during canceling the source. in addition, if the destination writable stream starts out closed or closing, the source readable 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 abortsigna...
...n 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 type
error 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())) specifications ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
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: abort
error switching the context over to the webxr-compatible context failed. invalidstate
error the webgl context has been lost or there is no available webxr device. usage notes because makexrcompatible() may involve replacing the underlying webgl context with a new one that uses the new rendering hardware, the existing contents of the co...
... been lost but can be restored */ event.canceled = true; }); /* when the gl context is reconnected, reload the resources for the current scene. ...
...urrent scene. ...
...xrsession) { try { await gl.makexrcompatible(); } catch(err) { switch(err) { case abort
error: showsimplemessagebox("unable to transfer the game to your xr headset.", "cancel"); break; case invalidstate
error: showsimplemessagebox("you don't appear to have a compatible xr headset available.", "cancel"); break; default: handlefatal
error(err); break; } xrsession.end(); } } async function handlestartbuttonclick(event) { if (event.target.classlist.contains("use-webxr") && navigator.xr) { try { xrsession = await navigator.xr.requestsession("immersive-vr"); usingxr = true; } catch(err) { xrsession = null; usingxr = false; } } startgame(); } function startgame() { current...
A basic 2D WebGL animation example - Web APIs
ns the shader program after it's been built and linked. function buildshaderprogram(shaderinfo) { let program = gl.createprogram(); shaderinfo.foreach(function(desc) { let shader = compileshader(desc.id, desc.type); if (shader) { gl.attachshader(program, shader); } }); gl.linkprogram(program) if (!gl.getprogramparameter(program, gl.link_status)) { console.log("
error linking shader program:"); console.log(gl.getprograminfolog(program)); } return program; } first, gl.createprogram() is called to create a new, empty, glsl program. then, for each shader in the specified list of shaders, we call a compileshader() function to compile it, passing into it the id and type of the shader function to build. each of those objects includes, as mentioned before,...
...e <script> element the shader code is found in and the type of shader it is. the compiled shader is attached to the shader program by passing it into gl.attachshader(). we could go a step farther here, actually, and look at the value of the <script> element's type attribute to determine the shader type. once all of the shaders are compiled, the program is linked using gl.linkprogram(). if an
error occurrs while linking the program, the
error message is logged to console. finally, the compiled program is returned to the caller. compiling an individual shader the compileshader() function, below, is called by buildshaderprogram() to compile a single shader. function compileshader(id, type) { let code = document.getelementbyid(id).firstchild.nodevalue; let shader = gl.createshader(type...
...ng an individual shader the compileshader() function, below, is called by buildshaderprogram() to compile a single shader. function compileshader(id, type) { let code = document.getelementbyid(id).firstchild.nodevalue; let shader = gl.createshader(type); gl.shadersource(shader, code); gl.compileshader(shader); if (!gl.getshaderparameter(shader, gl.compile_status)) { console.log(`
error compiling ${type === gl.vertex_shader ? "vertex" : "fragment"} shader:`); console.log(gl.getshaderinfolog(shader)); } return shader; } the code is fetched from the html document by obtaining the value of the text node contained within the <script> element with the specified id. then a new shader of the specified type is created using gl.createshader(). the source code is sent into the n...
...der)); } return shader; } the code is fetched from the html document by obtaining the value of the text node contained within the <script> element with the specified id. then a new shader of the specified type is created using gl.createshader(). the source code is sent into the new shader by passing it into gl.shadersource(), and then the shader is compiled using gl.compileshader() compile
errors are logged to the console. note the use of a template literal string to insert the correct shader type string into the message that gets generated. the actual
error details are obtained by calling gl.getshaderinfolog(). finally, the compiled shader is returned to the caller (which is the buildshaderprogram() function. drawing and animating the scene the animatescene() function is called to re...
WebGL constants - Web APIs
o enable/disable to turn on/off the sample coverage. used in multi-sampling. scissor_test 0x0c11 passed to enable/disable to turn on/off the scissor test. can also be used with getparameter to query the scissor test. stencil_test 0x0b90 passed to enable/disable to turn on/off the stencil test. can also be used with getparameter to query the stencil test.
errors constants returned from webglrenderingcontext.get
error(). constant name value description no_
error 0 returned from get
error. invalid_enum 0x0500 returned from get
error. invalid_value 0x0501 returned from get
error. invalid_operation 0x0502 returned from get
error. out_of_memory 0x0505 returned from gete...
... front face directions constants passed to webglrenderingcontext.frontface(). ...
...ue description fragment_shader 0x8b30 passed to createshader to define a fragment shader. vertex_shader 0x8b31 passed to createshader to define a vertex shader compile_status 0x8b81 passed to getshaderparamter to get the status of the compilation. returns false if the shader was not compiled. you can then query getshaderinfolog to find the exact
error delete_status 0x8b80 passed to getshaderparamter to determine if a shader was deleted via deleteshader. returns true if it was, false otherwise. link_status 0x8b82 passed to getprogramparameter after calling linkprogram to determine if a program was linked correctly. returns false if there were
errors. use getprograminfolog to find the exact
error. validate_...
...s true if it was, false otherwise. link_status 0x8b82 passed to getprogramparameter after calling linkprogram to determine if a program was linked correctly. returns false if there were
errors. use getprograminfolog to find the exact
error. validate_status 0x8b83 passed to getprogramparameter after calling validateprogram to determine if it is valid. returns false if
errors were found. attached_shaders 0x8b85 passed to getprogramparameter after calling attachshader to determine if the shader was attached correctly. returns false if
errors occurred. active_attributes 0x8b89 passed to getprogramparameter to get the number of attributes active in a program. active_uniforms 0x8b86 passed to getprogramparamter to get the numb...
Writing WebSocket client applications - Web APIs
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. ...
...ng on the specified protocol). if you don't specify a protocol string, an empty string is assumed. the constructor will throw a security
error if the destination doesn't allow access. this may happen if you attempt to use an insecure connection (most user agents now require a secure link for all websocket connections unless they're on the same device or possibly on the same network). ...
...ified protocol). if you don't specify a protocol string, an empty string is assumed. the constructor will throw a security
error if the destination doesn't allow access. this may happen if you attempt to use an insecure connection (most user agents now require a secure link for all websocket connections unless they're on the same device or possibly on the same network). ...
...ssumed. the constructor will throw a security
error if the destination doesn't allow access. this may happen if you attempt to use an insecure connection (most user agents now require a secure link for all websocket connections unless they're on the same device or possibly on the same network). connection
errors if an
error occurs while attempting to connect, first a simple event with the name
error is sent to the websocket object (thereby invoking its on
error handler), and then the closeevent is sent to the websocket object (thereby invoking its onclose handler) to indicate the reason for the connection's closing. the browser may also output to its console a more descriptive
error message as well as a closing code as defined in rfc 6455, section 7.4 through the closeevent. examples this ...
Using the Web Storage API - Web APIs
hat 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 making it unusable. conversely, we might get a legitimate quotaexceeded
error, which means that we've used up all available storage space, but storage is actually available. our feature detection should take these scenarios into account. here is a function that detects whether localstorage is both supported and available: function storageavailable(type) { var storage; try { storage = window[type]; var x = '__storage_test__'; storage.setite...
...we can use localstorage awesomeness } else { // too bad, no localstorage for us } ...
...we can use localstorage awesomeness } else { // too bad, no localstorage for us } you can test for sessionstorage instead by calling storageav...
... see here for a brief history of feature-d...
Worker - Web APIs
ns.) in firefox extensions, if you want to use workers with access to js-ctypes, use chromeworker object instead. constructors worker() creates a dedicated web worker that executes the script at the specified url. this also works for blob urls. properties inherits properties from its parent, eventtarget, and implements properties from abstractworker. event handlers abstractworker.on
error an eventlistener called whenever an
errorevent of type
error bubbles through to the worker. this is inherited from abstractworker. worker.onmessage an eventlistener called whenever a messageevent of type message bubbles through the worker — i.e. when a message is sent to the parent document from the worker via dedicatedworkerglobalscope.postmessage. the message is stored in the event's data ...
... methods inherits methods from its parent, eventtarget, and implements methods from abstractworker. worker.postmessage() sends a message — consisting of any javascript object — to the worker's inner scope. worker.terminate() immediately terminates the worker. ...
...herited from abstractworker. worker.onmessage an eventlistener called whenever a messageevent of type message bubbles through the worker — i.e. when a message is sent to the parent document from the worker via dedicatedworkerglobalscope.postmessage. the message is stored in the event's data property. worker.onmessage
error is an eventhandler representing the code to be called when the message
error event is raised. methods inherits methods from its parent, eventtarget, and implements methods from abstractworker. worker.postmessage() sends a message — consisting of any javascript object — to the worker's inner scope. worker.terminate() immediately terminates the worker. this does not let worker finish its operations; it is halted at once. serviceworker instances do not suppor...
...message — consisting of any javascript object — to the worker's inner scope. worker.terminate() immediately terminates the worker. this does not let worker finish its operations; it is halted at once. serviceworker instances do not support this method. events message fires when the worker's parent receives a message from that worker. also available via the onmessage property. message
error fires when a worker object receives a message that can't be deserialized. also available via the onmessage
error property. rejectionhandled fires every time a promise rejects, regardless of whether or not there is a handler to catch the rejection. also available through the onrejectionhandled event handler property. unhandledrejection fires when a promise rejects with no handler to catch...
XDomainRequest - Web APIs
ecifing the method (get/post) and url. xdomainrequest.send() sends the request. post data is specified in this method. xdomainrequest.abort() aborts the request. event handlers xdomainrequest.onprogress a handler for when the request has made progress between the send method call and the onload event. xdomainrequest.ontimeout a handler for when the request times out. ...
...xdomainrequest.send() sends the request. post data is specified in this method. xdomainrequest.abort() aborts the request. event handlers xdomainrequest.onprogress a handler for when the request has made progress between the send method call and the onload event. xdomainrequest.ontimeout a handler for when the request times out. xdomainrequest.on
error a handler for when a request has
errored. ...
...omainrequest.on
error a handler for when a request has
errored. xdomainrequest.onload a handler for when the full response has been received from the server. example if(window.xdomainrequest){ var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); xdr.onprogress = function () { //progress }; xdr.ontimeout = function () { //timeout }; xdr.on
error = function () { //
error occurred }; xdr.onload = function() { //success(xdr.responsetext); } settimeout(function () { xdr.send(); }, 0); } note: the xdr.send() call is wrapped in a timeout (see window.settimeout() to prevent an issue with the interface where some requests are lost if multiple xdomainrequests are being sent at the same time. note: the xdr.onprogress ev...
...ts are being sent at the same time. note: the xdr.onprogress event should always be defined, even as an empty function, or xdomainrequest may not fire onload for duplicate requests. security the xdomainrequest is built to be secure in multiple ways. the origin's security protocol must match that of the requested url. (http to http, https to https). if these do not match, the request will
error "access is denied". the requested url's server must have the access-control-allow-origin header set to either all ("*") or to include the origin of the request. specifications this interface and its methods are non-standard. ...
XMLHttpRequest: abort event - Web APIs
n a request has been aborted, for example because the program called xmlhttprequest.abort(). ...
...am called xmlhttprequest.abort(). ...
... class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbutton
error = document.queryselector('.xhr.
error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); ...
...queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('
error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbutton
error.addeventliste...
XMLHttpRequest: load event - Web APIs
the load event is fired when an xmlhttprequest transaction completes successfully. ...
...ransaction completes successfully. ...
... class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbutton
error = document.queryselector('.xhr.
error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); ...
...queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('
error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbutton
error.addeventliste...
XMLHttpRequest: loadstart event - Web APIs
the loadstart event is fired when a request has started to load data. ...
...est has started to load data. ...
... class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbutton
error = document.queryselector('.xhr.
error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); ...
...queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('
error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbutton
error.addeventliste...
XMLHttpRequest: progress event - Web APIs
the progress event is fired periodically when a request receives more data. ...
... a request receives more data. ...
... class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbutton
error = document.queryselector('.xhr.
error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); ...
...queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('
error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbutton
error.addeventliste...
Getting Started - Developer guides
tp standard, otherwise some browsers (like firefox) might not process the request. for more information on the possible http request methods, check the w3c specs. the second parameter is the url you're sending the request to. as a security feature, you cannot call urls on 3rd-party domains by default. be sure to use the exact domain name on all of your pages or you will get a "permission denied"
error when you call open(). a common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld. if you really need to send a request to another domain, see http access control (cors). the optional third parameter sets whether the request is asynchronous. if true (the default), javascript execution will continue and the user can interact with the page while the serv...
...us codes of the http response. the possible codes are listed at the w3c. in the following example, we differentiate between a successful and unsuccessful ajax call by checking for a 200 ok response code. if (httprequest.status === 200) { // perfect! } else { // there was a problem with the request. // for example, the response may have a 404 (not found) // or 500 (internal server
error) response code. } after checking the state of the request and the http status code of the response, you can do whatever you want with the data the server sent. you have two options to access that data: httprequest.responsetext – returns the server response as a string of text httprequest.responsexml – returns the response as an xmldocument object you can traverse with javascript dom fun...
...o alertcontents(); alertcontents() checks if the response was received and ok, then alert()s the contents of the test.html file. note: if you're sending a request to a piece of code that will return xml, rather than a static html file, you must set response headers to work in internet explorer. if you do not set header content-type: application/xml, ie will throw a javascript "object expected"
error after the line where you tried to access an xml element. note 2: if you do not set header cache-control: no-cache the browser will cache the response and never re-submit the request, making debugging challenging. you can also add an always-different get parameter, like a timestamp or random number (see bypassing the cache) note 3: if the httprequest variable is used globally, competing function...
...lenging. you can also add an always-different 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); } el...
spellcheck - HTML: Hypertext Markup Language
note: the spellcheck attribute is an enumerated one and not a boolean one. ...
... note: the spellcheck attribute is an enumerated one and not a boolean one. this means that the explicit usage of one of the values true or false is mandatory, and that a shorthand like <textarea spellcheck></textarea> is not allowed. ...
... note: the spellcheck attribute is an enumerated one and not a boolean one. ...
...the explicit usage of one of the values true or false is mandatory, and that a shorthand like <textarea spellcheck></textarea> is not allowed. the correct usage is <textarea spellcheck="true"></textarea>. if this attribute is not set, its default value is element-type and browser-defined. this default value may also be inherited, which means that the element content will be checked for spelling
errors only if its nearest ancestor has a spellcheck state of true. this attribute is merely a hint for the browser: browsers are not required to check for spelling
errors. typically non-editable elements are not checked for spelling
errors, even if the spellcheck attribute is set to true and the browser supports spellchecking. specifications specification status comment ...
Large-Allocation - HTTP
header type response header forbidden header name no syntax large-allocation: 0 large-allocation: <megabytes> directives 0 0 is a special value which represents uncertainty as to what the size of the allocation is. <megabytes> the expected size of the allocation to be performed, in megabytes. examples large-allocation: 0 large-allocation: 500 troubleshooting
errors the large-allocation header throws warnings or
error messages when used incorrectly. you'll encounter them in the web console. this page was loaded in a new process due to a large-allocation header. this message means that the browser saw the large-allocation header, and was able to reload the page into a new process which should have more available contiguous memory. a large-allocation he...
...allocation header. this message means that the browser saw the large-allocation header, and was able to reload the page into a new process which should have more available contiguous memory. a large-allocation header was ignored due to the load being triggered by a non-get request. when a post request is used to load a document, that load cannot currently be redirected into a new process. ...
...it can occur in these situations: the document with the large-allocation header was loaded in an <iframe>. firefox cannot move an iframe into a new process currently, so the document must load in the current process. ...
...ot handle the large-allocation header. this page would be loaded in a new process due to a large-allocation header, however large-allocation process creation is disabled on non-win32 platforms. firefox currently only supports the large-allocation header in our 32-bit windows builds, as memory fragmentation is not an issue in 64-bit builds. if you are running a non-win32 version of firefox, this
error will appear. this check can be disabled with the "dom.largeallocation. forceenable" boolean preferece in about:config. specifications not part of any current specifications. an explainer of the ideas behind this header can be found in this document. ...
Private class fields - JavaScript
tatic fields. only the class which defines the private static field can access the field. this can lead to unexpected behaviour when using this. class baseclasswithprivatestaticfield { static #private_static_field static basepublicstaticmethod() { this.#private_static_field = 42 return this.#private_static_field } } class subclass extends baseclasswithprivatestaticfield { } let
error = null try { subclass.basepublicstaticmethod() } catch(e) {
error = e} console.assert(
error instanceof type
error) private instance fields private instance fields are declared with # names (pronounced "hash names"), which are identifiers prefixed with #. the # is a part of the name itself. it is used for declaration and accessing as well. the encapsulation is enforced by the language. it i...
...y { subclass.basepublicstaticmethod() } catch(e) {
error = e} console.assert(
error instanceof type
error) private instance fields private instance fields are declared with # names (pronounced "hash names"), which are identifiers prefixed with #. the # is a part of the name itself. it is used for declaration and accessing as well. the encapsulation is enforced by the language. it is a syntax
error to refer to # names from out of scope. ...
...# names (pronounced "hash names"), which are identifiers prefixed with #. the # is a part of the name itself. it is used for declaration and accessing as well. the encapsulation is enforced by the language. it is a syntax
error to refer to # names from out of scope. class classwithprivatefield { #privatefield constructor() { this.#privatefield = 42 this.#randomfield = 666 // syntax
error } } const instance = new classwithprivatefield() instance.#privatefield === 42 // syntax
error private methods private static methods like their public equivalent, private static methods are called on the class itself, not instances of the class. like private static fields, they are only accessible from inside the class declaration. private static methods may be generator, async, and asyn...
... class classwithprivatemethod { #privatemethod() { return 'hello world' } getprivatemessage() { return this.#privatemethod() } } const instance = new classwithprivatemethod() console.log(instance.getprivatemessa...
Classes - JavaScript
"rectangle" here). class rectangle { constructor(height, width) { this.height = height; this.width = width; } } hoisting an important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. you first need to declare your class and then access it, otherwise code like the following will throw a reference
error: const p = new rectangle(); // reference
error class rectangle {} class expressions a class expression is another way to define a class. class expressions can be named or unnamed. the name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) name property, though). // unnamed let rectangle = class { constructor(height,...
...ng restrictions as described in the class declarations section. class body and method definitions the body of a class is the part that is in curly brackets {}. this is where you define class members, such as methods or constructor. strict mode the body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent
errors will be thrown, and certain keywords are reserved for future versions of ecmascript. constructor the constructor method is a special method for creating and initializing an object created with a class. there can only be one special method with the name "constructor" in a class. a syntax
error will be thrown if the class contains more than one occurrence of a constructor method. a constructor c...
...enting, and the fields are always present. as seen above, the fields can be declared with or without a default value. see public class fields for more information. private field declarations using private fields, the definition can be refined as below. class rectangle { #height = 0; #width; constructor(height, width) { this.#height = height; this.#width = width; } } it's an
error to reference private fields from outside of the class; they can only be read or written within the class body. by defining things which are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may change version to version. private fields can only be declared up-front in a field declaration. private fields cannot be created later through assig...
... method takes precedence over parent's method note that classes cannot extend regular (non-constructible) objects. if you want to inherit from a regular object, you can instead use object.setprototypeof(): const animal = { speak() { console.log(`${this.name} makes a noise.`); } }; class dog { constructor(name) { this.name = name; } } // if you do not do this you will get a type
error when you invoke speak object.setprototypeof(dog.prototype, animal); let d = new dog('mitzie'); d.speak(); // mitzie makes a noise. species you might want to return array objects in your derived array class myarray. the species pattern lets you override default constructors. for example, when using methods such as map() that returns the default constructor, you want these methods to return a ...
Array.prototype.reduceRight() - JavaScript
xoptional the index of the current element being processed in the array. arrayoptional the array reduceright() was called upon. initialvalueoptional value to use as accumulator to the first call of the callback. if no initial value is supplied, the last element in the array will be used and skipped. calling reduce or reduceright on an empty array without an initial value creates a type
error. return value the value that results from the reduction. description reduceright executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring. the call to the r...
...f two values. if an initialvalue was provided in the call to reduceright, then accumulator will be equal to initialvalue and currentvalue will be equal to the last value in the array. if no initialvalue was provided, then accumulator will be equal to the last value in the array and currentvalue will be equal to the second-to-last value. if the array is empty and no initialvalue was provided, type
error would be thrown. if the array has only one element (regardless of position) and no initialvalue was provided, or if initialvalue is provided but the array is empty, the solo value would be returned without calling callback. some example run-throughs of the function would look like this: [0, 1, 2, 3, 4].reduceright(function(accumulator, currentvalue, index, array) { return accumulator + curren...
...ng use of reduceright in implementations which do not natively support it. ...
... // reference: http://es5.github.io/#x15.4.4.22 if ('function' !== typeof array.prototype.reduceright) { array.prototype.reduceright = function(callback /*, initialvalue*/) { 'use strict'; if (null === this || 'undefined' === typeof this) { throw new type
error('array.prototype.reduce called on null or undefined'); } if ('function' !== typeof callback) { throw new type
error(callback + ' is not a function'); } var t = object(this), len = t.length >>> 0, k = len - 1, value; if (arguments.length >= 2) { value = arguments[1]; } else { while (k >= 0 && !(k in t)) { k--; } if (k < 0) { throw new type
error('reduce of empty array with no initial value'); } value = t[k--]; } for (; k >= 0; k--) { ...
Array.from() - JavaScript
ecma-262 standard in the 6th edition (es2015). as such, it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of array.from() in implementations that don't natively support it. polyfill notes: this algorithm is exactly as specified in ecma-262 6th edition (assuming object and type
error have their original values and that callback.call() evaluates to the original value of function.prototype.call()). in addition, since true iterables cannot be polyfilled, this implementation does not support generic iterables as defined in the 6th edition of ecma-262. // production steps of ecma-262, edition 6, 22.1.2.1 if (!array.from) { array.from = (function () { var symbolitera...
... return function from(arraylikeoriterator /*, mapfn, thisarg */) { // 1. let c be the this value. ...
...n, thisarg */) { // 1. let c be the this value. var c = this; // 2. let items be toobject(arraylikeoriterator). var items = object(arraylikeoriterator); var isiterator = iscallable(items[symboliterator]); // 3. returnifabrupt(items). if (arraylikeoriterator == null && !isiterator) { throw new type
error( 'array.from requires an array-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 i...
... an array-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 type
error exception. if (!iscallable(mapfn)) { throw new type
error( '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[...
Generator.prototype.throw() - JavaScript
return value an object with two properties: done (boolean) has the value true if the iterator is past the end of the iterated sequence. in this case value optionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. ...
...is case value optionally specifies the return value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. can be omitted when done is true. ...
...lue of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value returned by the iterator. can be omitted when done is true. examples using throw() the following example shows a simple generator and an
error that is thrown using the throw method. an
error can be caught by a try...catch block as usual. ...
... done property altogether. value any javascript value returned by the iterator. can be omitted when done is true. examples using throw() the following example shows a simple generator and an
error that is thrown using the throw method. an
error can be caught by a try...catch block as usual. function* gen() { while(true) { try { yield 42; } catch(e) { console.log('
error caught!'); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(new
error('something went wrong')); // "
error caught!" // { value: 42, done: false } specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.throw' in that specification. ...
JSON.parse() - JavaScript
arse(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 syntax
error 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 = /(?:^|:|,)(?:\s*\[)+/g; ...
...); // in the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. ...
...stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return (typeof reviver === "function") ? walk({ "": j }, "") : j; } // if the text is not json parseable, then a syntax
error is thrown. throw new syntax
error("json.parse"); }; } examples using json.parse() json.parse('{}'); // {} json.parse('true'); // true json.parse('"foo"'); // "foo" json.parse('[1, 5, "false"]'); // [1, 5, "false"] json.parse('null'); // null using the reviver parameter if a reviver is specified, the value computed by parsing is transformed before being returned. specifically,...
...mbers : value // return everything else unchanged ); // { p: 10 } json.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => { console.log(key); // log the current property name, the last is "". return value; // return the unchanged property value. }); // 1 // 2 // 4 // 6 // 5 // 3 // "" json.parse() does not allow trailing commas // both will throw a syntax
error json.parse('[1, 2, 3, 4, ]'); json.parse('{"foo" : 1, }'); json.parse() does not allow single quotes // will throw a syntax
error json.parse("{'foo': 1}"); specifications specification ecmascript (ecma-262)the definition of 'json.parse' in that specification. ...
JSON.stringify() - JavaScript
pped 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 type
error ("cyclic object value") exception when a circular reference is found. throws a type
error ("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 string objects are con...
... as a function, it takes two parameters: the key and the value being stringified. the object in which the key was found is provided as the replacer's this parameter. initially, the replacer function is called with an empty string as key representing the object being st...
...ngify(obj); // '{"data":"data"}' json.stringify({ obj }); // shorthand property names (es2015). // '{"obj":"now i am a nested object under key 'obj'"}' json.stringify([ obj ]); // '["now i am a nested object under key '0'"]' issue with json.stringify() when serializing circular references note that since the json format doesn't support object references (although an ietf draft exists), a type
error will be thrown if one attempts to encode an object with circular references. const circularreference = {}; circularreference.myself = circularreference; // serializing circular references throws "type
error: cyclic object value" json.stringify(circularreference); to serialize circular references you can use a library that supports them (e.g. cycle.js by douglas crockford) or implement a soluti...
...unction or as part of a jsonp url, and the following utility can be used: function jsfriendlyjsonstringify (s) { return json.stringify(s). replace(/\u2028/g, '\\u2028'). replace(/\u2029/g, '\\u2029'); } var s = { a: string.fromcharcode(0x2028), b: string.fromcharcode(0x2029) }; try { eval('(' + json.stringify(s) + ')'); } catch (e) { console.log(e); // "syntax
error: unterminated string literal" } // no need for a catch eval('(' + jsfriendlyjsonstringify(s) + ')'); // console.log in firefox unescapes the unicode if // logged to console, so we use alert alert(jsfriendlyjsonstringify(s)); // {"a":"\u2028","b":"\u2029"} note: properties of non-array objects are not guaranteed to be stringified in any particular order. do not rely on ordering of propertie...
Object.prototype.constructor - JavaScript
owing example shows how to modify the constructor value of generic objects. only true, 1, and "test" will not be affected (as they have read-only native constructors). this example shows that it is not always safe to rely on the constructor property of an object. ...
... // new array() function type() {},false, // [] function type() {},false,false // new boolean() function boolean() { [native code] },false,true // true function type() {},false,mon sep 01 2014 16:03:49 gmt+0600 // new date() function type() {},false,
error // new
error() function type() {},false,function anonymous() { } // new function() function type() {},false,function () {} // function () {} function type() {},false,[object math] // math function type() {},false,0 // new numbe...
...uperfluous line of code. take the following case: the object has the create() method to 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() // type
error 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.constru...
...child = object.assign(parentwithstatic) // notice that we assign it before we create(.
Object.preventExtensions() - JavaScript
properties can be added to it. object.preventextensions() marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. note that the properties of a non-extensible object, in general, may still be deleted. attempting to add new properties to a non-extensible object will fail, either silently or by throwing a type
error (most commonly, but not exclusively, when in strict mode). object.preventextensions() only prevents addition of own properties. properties can still be added to the object prototype. this method makes the [[prototype]] of the target immutable; any [[prototype]] re-assignment will throw a type
error. this behavior is specific to the internal [[prototype]] property, other properties of the targe...
...ject.isextensible(empty); // === true // ...but that can be changed. object.preventextensions(empty); object.isextensible(empty); // === false // object.defineproperty throws when adding // a new property to a non-extensible object. var nonextensible = { removable: true }; object.preventextensions(nonextensible); object.defineproperty(nonextensible, 'new', { value: 8675309 }); // throws a type
error // in strict mode, attempting to add new properties // to a non-extensible object throws a type
error. function fail() { 'use strict'; // throws a type
error nonextensible.newproperty = 'fail'; } fail(); a non-extensible object's prototype is immutable: var fixed = object.preventextensions({}); // throws a 'type
error'. fixed.__proto__ = { oh: 'hai' }; non-object coercion in es5, if the ...
...ct throws a type
error. function fail() { 'use strict'; // throws a type
error nonextensible.newproperty = 'fail'; } fail(); a non-extensible object's prototype is immutable: var fixed = object.preventextensions({}); // throws a 'type
error'. fixed.__proto__ = { oh: 'hai' }; non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return it. ...
...rototype is immutable: var fixed = object.preventextensions({}); // throws a 'type
error'. fixed.__proto__ = { oh: 'hai' }; non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return it. object.preventextensions(1); // type
error: 1 is not an object (es5 code) object.preventextensions(1); // 1 (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.preventextensions' in that specification. ...
handler.setPrototypeOf() - JavaScript
turn value the setprototypeof() method returns true if the [[prototype]] was successfully changed, otherwise false. description the handler.setprototypeof() method is a trap for object.setprototypeof(). interceptions this trap can intercept these operations: object.setprototypeof() reflect.setprototypeof() invariants if the following invariants are violated, the proxy will throw a type
error: 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 ...
...t). 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 type
error 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. const handlerreturnsfalse = { setprototypeof(target, newproto) { return false; } }; const newproto = {}, target = {}; const p1 = new proxy(target, handlerreturnsfalse); object.setprototypeof(p1, newproto); // thro...
... 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. ...
...s a type
error 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, handlerthrows); object.setprototypeof(p2, newproto); // throws new
error("custom
error") reflect.setprototypeof(p2, newproto); // throws new
error("custom
error") specifications specification ecmascript (ecma-262)the definition of '[[setprototypeof]]' in that specification. ...
TypedArray.from() - JavaScript
that the following are equivalent: typedarray.from(obj, mapfn, thisarg) typedarray.from(array.prototype.map.call(obj, mapfn, thisarg)). the length property of the from() method is 1. differences from array.from() some subtle distinctions between array.from() and typedarray.from(): if the thisarg value passed to typedarray.from() is not a constructor, typedarray.from() will throw a type
error, where array.from() defaults to creating a new array. typedarray.from() uses [[put]] where array.from() uses [[defineproperty]]. hence, when working with proxy objects, it calls handler.set to create new elements rather than handler.defineproperty(). when the source parameter is an iterator, the typedarray.from() first collects all the values from the iterator, then creates an instance of thisa...
...owing code at the beginning of your scripts, allowing use of much of the functionality of from() in implementations that do not natively support it. ...
...ively support it. ...
...function') { throw new type
error('# is not a constructor'); } if (this.__proto__ !== typedarrayclass) { throw new type
error('this is not a typed array.'); } func = func || function (elem) { return elem; }; if (typeof func !== 'function') { throw new type
error('specified argument is not a function'); } obj = object(obj); if (!obj['length']) { return new this(0); } var copy_data = []; for(var i = 0; i < obj.length; i++) { copy_data.push(obj[i]); } copy_data = copy_data.map(func, thisobj); var typed_array = new th...
delete operator - JavaScript
sion 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 type
error 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 operator removes a given p...
...le.log(delete employee.name); // returns true console.log(delete employee.age); // returns true // when trying to delete a property that does // not exist, true is returned console.log(delete employee.salary); // returns true non-configurable properties when a property is marked as non-configurable, delete won't have any effect, and will return false. in strict mode this will raise a type
error. var employee = {}; object.defineproperty(employee, 'name', {configurable: false}); console.log(delete employee.name); // returns false var, let, and const create non-configurable properties that cannot be deleted with the delete operator: var nameother = 'xyz'; // we can access this global property using: object.getownpropertydescriptor(window, 'nameother'); // output: object {value: "xy...
...ue, // 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 syntax
error. 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: true, }); object.defineproperty(globalthis, 'variable2', { value: 10, configurable: false, }); // syntax
error in strict mode. console.log(delete variable1); // true // sy...
...erefore, 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: true, }); object.defineproperty(globalthis, 'variable2', { value: 10, configurable: false, }); // syntax
error in strict mode. console.log(delete variable1); // true // syntax
error in strict mode. console.log(delete variable2); // false function func(param) { // syntax
error in strict mode. console.log(delete param); // false } // syntax
error in strict mode. console.log(delete func); // false cross-browser notes although ecmascript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on th...
WebAssembly
ing and instantiating webassembly code, returning both a module and its first instance. webassembly.memory() a webassembly.memory object is a resizable arraybuffer that holds the raw bytes of memory accessed by an instance. webassembly.table() a webassembly.table object is a resizable typed array of opaque values, like function references, that are accessed by an instance. webassembly.compile
error() creates a new webassembly compile
error object. webassembly.link
error() creates a new webassembly link
error object. webassembly.runtime
error() creates a new webassembly runtime
error object. examples wasmsobel see our webassembly-examples repo for a number of other examples. specifications specification status comment webassembly javascript interface ...
... 52notes notes disabled in the firefox 52 extended support release (esr).opera android full support 43safari ios full support 11samsung internet android full support 7.0nodejs full support 8.0.0compile
errorchrome full support 57edge full support 16firefox full support 52notes full support 52notes notes disabled in the firefox 52 extended support release (esr).ie no support noop...
... 52notes notes disabled in the firefox 52 extended support release (esr).opera android full support 43safari ios full support 11samsung internet android full support 7.0nodejs full support 8.0.0link
errorchrome full support 57edge full support 16firefox full support 52notes full support 52notes notes disabled in the firefox 52 extended support release (esr).ie no support noop...
... 52notes notes disabled in the firefox 52 extended support release (esr).opera android full support 43safari ios full support 11samsung internet android full support 7.0nodejs full support 8.0.0runtime
errorchrome full support 57edge full support 16firefox full support 52notes full support 52notes notes disabled in the firefox 52 extended support release (esr).ie no support noop...
content/worker - Archive of obsolete content
oaded before those specified by the contentscript option. optional. contentscript string,array the texts of content scripts to load. content scripts specified by this option are loaded after those specified by the contentscriptfile option. optional. onmessage function functions that will registered as a listener to a 'message' events. on
error function functions that will registered as a listener to an '
error' events. worker worker is composed from the eventemitter trait, therefore instances of worker and their descendants expose all the public properties exposed by eventemitter along with additional public properties that are listed below. methods postmessage(data) asynchronously emits "message" events in the...
...d to a content document, returns the related tab. events message this event allows the content worker to receive messages from its associated content scripts. calling the self.postmessage() function from a content script will asynchronously emit the message event on the corresponding worker. arguments value : the event listener is passed the message, which must be a json-serializable value.
error this event allows the content worker to react to an uncaught runtime script
error that occurs in one of the content scripts. arguments
error : the event listener is passed a single argument which is an
error object. detach this event is emitted when the document associated with this worker is unloaded or the worker's destroy() method is called. note that you can't communicate with the conte...
...ntime script
error that occurs in one of the content scripts. arguments
error : the event listener is passed a single argument which is an
error object. detach this event is emitted when the document associated with this worker is unloaded or the worker's destroy() method is called. note that you can't communicate with the content script in response to this event. if you try, you'll see this
error:
error: couldn't find the worker to receive this message. the script may not be initialized yet, or may already have been unloaded you can handle the detach event in the content script itself though: // in content script self.port.on("detach", function() { window.close(); }); ...
places/bookmarks - Archive of obsolete content
roperties group the group instance that the bookmark group lives under. index the index of the bookmark group within its group. updated a unix timestamp indicating when the bookmark was last updated on the platform. placesemitter the placesemitter is not exported from the module, but returned from the save and search functions. the placesemitter inherits from event/target, and emits data,
error, and end. data events are emitted for every individual operation (such as: each item saved, or each item found by a search query), whereas end events are emitted as the aggregate of an operation, passing an array of objects into the handler. events data the data event is emitted when a bookmark item that was passed into the save method has been saved to the platform. this includes implicit sa...
...ark item that matches the query will // be called in this function }); arguments bookmark|group|separator : for the save function, this is the saved, latest snapshot of the bookmark item. for search, this is a snapshot of a bookmark returned from the search query. bookmark|group|separator|object : only in save data events. the initial instance of the item that was used for the save request.
error the
error event is emitted whenever a bookmark item's save could not be completed. arguments string : a string indicating the
error that occurred. bookmark|group|separator|object : only in save
error events. the initial instance of the item that was used for the save request. end the end event is called when all bookmark items and dependencies have been saved, or an aggregate of all items r...
...instance of the item that was used for the save request. end the end event is called when all bookmark items and dependencies have been saved, or an aggregate of all items returned from a search query. arguments array : the array is an ordered list of the input bookmark items, replaced with their updated, latest snapshot instances (the first argument in the data handler), or in the case of an
error, the initial instance of the item that was used for the save request (the second argument in the data or
error handler). see also using xpcom without chrome - bookmark observer ...
places/history - Archive of obsolete content
access the user's browsing history. usage this module exports a single function, search(), which synchronously returns a placesemitter object which then asynchronously emits data and end or
error events that contain information about the state of the operation. example let { search } = require("sdk/places/history"); // simple query search( { url: "https://developers.mozilla.org/*" }, { sort: "visitcount" } ).on("end", function (results) { // results is an array of objects containing // data about visits to any site on developers.mozilla.org // ordered by visit count }); // complex query // the query objects are or'd together // let's say we want to retrieve all visits from before a week ago // with the query of 'ruby', but from last week onwards, we want // all results with '...
... 'url', 'visitcount', 'keyword', 'dateadded' and 'lastmodified'. descending boolean a boolean specifying whether the results should be in descending order. by default, results are in ascending order. placesemitter the placesemitter is not exposed in the module, but returned from the search functions. the placesemitter inherits from event/target, and emits data,
error, and end. data events are emitted for every individual search result found, whereas end events are emitted as an aggregate of an entire search, passing in an array of all results into the handler. events data the data event is emitted for every item returned from a search. arguments object : this is an object representing a history entry. contains url, time, accesscount and title of the entr...
...d end. data events are emitted for every individual search result found, whereas end events are emitted as an aggregate of an entire search, passing in an array of all results into the handler. events data the data event is emitted for every item returned from a search. arguments object : this is an object representing a history entry. contains url, time, accesscount and title of the entry.
error the
error event is emitted whenever a search could not be completed. arguments string : a string indicating the
error that occurred. end the end event is called when all search results have returned. arguments array : the value passed into the handler is an array of all entries found in the history search. each entry is an object containing the properties url, time, accesscount and title. ...
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. ...
...acktrace; 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 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. pa...
...
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. ...
cfx - Archive of obsolete content
nformation. -b binary, --binary=binary use the host application binary specified in binary. binary may be specified as a full path or as a path relative to the current directory. --binary-args=cmdargs pass extra arguments to the binary being executed (for example, firefox). for example, to pass the -jsconsole argument to firefox, which will launch the javascript
error console, try the following: cfx run --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --extra-packages=extra_packages extra packages to include, specified as a comma-separated list of package names. -g config, --use-config=config pass a set of optio...
...iple times. -b binary, --binary=binary use the host application binary specified in binary. binary may be specified as a full path or as a path relative to the current directory. --binary-args=cmdargs pass extra arguments to the binary being executed (for example, firefox). for example, to pass the -jsconsole argument to firefox, which will launch the javascript
error console, try the following: cfx run --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --dependencies load and run any tests that are included with modules that your package depends on. for example: if your add-on depends on modules from the sdk, then cfx wi...
...ag is set and the add-on includes its own copies of the sdk modules, then the add-on will use the sdk modules in the add-on, not the ones built into firefox. this flag is particularly useful for sdk developers or people working with the development version of the sdk, who may want to run an add-on using newer versions of the modules than than those shipping in firefox. --stop-on-
error stop running tests after the first failure. internal options --addons=addons paths of add-ons to install, comma-separated. addons may be specified as full paths or relative to the current directory. --e10s if this option is set then the add-on runs in a separate process. this option is currently not implemented. --keydir=keydir supply a different loc...
Boxes - Archive of obsolete content
s if you put image in the contents, you should probably add align="start" attribute to the box. ...
...the box. ...
...t href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <box align="start" style="display:block"> <image src="chrome://global/skin/icons/
error.png" style="padding:5px"/> <textbox /> <image src="chrome://global/skin/icons/
error.png" style="padding:5px"/> <button label="hello"/> <image src="chrome://global/skin/icons/
error.png" style="padding:5px"/> </box> </window> ...
Preferences - Archive of obsolete content
ed, it does the following: checks whether the current tree has a value for the preference and whether or not the preference is locked. if there's a value of the 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_e...
...ce, 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 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 ...
...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"] .getservice(components.interfaces.nsiprefservice); prefservice.savepreffile(null); checking for existence of a key if you try to get the value of a nonexistent preference, an
error will be thrown:
error: ns_
error_unexpected: component returned failure code: 0x8000ffff (ns_
error_unexpected) [nsiprefbranch.getcharpref] to avoid such
errors, you should check whether the key exists or not using nsiprefservice.getpreftype(), as shown below: var prefservicebranch = components.classes["@mozilla.org/preferences-service;1"] .getservice(components...
JavaScript Daemons Management - Archive of obsolete content
se, version 3 or later. ...
...epending on your needs. if you want to remove them and are using the daemon.safe subsystem you * should also remove the daemon.safe global object methods that require them. ...
...use daemon.prototype.adaptlength()."); } if (ntime > 0) { this.rate = math.floor(ntime / this.length); this.synchronize(); } return this.rate; }; daemon.prototype.adaptlength = function (ntime) { this.length = math.floor(ntime / this.rate); return this.length; }; daemon.prototype.playuntil = fu...
Tabbed browser - Archive of obsolete content
of a browser.xul overlay. finally, use gbrowser.browsers.length to get the number of browsers and gbrowser.getbrowseratindex() to get a <browser/> element. for example: var num = gbrowser.browsers.length; for (var i = 0; i < num; i++) { var b = gbrowser.getbrowseratindex(i); try { dump(b.currenturi.spec); // dump urls of all open tabs to console } catch(e) { components.utils.report
error(e); } } to learn what methods are available for <browser/> and <tabbrowser/> elements, use dom inspector or look in browser.xml for corresponding xbl bindings (or just look at the current reference pages on browser and tabbrowser. getting the browser that fires the http-on-modify-request notification see the observer notifications page for information on http-on-* notifications. note that s...
...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: functi...
...ttpchannel); if (goodies) { httpchannel.cancel(cr.ns_binding_aborted); goodies.contentwindow.location = self.data.url('pages/test.html'); } else { //dont do anything as there is no contentwindow associated with the httpchannel, liekly a google ad is loading or some ajax call or something, so this is not an
error } } return; } } }; services.obs.addobserver(httprequestobserver, "http-on-modify-request", false); //this function gets the contentwindow and other good stuff from loadcontext of httpchannel function loadcontextgoodies(httpchannel) { //httpchannel must be the subject of http-on-modify-request qi'ed to nsihttpchannel as is done on line ...
Locked config settings - Archive of obsolete content
mozilla.cfg, which means that these cannot be locked. if you have trouble getting the moz-byteshift.pl script to work locally, there is also an online version available. note: in recent versions of mozilla (tested on windows and linux, with 1.5, 1.6 and 1.7b), the mozilla.cfg file needs to be placed in mozilla's root directory, rather than default\pref where all.js resides. ...
... if you have trouble getting the moz-byteshift.pl script to work locally, there is also an online version available. note: in recent versions of mozilla (tested on windows and linux, with 1.5, 1.6 and 1.7b), the mozilla.cfg file needs to be placed in mozilla's root directory, rather than default\pref where all.js resides. ...
...nline version available. note: in recent versions of mozilla (tested on windows and linux, with 1.5, 1.6 and 1.7b), the mozilla.cfg file needs to be placed in mozilla's root directory, rather than default\pref where all.js resides. if you suspect syntax
errors in your config file, you can display the exact
error message by enclosing your code in a try-catch block: try { ... ...
Using Dehydra - Archive of obsolete content
*/ function isfinal(c) { if (!c.attributes) return false; for each (let a in c.attributes) if (a.name == 'user' && a.value == 'final') return true; return false; } function process_type(t) { if (t.bases) ...
...pt final.js: /** * helper function: returns true if a class is marked with the "final" attribute. ...
...rue; return false; } function process_type(t) { if (t.bases) for each (let base in t.bases) if (isfinal(base.type))
error("class " + t.name + " extends final class " + base.type.name, t.loc); } compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/final.js -o/dev/null -c final.cc it should print the following results and return with an
error code: final.cc:8:
error: class subclass extends final class myclass see documentation for: process_type,
error, .bases property, .attributes property ...
jspage - Archive of obsolete content
[c])){case"object":var d=function(){};d.prototype=a[c];var b=new d;a[c]=object.reset(b);break;case"array":a[c]=$unlink(a[c]); break;}return a;};new native({name:"class",initialize:class}).extend({instantiate:function(b){b._prototyping=true;var a=new b;delete b._prototyping;return a; },wrap:function(a,b,c){if(c._origin){c=c._origin;}return function(){if(c._protected&&this._current==null){throw new
error('the method "'+b+'" cannot be called.'); }var e=this.caller,f=this._current;this.caller=f;this._current=arguments.callee;var d=c.apply(this,arguments);this._current=f;this.caller=e;return d;}.extend({_owner:a,_origin:c,_name:b}); }});class.implement({implement:function(a,d){if($type(a)=="object"){for(var e in a){this.implement(e,a[e]);}return this;}var f=class.mutators[a];if(f){d=f.call(this,d); ...
...rn this;}c[a]=class.wrap(this,a,d);break;case"object":var b=c[a]; if($type(b)=="object"){$mixin(b,d);}else{c[a]=$unlink(d);}break;case"array":c[a]=$unlink(d);break;default:c[a]=d;}return this;}});class.mutators={extends:function(a){this.parent=a; this.prototype=class.instantiate(a);this.implement("parent",function(){var b=this.caller._name,c=this.caller._owner.parent.prototype[b];if(!c){throw new
error('the method "'+b+'" has no parent.'); }return c.apply(this,arguments);}.protect());},implements:function(a){$splat(a).each(function(b){if(b instanceof function){b=class.instantiate(b);}this.implement(b); },this);}};var chain=new class({$chain:[],chain:function(){this.$chain.extend(array.flatten(arguments));return this;},callchain:function(){return(this.$chain.length)?this.$chain.shift().apply(thi...
....keys.each(function(e){this.addevent(a,e);},this);}}return this;}});element.nativeevents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,dommousescroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,domcontentloaded:1,readystatechange:1,
error:1,abort:1,scroll:1}; (function(){var a=function(b){var c=b.relatedtarget;if(c==undefined){return true;}if(c===false){return false;}return($type(this)!="document"&&c!=this&&c.prefix!="xul"&&!this.haschild(c)); };element.events=new hash({mouseenter:{base:"mouseover",condition:a},mouseleave:{base:"mouseout",condition:a},mousewheel:{base:(browser.engine.gecko)?"dommousescroll":"mousewheel"}}); })();e...
New Security Model for Web Services - Archive of obsolete content
omains, but on the web, it is often a script from a relatively-untrusted domain that must be granted access to other untrusted domains, without compromising internal domains. more-complex access lists could be created to try to establish, with finer granularity, which domains are to be accessible or permitted from which other domains, but this requires extensive management which at best is quite
error-prone for the end user and easily opens holes in a firewall that do not directly hurt the user who reconfigured his browser to try to access some external service but hurts the owners of other services behind the firewall. signed scripts a certain degree of additional trust may be lent to a script by having the author digitally sign it. but signed scripts have not really caught on as they requi...
...-scripts-access.xml which contains the "delegate" keyword delegates to http://www.example.com/foo/web-scripts-access.xml. if the uri is in a subdirectory, and the root directory's access file delegated but no access file exists in the subdirectory, then no access is granted. if the root's access file did not delegate, then that access file also handles all resources in subdirectories. any syntax
error in the document will result in the rest of the file to be ignored. since the commands only allow access, the order of processing the "allow" commands that were successfully parsed is never significant. allowing web script access to permit scripts to access the resources of this server, use the following command: <wsa:allow type="<request-type>" from ="<uri-prefix>"/> the type of request, if ...
...cting information from it (declaration file); requested type and subject princple's prefix are compared to the allowed type and prefix in order to determine access. an entry is created if and only if the declaration file is considered valid (validation based on the syntax described above); an invalid document will result in access denial. denies script access in the event of an xml-wellformedness
error, or validation
error, or if the declaration file does not grant access. reports
errors (validation, wellformedness, file not found, etc.) to the console via nsiconsoleservice. note: script access is checked via declaration file only if the script security manager denies access. summary advantages the proposed declaration file places the server operator, not the client in control of access t...
Porting NSPR to Unix Platforms - Archive of obsolete content
local variables are allocated on the stack). on some platforms, <tt>jmp_buf</tt> is a struct, then you should look for a struct member named <tt>sp</tt> or something similar. ...
...ck). on some platforms, <tt>jmp_buf</tt> is a struct, then you should look for a struct member named <tt>sp</tt> or something similar. ...
...de/md/_unixos.h</tt>: just fix the compiling
errors, usually pointed out by the <tt>#
error</tt> preprocessor directives we inserted. <tt>mozilla/nsprpub/pr/include/md/prosdep.h</tt> <tt>mozilla/nsprpub/pr/src/md/prosdep.c</tt> <tt>mozilla/nsprpub/pr/src/md/unix/makefile</tt> <tt>mozilla/nsprpub/pr/src/md/unix/objs.mk</tt> <tt>mozilla/nsprpub/pr/src/md/unix/unix.c</tt>: just fix the compiling
errors, usually pointed out by the <tt>#
error</tt> preprocessor directives we inserted for a pthreads port, you need to modify the following files: <tt>mozilla/nsprpub/pr/include/md/_pth.h</tt> files in mozilla/nsprpub/pr/src/pthreads, most likely <tt>ptthread.c</tt> and <tt>ptio.c</tt> testing your port we have some unit tests in <tt>mozilla/nsprpub/pr/tests</tt>. first a warning: some of the t...
Abc Assembler Tests - Archive of obsolete content
pt that is used for the actionscript tests. when run, the assembler tests include the abcasm/abs_helper.as file which defines the following functions: start(summary:string):void - start a new test section described by summary end():void - test section finished compare_stricteq(name:string, expected:*, actual:*):void - compare the results of a testcase where name is the testcase name compare_type
error(name:string, expected:*, actual:*):void - special function for comparing type
errors (runtime
errors) - will only compare the first 22 chars of expected and actual so that test can be run in release and releasedebugger configurations. compare_numbereq(name:string, expected:*, actual:*, fractiondigits:int=-1):void - compare 2 numbers up to fractiondigits this is to be used for high precisi...
...n .function_id(runtest) getlocal0 call 0 findproperty end callpropvoid end 0 returnvoid } function runtest() { // test null <= null == true findproperty compare_stricteq pushstring "null lessequals null" // testname pushtrue // expected pushnull pushnull lessequals // actual callpropvoid compare_stricteq 3 // use .try / .catch to catch type
error // convert_o null .try { pushnull convert_o pop findproperty fail pushstring "convert_o null" pushstring "exception should have been thrown: type
error:
error #1009: cannot access a property or method of a null object reference." getlocal1 callpropvoid fail 3 jump finished_convert_o_null } .catch { ge...
... convert_o pop findproperty fail pushstring "convert_o null" pushstring "exception should have been thrown: type
error:
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 type
error findproperty compare_type
error pushstring "convert_o null" // test name pushstring "type
error:
error #1009" // expected getlocal2 // actual callpropvoid compare_type
error 3 } finished_convert_o_null: } ...
Venkman Introduction - Archive of obsolete content
e 4, to indicate 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...
...y set, the margin will show the letter "b" on a red background, and both the loaded scripts view and interactive session view will provide feedback. the breakpoint can be cleared by clicking in the margin again (on the letter "b"). breakpoints cannot be set on lines which do not contain executable code, such as blank and comment lines. for these lines, the interactive session view will display an
error message explaining why the breakpoint could not be set. breakpoints can also be set and cleared from the interactive session view, 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 patt...
... the breakpoint could not be set. breakpoints can also be set and cleared from the interactive session view, 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...
initInstall - Archive of obsolete content
ackage, installversion version); parameters the initinstall method has the following parameters: displayname a string that contains the name of the software being installed. the name of the software is displayed to the user. package the client version registry pathname for the software (for example: plugins/adobe/acrobat or /royalairways/royalpi/). it is an
error to supply a null or empty name. the name can be absolute or relative. a relative pathname is relative to the netscape 6 namespace. a relative pathname must start with plugins/, to be relative to the plug-ins portion of that namespace or java/download/, to be relative to the java portion. all other parts of the netscape 6 area of the registry are reserved for use by netscape. the cli...
...mportant when you add components with the addfile method. version an installversion object or a string representing the version of the package being installed. when version is a string it should be up to four integer values delimited by periods, such as "1.17.1999.1517". flags an optional field; reserved for future use. pass 0 as the default value. returns an integer
error code. for a list of possible values, see return codes. description the initinstall method initializes the installation of the specified software. you must call this method immediately after the constructor. it is an
error to call any other install methods before calling initinstall. after calling initinstall, your script must call performinstall or cancelinstall before it finishes. if your scr...
... your script must call performinstall or cancelinstall before it finishes. ...
performInstall - Archive of obsolete content
summary performs the actual installation of the software. moves all components to their final locations, launches any pending executions, and registers the package and all of its subcomponents in the client version registry. method of install syntax int performinstall(); parameters none. returns an integer
error code. for a list of possible values, see return codes. in some situations the method may return other
errors. ...
...mponents to their final locations, launches any pending executions, and registers the package and all of its subcomponents in the client version registry. method of install syntax int performinstall(); parameters none. returns an integer
error code. for a list of possible values, see return codes. in some situations the method may return other
errors. in a few cases you may get a registry
error. ...
...integer
error code. for a list of possible values, see return codes. in some situations the method may return other
errors. in a few cases you may get a registry
error. example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner", "/royalairways/tripplanner", "1.0.0.0"); ... ...
Reading from Files - Archive of obsolete content
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. reading data from a file involves getting a reference to a file and then creating an input stream to read from it. an input stream provides a means of reading bytes, strings or other values from the file. while there is only one method to create an input stream, it provides a number of options to control exactly how reading is performed. for instance, there are options to read a file as if...
...tream = io.newinputstream(file, "text"); this example first retrieves a file object using nsiscriptableio.getfile(). in this case, the file 'sample.txt' within the user's home directory is retrieved. next, nsiscriptableio.newinputstream() is called to create a new input stream for reading from the file. this method will open the file and return a stream. naturally, if the file does not exist, an
error will occur. you may wish to use nsifile.exists() to check if the file exists before opening it. in fact, it is a good idea to enclose file reading and writing operations within a try-catch block to capture any
errors that might occur during the process. see file
errors for a list of
errors that might occur. the newinputstream method takes two arguments in this example. the first argument is the f...
...pending on the character encoding, it is possible that more than 20 bytes will be read from the file in order to retrieve 20 characters from the file. the readstring method returns the string read from the stream. usually this string have a length equal to the number of characters that were requested. however, it may not do, for instance if the end of the file was reached. this doesn't trigger an
error, and the string will just be returned containing as many characters as are available. you can use the available method to check if data is available for reading: var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); var str = stream.readstring(stream.available()); stream.close(); in this example, the available method is called to determine the number of avail...
Writing to Files - Archive of obsolete content
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. to write to a file, an output stream is used. an output stream is an object which can be used to write bytes, strings and other values to a file. to create an output stream, use nsiscriptableio.newoutputstream(). this method has a number of options to specify text or binary writing, the character set, and whether to append to an existing file or create a new one. to create an input stream...
... "text"); } catch (ex) { alert(ex); } this example retrieves a file object on the desktop called 'myinfo.txt' using nsiscriptableio.getfile(). it doesn't matter whether the file exists or not. nsiscriptableio.newoutputstream() is called to create a new output stream, which will be used to write to the file. in this example, the operations are enclosed in a try-catch block in order to capture any
errors that might occur during the process. see file
errors for a list of
errors that might occur. the newoutputstream method takes two arguments in this example. the first argument is the file to write to, and the second is a set of flags which control the writing. in this case, the 'text' flag is used which indicates that you will be writing text to the file. when writing text files, characters are w...
.... however, there are three flags that can be used to control this behaviour. append if used, always write data to the end of the file. this flag is used when adding more to an existing file. if this flag is not used, the data is written at the beginning of the file, overwriting what is already there. nocreate if used, don't create a new file if it does not already exist. in this case, an
error will occur if the file does not exist, which you can capture using a try-catch block. if this flag is not used, a new file will be created. in either case, if the file already exists, it will be truncated to zero length. notruncate if used, don't truncate an existing file when opening it for writing. instead, just overwrite the existing content. if the new data being written is shorter than t...
Index - Archive of obsolete content
xul attributes, xul reference no summary! 225 ondialogdisclosure xul attributes, xul reference no summary! 226 ondialogextra1 xul attributes, xul reference no summary! 227 ondialogextra2 xul attributes, xul reference no summary! 228 ondialoghelp xul attributes, xul reference no summary! 229 on
error xul attributes, xul reference no summary! 230 on
errorcommand xul attributes, xul reference no summary! 231 onextra1 xul attributes, xul reference no summary! 232 onextra2 xul attributes, xul reference no summary! 233 oninput xul attributes, xul reference no summary! 234 onload xul attribut...
... are loaded via javascript. this will not work for other types of trees, for example rdf-backed or ones created with dom methods. ...
... builder will be created. both types of builder share much of the same code except for how they generate output to be displayed. both types of builders implement the nsixultemplatebuilder interface, while the tree builder also implements the nsixultreebuilder interface.</tree> 946 template logging debugging problems with a template can be difficult as many problems are logic
errors that are often not possible to determine automatically. for example, if you spell a value wrong, no data may be returned, but the template system won't know that that this was because of a spelling
error, or simply that there shouldn't be any data anyway. fortunately, some debugging and logging support is provided with templates that may help. 947 template and tree listeners xul, ...
Textbox (XPFE autocomplete) - Archive of obsolete content
arch, autocompletesearchparam, autofill, autofillaftermatch, autofill, completedefaultindex, crop, disableautocomplete, disableautocomplete, disabled, disablehistory, enablehistory, focused, forcecomplete, forcecomplete, highlightnonmatches, ignoreblurwhilesearching, ignoreblurwhilesearching, inputtooltiptext, label, maxlength, maxrows, minresultsforpopup, minresultsforpopup, nomatch, onchange, on
errorcommand, oninput, onsearchcomplete, ontextcommand, ontextentered, ontextrevert, ontextreverted, open, readonly, searchsessions, showcommentcolumn, showcommentcolumn, showpopup, size, tabindex, tabscrolling, tabscrolling, timeout, type, useraction, value properties accessible, alwaysopenpopup, autofill, autofillaftermatch, completedefaultindex, crop, disableautocomplete, disabled, e...
... oninput type: script code this event is sent when a user enters text in a textbox. this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. onsearchcomplete new in thunderbird 3requires seamo...
... xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> on
errorcommand type: script code this event handler is called when an
error occurs when selecting a result from the popup. oninput type: script code this event is sent when a user enters text in a textbox. this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. onsearchcomplete new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the aut...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
will be an extension. 2. delete these two files: chrome.rdf overlays.rdf explanation: seamonkey automatically rebuilds these files the next time it starts. when it rebuilds them, it will include your new extension. 3. edit the file: installed-chrome.txt at the end of the file, add the following line. copy and paste the line from here, to avoid typing
errors: content,install,url,resource:/chrome/custombutton/ explanation: this line registers your custom toolbar button extension, linking it into seamonkey. 4. create a new directory named: custombutton perform the following steps in this new directory, creating five files there. explanation: the name is a unique identifier for your extension, and the ...
...at you have followed all the steps exactly. if necessary, uninstall the button and start again, this time without making any changes to the files. after you get the button working, customize the files carefully. to see the effect of any change that you make, restart seamonkey. advanced troubleshooting if you have some technical knowledge, then you can use the seamonkey's javascript console to see
error messages. however, you might see messages that are unhelpful or confusing, or that come from other parts of the application. to open the javascript console, choose tools – web development – javascript console. messages in the javascript console can provide information about javascript, xul or css files. note: the preference setting javascript.options.strict imposes restrictions that are no...
...ckground. they are in png format. some other formats will also work. here are some more images that you can download and use: restart the application to find the new button. you can repeat these steps to add as many buttons as you need. positioning buttons to position your buttons on each toolbar, you can use their position attributes in button.xul. you might have to use trial and
error to find values that work well, and you might find that not all positions are possible using this technique. this simplfied tutorial handles all the toolbars in a single file, button.xul. this is not always satisfactory. if you find that settings for different toolbars interfere with each other, make a separate xul file for each toolbar by copying button.xul and removing that parts that you do not...
CommandLine - Archive of obsolete content
a66"); const class_name = "applicationnameclh"; const contract_id = "@example.com/applicationname/clh;1"; const cld_category = "m-applicationname"; var apphandler = { /* nsisupports */ queryinterface : function clh_qi(aiid) { if (aiid.equals(nsicommandlinehandler) || aiid.equals(nsifactory) || aiid.equals(nsisupports)) return this; throw components.results.ns_
error_no_interface; }, /* nsicommandlinehandler */ handle : function clh_handle(acmdline) { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.notifyobservers(acmdline, "commandline-args-changed", null); }, helpinfo : " -test <value> a test at...
...zilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.notifyobservers(acmdline, "commandline-args-changed", null); }, helpinfo : " -test <value> a test attribute\n", /* nsifactory */ createinstance : function mdh_ci(aouter, aiid) { if (aouter != null) { throw components.results.ns_
error_no_aggregation; } return this.queryinterface(aiid); }, lockfactory : function mdh_lock(alock) { /* no-op */ } }; var apphandlermodule = { /* nsisupports */ queryinterface : function mod_qi(aiid) { if (aiid.equals(nsimodule) || aiid.equals(nsisupports)) return this; throw components.results.ns_
error_no_interface; }, /* nsimodule */ getclas...
... /* nsisupports */ queryinterface : function mod_qi(aiid) { if (aiid.equals(nsimodule) || aiid.equals(nsisupports)) return this; throw components.results.ns_
error_no_interface; }, /* nsimodule */ getclassobject : function mod_gch(acompmgr, acid, aiid) { if (acid.equals(class_id)) return apphandler.queryinterface(aiid); throw components.results.ns_
error_failure; }, registerself : function mod_regself(acompmgr, afilespec, alocation, atype) { var compreg = acompmgr.queryinterface(nsicomponentregistrar); compreg.registerfactorylocation(class_id, class_name, contract_id, afilespec, alocation, atype); var catman = components.classes["@mozilla.org/categorymanager;1"] .
XULRunner tips - Archive of obsolete content
without these settings password manager will not store login details. p...
...without these settings password manager will not store login details. pref("signon.remembersignons", true); pref("signon.expirem...
...without these settings password manager will not store login details. pref("signon.remembersignons", true); pref("signon.expiremasterpassword", false); pref("signon.signonfile...
2006-10-27 - Archive of obsolete content
x (linux) not building since 20-oct-2006 17:45 pdt october 22nd: gavin sharp answered a question that was posted by tony mechelynck. the question tony posted was that he wanted to know what was wrong with fx 1.5.0.x (linux) tinderbox because it has been failing since october 22 at around 5:45 pm pdt. gavin responded to tony's posting saying that the log file shows a "no space left on device"
error when trying to link the final executable. on the same day tony replied to gavin's posting stating the possible choices to solve the problem. these were the following choices stated: search the filesystem for unneeded files delete or archive them, add a hard disk, move all or part of the concerned filesystem there move that tinderbox to a different machine with more empty disk space o...
...fox 2 on solaris. ./configure --prefix=/export/home/alex/thunderbird --enable-application=browser --disable-tests --disable-debug -disable-auto-deps --disable-freetype2 -enable-official-branding --enable-default-toolkit=gtk2 --enable-optimize=-xo5 --enable-static --disable-shared --enable-xft --enable-svg the build tools that he used to build firefox 2 are listed in his posting along with the
error that he receives when he tries to build it. alex is not sure if he is missing a library or if he needs to pass extra options to configure the build. peter weilbacher responded to alex's posting on the same day, stating that he is not sure what packaging system solaris 10 x86 uses but thinks that he might need to install the developer packages of x and/or xrender and freetype which should conta...
...lex replied to masaki posting, stating that he was going to use the work around that he provided and would provide feedback if it was successful or not. later that day alex able to successful complete his firefox 2 build by using masaki'swork around that he had posted. update-packaging october 27: atachi.hayash wanted to know if you use msys would update-packaging work. click here to view the
errorthat he receives when trying to update-packaging.
error building firefox-2.0rc3 october 27: chotu atwork is trying to build firefox-2.0rc3 on uclinux running on a mips processor. during his build he receives an
error which he has tried to find a solution by using google, but has not been successful. announcements there are no announcements this week. discussions final ff release already an...
2006-11-03 - Archive of obsolete content
11 2006. when he builds using the disable.crypto option he encounters the following problem: no rule to make target `../../dist/lib/components/libpipboot.a', needed by `minimo'. he has also created a bug en...
...the code base from sept. 11 2006. when he builds using the disable.crypto option he encounters the following problem: no rule to make target `../../dist/lib/components/libpipboot.a', needed by `minimo'. he has also created a bug entry on bugzilla with the bug id of opened bug #344854. problem compiling with vs 2003 .net phil is trying to compile firefox for the first time and is getting an
error when doing so: building deps for /cygdrive/c/mozilla/toolkit/airbag/airbag/src/common/windows/guid_string.cc make[1]: leaving directory `/cygdrive/c/mozilla/obj-i686-pc-cygwin' make: *** [build]
error 2 he also noted that he is using make 3.80-1. on november 1st gavin sharp responded phil's question. he said that the problem that phil is experiencing is a known issue. he also mentioned tha...
...nded that phil should add |ac_add_options --disable-airbag| to his .mozconfig. new windows compatibility issue? originally posted on november 1st: dale dale has set up a windows machine in order to perform mozilla builds but has been unsuccessful to do so. according to him he has followed the windows build requirements recommended by mozilla. he also noted that he has had different results (
error messages when compiling) on different machines. dale has discovered that there are other people who are experiencing the same issues as he is. he has also found a work around which is to use version 20040127-1 of sh.exe instead of the sh.exe version 20040127-3. fix host_libidl_libs originally posted on october 29th: gery gery claims to have discovered a problem when he compiles mozilla acr...
NPN_DestroyStream - Archive of obsolete content
stream pointer to current stream, initiated by either the browser or the plug-in. reason reason the stream was stopped so the application can give the user appropriate feedback. ...
... stream pointer to current stream, initiated by either the browser or the plug-in. reason reason the stream was stopped so the application can give the user appropriate feedback. ...
...n the stream was stopped so the application can give the user appropriate feedback. values: npres_done (most common): stream completed normally; all data was sent by the plug-in to the browser. npres_user_break: plug-in is terminating the stream due to a user request. npres_network_err: stream failed due to network problems. 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 the plug-in calls the npn_destroystream() function to close and delete a stream. this stream can be either a stream that the browser created and passed to the plug-in in npp_newstream(), or a stream created by the plug-in through a call to npn_newstream(). see al...
NPN_GetValue - Archive of obsolete content
variable information the call gets. ...
...olkit: npnvsupportsxembedbool: npnvwindownpobject: returns the npobject * pointer for the dom window object; see getting the page url in npapi plugin for a rough example npnvpluginelementnpobject: npnvsupportswindowless: tells whether the browser supports windowless plugins. the value parameter should point to a npbool, which will be set appropriately if the function returns nperr_no_
error. npnvprivatemodebool: indicates whether or not the browser is currently in private browsing mode. the value parameter should point to an npbool, which will be set appropriately if the function returns nperr_no_
error. npnvdocumentorigin: the value for this variable is the unicode serialization of the origin converted to nfkc-encoded (normalized) utf-8. memory for this string must be freed ...
...l: (mac only) npnvsupportsquickdrawbool : (mac only) npnvsupportscoregraphicsbool : (mac only) value function returns the name of the plug-in in the value parameter. gecko 1.9.2 note starting with gecko 1.9.2 (firefox 3.6), the variables npnvservicemanager, npnvdomelement, and npnvdomwindow are no longer supported. 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_getvalue returns the browser information set with npn_setvalue. the queried information is returned in the value parameter. unix the platform-specific values for this parameter are npnvxdisplay (the current display), npnvxtappcontext (the browser's xtappconte...
NPN_PostURLNotify - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary posts data to a url, and receives notification of the result. syntax #include <npapi.h> np
error npn_posturlnotify(npp instance, const char* url, const char* target, uint32 len, const char* buf, npbool file, void* notifydata); parameters the function has the following parameters: instance current plug-in instance, specified by the plug-in. url url of the post request, specified by the plug-in. target target window, specified by the plug-in. for values, see npn_geturl. len length of the...
... whether to post a file. values: true: post the local file whose path is specified in buf, then delete the file. false: post the raw data in buf. notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify call, which returns this value (see description below). returns if successful, the function returns nperr_no_
error. if unsuccessful, the plug-in is not loaded and 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 m...
...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 value of _self or a parent to _self, this function should return an invalid_param np
error. this is the only way to notify the plug-in once it is deleted. see npn_geturl for information about this parameter. see also npn_geturl, npp_urlnotify, npn_posturl ...
NPN_SetValue - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary implemented by browsers. this call is used to inform the browser of variable information controlled by the plugin. syntax #include <npapi.h> np
error npn_setvalue(npp instance, nppvariable variable, void *value); parameters the function has the following parameters: instance pointer to the plugin instance setting the variable. variable values the function can set: nppvpluginwindowbool: sets windowed/windowless mode for plugin display; true=windowed, false=windowless nppvplugintransparentbool: sets transparent mode for display of a plugin; true=transparent, false=opaque nppvjavaclass nppvpluginwindowsize nppvplugintimerinterval nppvplugi...
...erbool: specifies whether you are pushing or popping the jscontext off the stack nppvpluginkeeplibraryinmemory: tells browser that the plugin dll should live longer than usual nppvpluginneedsxembed nppvpluginscriptablenpobject nppvformvalue nppvplugindrawingmodel value the value of the specified variable to be set. returns if successful, the function should return nperr_no_
error. if unsuccessful, the function should return the most relevant npapi
error code. for possible values, see
error codes. description a good place to set plugin operation mode such as windowless mode is npp_new, so the browser knows right away what mode the plugin is designed to operate in. nppvpluginwindowbool (windows and unix) specifies that the plugin operates in windowed mode. the alternat...
...emory as variable parameter and value set to true. by default, the dll will be unloaded from memory preceded by an np_shutdown call. remarks all four variable values are boolean. although the function prototype has type of value void *, the actual boolean should be placed there, not a pointer to a boolean. the browser code reads this parameter as follows (nppvpluginwindowbool as an example): np
error np_export _setvalue(npp npp, nppvariable variable, void *value) { ... bool bwindowless = (value == null); ... } so the proper way to call this function from a plug-in would be: bool bwindowed = false; npn_setvalue(npp, nppvpluginwindowbool, ( void *)bwindowed); see also npp_new, npn_getvalue, npp_setvalue, npp_getvalue ...
Using the W3C DOM - Archive of obsolete content
the w3c document object model provides interfaces dom elements to scriptable objects. ...
...instead, use the w3c dom properties and methods (examples in the next section). these are supported by internet explorer too so there is no need to use msie-specific attributes and methods. accessing elements with the w3c dom the basic method for referencing elements in an html page is document.getelementbyid(). all modern browsers support it. the method r...
...and top, make sure to construct a string that includes the unit (such as "140px") by appending the unit string to the integer value. css 1 and css 2.x specifications require that non-zero values must be specified with a length unit; otherwise, the css declaration will be ignored. mozilla-based browsers, msie 6+, opera 7+ and other w3c standards-compliant browsers enforce such handling of parsing
error. css 1 forward-compatible parsing css 2.1 rules for handling parsing
errors changing an element's text using the dom the text of an element is available as the textcontent or innertext property (some browsers support both). the textcontent property was introduced in the w3c dom 3 core, innertext has been an ie method since ie 4 and has been standardised in html5. both properties can be read...
Object.prototype.__noSuchMethod__ - Archive of obsolete content
ect, with which you can achieve the below (and more). syntax obj.__nosuchmethod__ = fun parameters fun a function that takes the form function (id, args) { . . . } id the name of the non-existent method that was called args an array of the arguments passed to the method description by default, an attempt to call a method that doesn't exist on an object results in a type
error being thrown. this behavior can be circumvented by defining a function at that object's __nosuchmethod__ member. the function takes two arguments, the first is the name of the method attempted and the second is an array of the arguments that were passed in the method call. the second argument is an actual array (that is, it inherits through the array.prototype chain) and not the array-like argume...
...od attempted and the second is an array of the arguments that were passed in the method call. the second argument is an actual array (that is, it inherits through the array.prototype chain) and not the array-like arguments object. if this method cannot be called, either as if undefined by default, if deleted, or if manually set to a non-function, the javascript engine will revert to throwing type
errors. examples simple test of __nosuchmethod__ var o = { __nosuchmethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); } }; o.foo(1, 2, 3); o.bar(4, 5); o.baz(); // output // foo (1, 2, 3) // bar (4, 5) // baz () using __nosuchmethod__ to simulate multiple inheritance an example of code that implements a primitive form of mult...
... // example base class 1 function namedthing(name) { this.name = ...
Common causes of memory leaks in extensions - Extensions
re caused by a failure to release resources appropriately in certain circumstances, such as when a window is closed, a page unloads, or an extension is disabled or removed. while bug 695480 should prevent most of these compartment leaks, add-ons still need to be aware of the practices that caused these leaks, as the fix causes many add-ons which would have otherwise caused a leak to instead throw
errors when attempting to access nodes from documents which no longer exist. storing references to window objects and dom nodes the most common problem is extensions holding onto references to content windows for too long. for example, in xul overlay code: var contentwindows = []; function inbrowserxuloverlay(contentwindow) { // forgetting or failing to pop the content window thing again conten...
...t to declare local variables with var or let, which means they end up belonging to the global scope. for example: function implicitdeclarationleak(window) { // implicit variable declaration in the js global, holding a strong ref to the document doc = window.document; } implicitly declared variables can be avoided by using ecmascript 5's strict mode. strict mode also excludes several other
error-prone code patterns. for some examples found in real-world add-ons, see bug 712733, bug 725875, and bug 727552. to avoid these issues, references to dom nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. be careful with setinterval/settimeout using window.setinterval(...
...need to break circular references that might negatively // impact the shutdown process. if (reason == app_shutdown) return; // your add-on needs to unload all modules it ships and imported! components.utils.unload("chrome://myaddon/content/mymodule.jsm"); } note: modules not belonging to your add-on — such as services.jsm — should not be unloaded by your add-on, as this might cause
errors and/or performance regressions and will actually increase the memory usage. other information also see using xpcom in javascript without leaking (though that page could use some updating). ...
What are browser developer tools? - Learn web development
find more out about the javascript debugger in different browsers: firefox javascript debugger microsoft edge debugger chrome debugger safari debugger the javascript console the javascript console is an incredibly useful tool for debugging javascript that isn't working as expected. it allows you to run lines of javascript against the page currently loaded in the browser, and reports the
errors encountered as the browser tries to execute your code. to access the console in any browser: if the developer tools are already open, click or press the console tab. if not, firefox allows you to open the console directly using ctrl + shift + k or using the menu command: menu ➤ web developer ➤ web console, or tools ➤ web developer ➤ web console. on other browser, open the developer to...
...versions of the code and see what you get. ...
... find out more find more out about the javascript console in different browsers: firefox web console ie javascript console chrome javascript console (opera's inspector works the same as this) safari console ...
What is a web server? - Learn web development
ear rules for how a client and server communicate. we'll cover http itself in a technical article later. for now, just be aware of these things: only clients can make http requests, and then only to servers. servers can only respond to a client's http request. when requesting a file via http, clients must provide the file's url. ...
...dynamic content roughly speaking, a server can serve either static or dynamic content. remember that the term static means "served as-is". ...
... processing and answering incoming requests. upon receiving a request, an http server first checks if the requested url matches an existing file. if so, the web server sends the file content back to the browser. if not, an application server builds the necessary file. if neither process is possible, the web server returns an
error message to the browser, most commonly 404 not found. (the 404
error is so common that some web designers devote considerable time and effort to designing 404
error pages.) static vs. dynamic content roughly speaking, a server can serve either static or dynamic content. remember that the term static means "served as-is". static websites are the easiest to set up, so we suggest you make your first site a static site. the term dynamic means that the server proce...
Index - Learn web development
t. we've begun with just theory, to start getting you used to why you'd use javascript and what kind of things you can do with it. along the way, you saw a few code examples and learned how javascript fits in with the rest of the code on your website, amongst other things. 88 what went wrong? troubleshooting javascript article, beginner, codingscripting, debugging, developer tools,
error, javascript, learn, tutorial, console.log, l10n:priority so there we have it, the basics of figuring out
errors in simple javascript programs. it won't always be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't turn out right, especially in the earlier stages of your learning jour...
...f, hyperlinks, relative, urls that's it for links, for now anyway! you'll return to links later on in the course when you start to look at styling them. next up for html, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — advanced text formatting is your next stop. 233 debugging html beginner, codingscripting, debugging,
error, guide, html, validation, validator so there we have it, an introduction to debugging html, which should give you some useful skills to count on when you start to debug css, javascript, and other types of code later on in your career. this also marks the end of the introduction to html module learning articles — now you can go on to testing yourself with our assessments: the first one is ...
...tml forms, these tables can't be considered a perfect reference. however, they will give you good insight into what can and can't be done, which will help you learn how to do things. 312 client-side form validation beginner, example, forms, guide, html, javascript, learn, web, regex client-side form validation sometimes requires javascript if you want to customize styling and
error messages, but it always requires you to think carefully about the user. always remember to help your users correct the data they provide. to that end, be sure to: 313 html forms in legacy browsers example, forms, guide, html, intermediate, web to understand common patterns, it helps to read browser documentation. if you are reading this on mdn, you are at the right place to s...
Client-side storage - Learn web development
your database (for example, by changing the table structure), you have to run your code again with an increased version number, different schema specified inside the onupgradeneeded handler (see below), etc. we won't cover upgrading databases in this simple tutorial. now add the following event handlers just below your previous addition — again inside the window.onload handler: // on
error handler signifies that the database didn't open successfully request.on
error = function() { console.log('database failed to open'); }; // onsuccess handler signifies that the database opened successfully request.onsuccess = function() { console.log('database opened successfully'); // store the opened database object in the db variable. this is used a lot below db = request.result; //...
...atabase failed to open'); }; // onsuccess handler signifies that the database opened successfully request.onsuccess = function() { console.log('database opened successfully'); // store the opened database object in the db variable. this is used a lot below db = request.result; // run the displaydata() function to display the notes already in the idb displaydata(); }; the request.on
error handler will run if the system comes back saying that the request failed. this allows you to respond to this problem. in our simple example, we just print a message to the javascript console. the request.onsuccess handler on the other hand will run if the request returns successfully, meaning the database was successfully opened. if this is the case, an object representing the opened database ...
...entry titleinput.value = ''; bodyinput.value = ''; }; // report on the success of the transaction completing, when everything is done transaction.oncomplete = function() { console.log('transaction completed: database modification finished.'); // update the display of data to show the newly added item, by running displaydata() again. displaydata(); }; transaction.on
error = function() { console.log('transaction not opened due to
error'); }; } this is quite complex; breaking it down, we: run event.preventdefault() on the event object to stop the form actually submitting in the conventional manner (this would cause a page refresh and spoil the experience). create an object representing a record to enter into the database, populating it with values from th...
Ember resources and troubleshooting - Learn web development
t in their responsibilities, delegating to components and services where possible. what is the purpose of routes? a route represents part of the url when a user navigates from place to place in the app. a route has only a couple responsibilities: load the minimally required data to render the route (or view-sub-tree). gate access to the route and redirect if needed. ...
... more information on everything a route can do is found in the api documentation. ...
...ates from the minimally required data. a route only has 3 lifecycle hooks, all of which are optional: beforemodel — gate access to the route. model — where data is loaded. aftermodel — verify access. last, a route has the ability to handle common events resulting from configuring the model: loading — what to do when the model hook is loading.
error — what to do when an
error is thrown from model. both loading and
error can render default templates as well as customized templates defined elsewhere in the application, unifying loading/
error states. more information on everything a route can do is found in the api documentation. previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main...
Getting started with React - Learn web development
.js to use code that has been defined elsewhere. let's look at these statements more closely. import react from 'react'; import logo from './logo.svg'; import './app.css'; the first statement imports the react library itself. because react turns the jsx we write into react.createelement(), all react components must import the react module. if you skip this step, your application will produce an
error. the second statement imports a logo from './logo.svg'. note the use of ./ at the beginning of the path, and the .svg extension at the end — these tell us that the file is local and that it is not a javascript file. indeed, the logo.svg file lives in our source directory. we don't write a path or extension when importing the react module — this is not a local file; instead, it is listed as ...
...he browser. the app component after the imports, we have a function named app. whereas most of the javascript community prefers camel-case names like helloworld, react components use pascal-case variable names, like helloworld, to make it clear that a given jsx element is a react component, and not a regular html tag. if you were to rename the app function to app, your browser would show you an
error. let's look at app more closely. function app() { return ( <div classname="app"> <header classname="app-header"> <img src={logo} classname="app-logo" alt="logo" /> <p> edit <code>src/app.js</code> and save to reload. </p> <a classname="app-link" href="https://reactjs.org" target="_blank" rel="noopener ...
... in this case the element with an id of root. if you look inside public/index.html, you'll see that this is a <div> element just inside the <body>. all of this tells react that we want to render our react application with the app component as the root, or first component. note: in jsx, react components and html elements must have closing slashes. writing just <app> or just <img> will cause an
error. service workers are interesting pieces of code that help application performance and allow features of your web applications to work offline, but they’re not in scope for this article. you can delete line 5, as well as lines 9 through 12. your final index.js file should look like this: import react from 'react'; import reactdom from 'react-dom'; import './index.css'; import app from './app...
Getting started with Vue - Learn web development
eatures" option. the first menu you’ll be presented with allows you to choose which features you want to include in your project. make sure that "babel" and "linter / formatter" are selected. if they are not, use the arrow keys and the space bar to toggle them on. once they are selected, press enter to proceed. next you’ll select a config for the linter / formatter. navigate to "eslint with
error prevention only" and hit enter again. this will help us catch common
errors, but not be overly opinionated. next you are asked to configure what kind of automated linting we want. select "lint on save". this will check for
errors when we save a file inside the project. hit enter to continue. now, you will select how we want your config files to be managed. "in dedicated config files" will put y...
... element from the template section: <img alt="vue logo" src="./assets/logo.png"> if your server is still running, you should see the logo removed from the rendered site almost instantly. let’s also remove the helloworld component from our template. ...
... let’s add a new <h1> inside <div id="app">. since we’re going to be creating a todo list app below, let's set our header text to "to-do list". ...
Handling common accessibility problems - Learn web development
sibility if used badly, or overused. we've already hinted at some accessibility problems related to javascript, mainly in the area of semantic html — you should always use appropriate semantic html to implement functionality wherever it is available, for example use links and buttons as appropriate. don't use <div> elements with javascript code to fake functionality if at all possible — it is
error prone, and more work than using the free functionality html gives you. simple functionality generally simple functionality should work with just the html in place — javascript should only be used to enhance functionality, not build it in entirely. good uses of javascript include: providing client-side form validation, which alerts users to problems with their form entries quickly, without ...
...nto. they will look over them and return a list of accessibility issues present on the page. examples include: wave: a rather nice online accessibility testing tool that accepts a web address and returns a useful annotated view of that page with accessibility problems highlighted. tenon: another nice online tool that goes through the code at a provided url and returns results on accessibility
errors including metrics, specific
errors along with the wcag criteria they affect, and suggested fixes. it requires a free trial signup to view the results. tota11y: an accessibility tool from the khan academy that takes the form of a javascript library that you attach to your page to provide a number of accessibility tools. let's look at an example, using wave. go to the wave homepage. enter t...
...ems are occuring where are rather useful). note: such tools aren't good enough to solve all your accessibility problems on their own. you'll need a combination of these, knowledge and experience, user testing, etc. to get a full picture. automation tools deque's axe tool goes a bit further than the auditing tools we mentioned above. like the others, it checks pages and returns accessibility
errors. its most immediately useful form is probably the browser extensions: axe for chrome axe for firefox these add an accessibility tab to the browser developer tools. for example, we installed the firefox version, then used it to audit our bad-table.html example. we got the following results: axe is also installable using npm, and can be integrated with task runners like grunt and gulp, au...
Client-side tooling overview - Learn web development
process easier with respect to generating stable and reliable code. safety net tooling should also help you either prevent mistakes or correct mistakes automatically without having to build your code from scratch each time. a few very common safety net tool types you will find being used by developers are as follows. linters linters are tools that check through your code and tell you about any
errors that are present, what
error types they are, and what code lines they are present on. often linters can be configured to not only report
errors, but also report any violations of a specified style guide that you team might be using (for example code that is using the wrong number of spaces for indentation, or using template literals rather than regular string literals). eslint is the industry s...
...some companies and projects have also shared their eslint configs. you can also find linting tools for other languages, such as csslint. ...
...n be accessed via friendly user interfaces. with your code in a git repository, you can push it to your own server instance, or use a hosted source control website such as github, gitlab, or bitbucket. we'll be using github in this module. you can find more information about it at git and github. code formatters code formatters are somewhat related to linters, except that rather than point out
errors in your code, they usually tend to make sure your code is formatted correctly, according to your style rules, ideally automatically fixing
errors that they find. prettier is a very popular example of a code formatter, which we’ll make use of later on in the module. bundlers/packagers these are tools that get your code ready for production, for example by “tree-shaking” to make sure only...
Package management basics - Learn web development
default for now. press return one more time to accept these settings. go into your parcel-experiment directory and you should now find you've got a package.json file. open it up and it should look something like this: { "name": "parcel-experiment", "version": "1.0.0", "description": "a simple npm package to learn about using npm", "main": "index.js", "scripts": { "test": "echo \"
error: no test specified\" && exit 1" }, "author": "chris mills", "license": "isc" } so this is the config file that defines your package. this is good for now, so let's move on. installing parcel run the following command to install parcel locally: npm install parcel-bundler once that's done all the things, we're now ready for some "modern client-side development" (which really means using ...
...an be empty; it just needs to exist. create this now. having fun with parcel now we’ll run our newly installed parcel tool. in your terminal, run the following command: parcel index.html you should see something like this printed to your terminal: server running at http://localhost:1234 ✨ built in 193ms. note: if you have trouble with the terminal returning a "command not found" type
error, try running the above command with the npx utility, i.e. npx parcel index.html. now we're ready to benefit from the full javascript package ecosystem. for a start, there is now a local web server running at http://localhost:1234. go there now and you’ll not see anything for now, but what is cool is that when you do make changes to your app, parcel will rebuild it and refresh the server autom...
...sing the command parcel server filename.html, and we’d like to use that often during our development. so let’s create a custom shorthand command — “dev” — in our package.json. if you followed the tutorial from earlier, you should have a package.json file inside your parcel-experiment directory. open it up, and its scripts member should look like this: "scripts": { "test": "echo \"
error: no test specified\" && exit 1", }, update it so that it looks like this, and save the file: "scripts": { "test": "echo \"
error: no test specified\" && exit 1", "dev": "parcel serve index.html" }, we’ve added a custom dev command as an npm script. now try running the following in your terminal, making sure you are inside the parcel-experiment directory: npm run dev this should start ...
Android-specific test suites
there are several android-specific test suites that run on the firefox for android codebase: android-test ensures that the code passes unit tests. android-checkstyle ensures that the java coding style is consistent throughout. android-findbugs ensures that the code avoids common java coding
errors. android-lint ensures that the code avoids common android coding
errors. all of these suites require a functioning build of firefox for android — either a full build or an artifact build. all of the suites are configured by and invoked using gradle. android-test runs android-specific local unit tests. these tests are local — they run on your development machine and do not require an android device or android emulator. local unit tests are the fastest to develop and execute, but...
...alent to the eslint jobs that check the javascript coding style throughout the tree. however, the existing configuration can be tweaked and the set of files checked can be modified. contact information android-checkstyle is currently owned by :mcomella and :nalexander. file tickets in the firefox for android product in bugzilla. android-findbugs ensures that the code avoids common java coding
errors. using this suite will allow the code to be analyzed to spot any design flaws or potential bugs. if an issue is found within the code, a warning will be identified and put into the correct category that the suite controls — this could be malicious, correctness, or just bad practice. see http://findbugs.sourceforge.net/index.html and https://docs.gradle.org/2.14/userguide/findbugs_plugin.html...
...l, it's not sensible to allow new java code to land that findbugs detects issues with. however, the existing configuration can be tweaked and the set of files checked can be modified. contact information android-checkstyle is currently owned by :mcomella and :nalexander. file tickets in the firefox for android product in bugzilla. android-lint ensure that the code avoids common android coding
errors. lint is a code scanning tool that identifies problems in the code regarding quality. it is a fast process that can be run on unexecuted code, and test cases are not needed for the process to be completed. lint is a simple test that can assure you have a quality code. see https://developer.android.com/studio/write/lint.html and http://tools.android.com/tips/lint for more details. running andr...
Debugging Frame Reflow
tablerowgroup row tablerow textctl textinput text text vp viewport once the problem is reduced to a single frame level, placing a breakpoint at displayreflowenterprint in nsframe.cpp is a very efficient way to step through the reflow tree. other reflow debug options gecko_display_reflow_flag_pixel_
errors setting this option via set gecko_display_reflow_flag_pixel_
errors = 1 enables a verification for each coordinate value that the coordinates are aligned at pixel boundaries. row 0268a594 r=0 a=uc,uc c=uc,20 cnt=870 value 20 is not a whole pixel cell 0268a6c0 r=0 a=uc,uc c=uc,15 cnt=871 block 0268a764 r=0 a=uc,uc c=uc,uc cnt=872 block 0...
...gecko_display_reflow_indent_undisplayed_frames setting this option via set gecko_display_reflow_indent_undisplayed_frames = 1 will cause an advance of the indent even for frames which are blocked via the reflow rules file. original document information author(s): bernd mielke la...
...k 0268a764 d=0,0 me=0 cell 0268a6c0 d=0,0 me=0 row 0268a594 d=uc,20 value 20 is not a whole pixel rowg 0268a02c d=uc,695 value 695 is not a whole pixel while unaligned values at the entrance of a frame reflow can be ignored, when they appear at the exit of a routine this can cause display
errors like stray lines. os2 is very vulnerable to pixel alignment
errors as text is drawn on pixel boundaries. gecko_display_reflow_indent_undisplayed_frames setting this option via set gecko_display_reflow_indent_undisplayed_frames = 1 will cause an advance of the indent even for frames which are blocked via the reflow rules file. original document information author(s): bernd mielke last updated date: december 4, 2004 copyright information: portio...
Debugging JavaScript
d to help developers writing javascript code in mozilla, mainly for mozilla itself, but it may also be useful for web developers. it should give pointers to tools, aids and tricks which make debugging your code easier. web console this is the first place to go when you're debugging a web page; open the web console using the web console option in the web developer menu. this shows any javascript
errors in your app, as well as any logging calls from the console api. browser console the browser console lets you see all javascript
errors and logging in the browser, including from firefox code. to enable it, go to about:config in the url bar and set devtools.chrome.enabled to true, or set the "enable chrome and add-on debugging" option in the developer tool settings. activate it through with the...
... > browser console. you can also start the browser console when you launch firefox, by launching firefox from the command line and passing --jsconsole as a flag: /path/to/firefox --jsconsole log to the browser console using the standard console api after importing console.jsm: let console = (cu.import("resource://gre/modules/console.jsm", {})).console; console.log("hello from firefox code");
error console this is obsolete and is no longer enabled in firefox by default. use the web console or the browser console instead. browser debugger (built-in) on firefox 19 or later, it's possible to use the built-in js debugger on the browser itself. go to about:config and set the following two prefs: devtools.chrome.enabled: true devtools.debugger.remote-enabled: true after you restart the brow...
...he devtools.debugger.force-local preference to false.) then, the browser toolbox displays the available tools for debugging. (note that before firefox 28, only the script debugger was available.) the use of these tools are the same as the built-in tools. strict code checking if you set the pref javascript.options.strict to true, the javascript engine gives you more types of warnings on the
error console, most of which hint at code bugs that are easy to oversee or even bad syntax. (the pref also warns on common javascript idioms that are not
errors). console.log in browser console you can dump variables in the browser console from addon code, by adding this line to import the console utility: const { console } = components.utils.import("resource://gre/modules/devtools/console.jsm", {})...
ESLint
-l eslint browser/components or work directory changes: ./mach lint -l eslint -w or outgoing commits only: ./mach lint -l eslint -o see ./mach eslint --help for more options when running eslint. vcs hooks hooks are available for mercurial & git, see using a vcs hook for more details. editor integration it is highly recommended that you integrate eslint into your editor. this lets you see
errors in real time, and can help you fix issues before you compile or run tests, reducing the time to develop patches. see the eslint user guide for which plugins to install in your editor. prior to firefox 55 the location for the eslint binary used to be tools/lint/eslint/node_modules/.bin, since bug 1305023, node_modules is now located in the top-level directory, and should need no special set-up...
... you fix issues before you compile or run tests, reducing the time to develop patches. see the eslint user guide for which plugins to install in your editor. prior to firefox 55 the location for the eslint binary used to be tools/lint/eslint/node_modules/.bin, since bug 1305023, node_modules is now located in the top-level directory, and should need no special set-up. understanding rules and
errors not all files are linted currently eslint runs on: .js .jsx .jsm .xml .html .xhtml additionally, some directories and files are ignored, see the .eslintignore file handling
errors if your code fails an eslint rule, you'll get an
error similar to this: /gecko/toolkit/mozapps/installer/js-compare-ast.js 18:39
error 'snarf' is not defined. no-undef (eslint) if you don't un...
...de_modules folder. node.js is not recognized add it to your path environment variable by running path="$path:/path/to/node.js/". for example: in windows 10, if you have installed node.js on "c:\nodejs", then the command should look like: export path=$path:/c/nodejs enabling eslint for a new directory remove the directory from .eslintignore (in the base directory of the repository) fix
errors that occur when running ./mach eslint path/to/dir, see also the no-undef rules below. no-undef the no-undef rule is currently being enabled throughout the code base. here are some common issues: my script is imported into the global browser.xul scope. add a line like: /* eslint-env mozilla/browser-window */ or enable the rule in a .eslintrc.js if it will apply t...
Gecko Logging
theses. moz_log_test(module, level) checks if the module has the given level enabled. module - the log module to use. level - the output level of the message. log level numeric value purpose mozilla logging levels disabled 0 indicates logging is disabled. this should not be used directly in code.
error 1 an
error occurred, generally something you would consider asserting in a debug build. warning 2 a warning often indicates an unexpected state. info 3 an informational message, often indicates the current program state. debug 4 a debug message, useful for debugging but too verbose to be turned on normally. verbose 5 a message that...
... while (i++ < 10) { moz_log(slogger, loglevel::verbose, ("i = %d", i)); } // only calculate the elapsed time if the warning level is enabled. if (moz_log_test(slogger, loglevel::warning)) { int elapsed = time::nowms() - start; if (elapsed > 1000) { moz_log(slogger, loglevel::warning, ("loop took %dms!", elapsed)); } } if (i != 10) { moz_log(slogger, loglevel::
error, ("i should be 10!")); } } enabling logging the log level for a module is controlled by setting an environment variable before launching the application. it can also be adjusted by setting prefs. by default all logging output is disabled. set moz_log="example_logger:3" in the windows command prompt (cmd.exe), don't use quotes: set moz_log=example_logger:3 if you want this on geckoview...
...erbose: set rust_log="debug" you can also target individual modules by path: set rust_log="style::style_resolver=debug" for linux/macos users, you need to use export rather than set. if you're only interested in the content process you can use rust_log_child rather than rust_log. the log crate lists the available log levels: log level purpose rust logging levels
error designates very serious
errors. warn designates hazardous situations. info designates useful information. debug designates lower priority information. trace designates very low priority, often extremely verbose, information. it is common for debug and trace to be disabled at compile time in release builds, so you may need a debug build if ...
JavaScript OS.Constants
th to the local applications directory. os.constants.libc constants for interacting with libc. useful mostly for using js-ctypes to interact with the following platforms: macos x; android; linux; other variants of unix. os.constants.libc is available on all platforms, although some constants are not defined everywhere. before using a constant, you should check that it is defined. ...
...nstants are not defined everywhere. before using a constant, you should check that it is defined.
error values eacces permission denied eagain resource temporarily unavailable ebadf bad file descriptor eexist file exists efault bad address efbig file too large einval invalid argument eio input/output
error eisdir is a directory eloop (not always available under windows) too many levels of symbolic links. emfile too many open files in the process enametoolong name too long enfile too many open files on the system enoent no such file or directory enomem cannot allocate memory enospc no space on de...
...write (modify) the file. s_ixoth all other users can execute the file. unix opening mode o_append open the file for appending. o_creat create the file if it does not exist yet. o_directory (linux only) succeed only of the file is a directory. o_evtonly descriptor requested for event notifications only. o_excl raise an
error if o_creat is set and the file exists. o_exlock atomically obtain an exclusive lock. o_largefile o_nofollow do not follow symbolic links. o_nonblock do not block on open or for data to become available. o_rdonly open the file for read only. o_rdwr open the file for read and write. o_rsync o_shlock ...
Localization content best practices
ngs don't land temporary strings. if you already know that your strings are temporary, they shouldn't be exposed to the localization process. this would waste everybody's time and create unnecessary frustration: localizers have to translate strings that are destined to change, developers will need to use new ids later to update them. if you're reviewing a patch, check also strings for grammar
errors, capitalization or inconsistencies. for example, use the single unicode …, and not three dots. if you have any doubts about the quality of strings, ask a copywriter to do a copy review of this text. ideally, all strings landing in code should originate from approved ux wireframes, any copy review should be part of the initial stage of creating these wireframes. use unicode characters over th...
...d, and those that don't and work on mirroring the verb. for example, a do you want to open the page? > yes/no dialog works in english, but in gaelic/irish/welsh and several other languages the equivalent answer is want/not want. w3c has a good guide on the length ratios a developer should be prepared for. test localizability as a developer, you should always test your patches not just for code
errors, but also for localizability issues in case they involve string or ui changes. gecko and mozilla-central first, make sure that there are no hard-coded strings, and all strings are available in localization files (.dtd, .properties). one possible way to test a patch for localizability issues is to alter the en-us localization files, adding extraneous characters to the original strings: this can...
...o the original strings: this can help to identify both hard-coded strings and "flexibility issues" in the ui. changing existing strings updating entity names if you are changing a string such that its meaning has changed, you must update the entity or property name for the string to match the new meaning. if your changes are relevant only for english — for example, to correct a typographical
error or to make letter case consistent — then there is generally no need to update the entity name. changing the string id will invalidate the existing translation, the new string will be reported as missing in all tools, and localizers will have to retranslate it. given the diversity of tools used by localization teams, this is the only reliable method to ensure that localizers update existing loc...
Localization formats
with this arrangement, content for localization is presented in the following manner: msgid "coming soon" msgstr "bientôt disponible" where the value in the "" of the msgid is the...
...with this arrangement, content for localization is presented in the following manner: msgid "coming soon" msgstr "bientôt disponible" where the value in the "" of the msgid is the english content, and the value in the "" of the msgstr is the transla...
...t in a special repository. but, in the download day example, when changes were made to en-us, the web-developer had to push those changes to all the repositories of all the locales. localizers had to revisit an en-us repository to find the exact msgid, review the change, and return to their repository to make changes. without having the exact content as the msgid, this process may cause several
errors since the localizers cannot has to continually switch back-and-forth. in this case, the choice to use customized values for msgid was
error-prone, onerous, and unfamiliar to localizers who are used to more customary gettext operations. ...
Nonblocking IO In NSPR
ished. the blocking io model encourages the use of multiple threads as a programming model. a thread is typically created to attend to one of the simultaneous i/o operations that may potentially block. in the nonblocking io model, a file descriptor may be marked as nonblocking. an io function on a nonblocking file descriptor either succeeds immediately or fails immediately with <tt>pr_would_block_
error</tt>. a single thread is sufficient to attend to multiple nonblocking file descriptors simultaneously. typically, this central thread invokes <tt>pr_poll()</tt> on a set of nonblocking file descriptors. (note: <tt>pr_poll()</tt> also works with blocking file descriptors, although it is less useful in the blocking io model.) when <tt>pr_poll()</tt> reports that a file descriptor is ready for some ...
...o never blocks. fundamentally, this constraint is due to the fact that nonblocking i/o and <tt>select()</tt> are only available to sockets on some platforms (e.g., winsock). in nspr, a new socket returned by <tt>pr_newtcpsocket()</tt> or <tt>pr_newudpsocket()</tt> is always created in blocking mode. one can make the new socket nonblocking by using <tt>pr_setsockopt()</tt> as in the example below (
error checking is omitted for clarity): <tt>prfiledesc *sock;</tt> <tt>printn optval = 1;</tt> <tt>sock = pr_newtcpsocket();</tt> /* * make the socket nonblocking */ pr_setsockopt(sock, pr_sockopt_nonblocking, &optval, sizeof(optval)); programming constraints there are some constraints due to the use of nt asynchronous i/o in the nspr. in nspr, blocking sockets on nt are associated with an i/o com...
...descriptors (socket handles) cannot be added to <tt>pr_fd_set</tt>, i.e., the functions <tt>pr_fd_nset</tt>, <tt>pr_fd_nclr</tt>, <tt>pr_fd_nisset</tt> do not work. pr_available() when <tt>pr_available()</tt> returns 0, it may mean one of two things: there is no data available for reading on that socket. i.e., <tt>pr_recv()</tt> would block (a blocking socket) or fail with <tt>pr_would_block_
error</tt> (a nonblocking socket). the tcp connection on that socket has been closed (end of stream). these two cases can be distinguished by <tt>pr_poll()</tt>. if <tt>pr_poll()</tt> reports that the socket is readable (i.e., <tt>pr_poll_read</tt> is set in <tt>out_flags</tt>), and <tt>pr_available()</tt> returns 0, this means that the socket connection is closed. current status implemented acros...
PR_OpenSharedMemory
shm_create 0x1 /* create if not exist */ #define pr_shm_excl 0x2 /* fail if already exists */ parameters the function has the following parameters: name the name of the shared memory segment. size the size of the shared memory segment. flags options for creating the shared memory. mode same as passed to pr_open. returns pointer to opaque structure prsharedmemory, or null if an
error occurs. retrieve the reason for the failure by calling pr_get
error and pr_getos
error. description pr_opensharedmemory creates a new shared memory segment or associates a previously created memory segment with the specified name. when parameter create is (pr_shm_excl | pr_shm_create) and the shared memory already exists, the function returns null with the
error set to pr_file_exists_
error. when...
... ...
... ...
PR_ReadDir
resenting the parent directory. pr_skip_both. skip both "." and ".." pr_skip_hidden. skip hidden files. on windows platforms and the mac os, this value identifies files with the "hidden" attribute set. on unix platform, this value identifies files whose names begin with a period ("."). returns a pointer to the next entry in the directory. if the end of the directory is reached or an
error occurs, null. the reason can be retrieved via pr_get
error. description pr_readdir returns a pointer to a directory entry structure: struct prdirentry { const char *name; }; typedef struct prdirentry prdirentry; the structure has the following field: name name of entry, relative to directory name. the flags parameter is an enum of type prdirflags: typedef enum prdirflags { pr_ski...
... see also pr_opendir ...
... see also pr_opendir ...
4.3 Release Notes
o configdir parameter for crypomanager.initialize method or using the nss environment variable nss_default_db_type. ...
...ent variable nss_default_db_type. ...
...: an rfc 3280 compliant certificate path validation library (see pkixverify) pk11token.needslogin method (see needslogin) support hmacsha256, hmacsha384, and hmacsha512 (see hmactest.java) support for all nss 3.12 initialization options (see initializationvalues) new ssl
error codes (see http://mxr.mozilla.org/security/sour...util/sslerrs.h) ssl_
error_unsupported_extension_alert ssl_
error_certificate_unobtainable_alert ssl_
error_unrecognized_name_alert ssl_
error_bad_cert_status_response_alert ssl_
error_bad_cert_hash_value_alert new tls cipher suites (see http://mxr.mozilla.org/security/sour...sslsocket.java): tls_rsa_with_camellia_128_cbc_sha tls_dhe_dss_with_camellia_128_cbc_sha tls_dhe_rsa_with_camellia_128_cbc_sha tls_rsa_with_camellia_256_cb...
NSS 3.12.6 release notes
ction is intended for use when ocsp responses are provided via a side-channel, i.e. tls ocsp stapling (a.k.a. the status_request extension). ...
...annel, i.e. tls ocsp stapling (a.k.a. the status_request extension). ...
... status_request extension). ...
NSS 3.12.9 release notes
tp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3.12.9_rtm/src/. you also need to download the nspr 4.8.7 binary distributions to get the nspr 4.8.7 header files and shared libraries, which nss 3.12.9 requires. nspr 4.8.7 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.7/. new in nss 3.12.9 removed functions new ssl options new
error codes bugs fixed the following bugs have been fixed in nss 3.12.9. bug 609068: implement j-pake in freebl bug 607058: crash [@ nss_cms_decoder_work_data] bug 613394: november/december 2010 batch of nss root ca changes bug 610843: need way to recover softoken in child after fork() bug 617492: add pk11_keygenwithtemplate function to pk11wrap (for firefox sync) bug 610162: sha...
...in pkits tests. bug 536485: crash during ssl handshake in [@ intel_aes_decrypt_cbc_256] bug 444367: nss 3.12 softoken returns the certificate type of a certificate object as ckc_x_509_attr_cert. bug 620908: certutil -t -d "sql:." dumps core bug 584257: need a way to expand partial private keys. ...
...rash during ssl handshake in [@ intel_aes_decrypt_cbc_256] bug 444367: nss 3.12 softoken returns the certificate type of a certificate object as ckc_x_509_attr_cert. bug 620908: certutil -t -d "sql:." dumps core bug 584257: need a way to expand partial private keys. ...
NSS 3.14 release notes
on-specific security policies, allowing libpkix to continue discovering certificate paths until it can find a chain that satisfies the policies. ...
...rity policies, allowing libpkix to continue discovering certificate paths until it can find a chain that satisfies the policies. ...
...pkix to continue discovering certificate paths until it can find a chain that satisfies the policies. ...
NSS Sample Code sample4
tcertificate *cert = null; seckeypublickey *pubkey = null; seckeyprivatekey *pvtkey = null; int modulus_len, i, outlen; char *buf1 = null; char *buf2 = null; /* initialize nss */ pk11_setpasswordfunc(passwdcb); rv = nss_init("."); if (rv != secsuccess) { fprintf(stderr, "nss initialization failed (err %d)\n", pr_get
error()); goto cleanup; } cert = pk11_findcertfromnickname("testca", null); if (cert == null) { fprintf(stderr, "couldn't find cert testca in nss db (err %d)\n", pr_get
error()); goto cleanup; } pubkey = cert_extractpublickey(cert); if (pubkey == null) { fprintf(stderr, "couldn't extract public key from cert testca (err %d)\n", pr_get
error()); ...
...* initialize buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= (i %26) + 'a'; } buf1[modulus_len-1] = '\0'; fprintf(stderr, "buffer being encrypted = \n%s\n", buf1); /* encrypt buf1, result will be in buf2 */ rv = pk11_pubencryptraw(pubkey, buf2, buf1, modulus_len, null); if (rv != secsuccess) { fprintf(stderr, "encrypt with public key failed (err %d)\n", pr_get
error()); goto cleanup; } pvtkey = pk11_findkeybyanycert(cert, null); if (pvtkey == null) { fprintf(stderr, "couldn't find private key for cert testca (err %d)\n", pr_get
error()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } /* decrypt buf2, result will be in buf1 */ rv = pk11_pubdecryptraw(pvtkey, buf1, &outlen, mo...
...d)\n", pr_get
error()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } /* decrypt buf2, result will be in buf1 */ rv = pk11_pubdecryptraw(pvtkey, buf1, &outlen, modulus_len, buf2, modulus_len); if (rv != secsuccess) { fprintf(stderr, "decrypt with private key failed (err %d)\n", pr_get
error()); goto cleanup; } fprintf(stderr, "result of decryption, outlen = %d\n", outlen); fprintf(stderr, "result of decryption, buf = \n%s\n", buf1); exit(0); cleanup: if (cert) cert_destroycertificate(cert); if (pubkey) seckey_destroypublickey(pubkey); if (pvtkey) seckey_destroyprivatekey(pvtkey); if (buf1) free(buf1); if (buf2) free(buf2); exit(1); } c...
Utilities for nss samples
util.h /* this source code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. */ #ifndef _util_h #define _util_h #include <prlog.h> #include <termios.h> #include <base64.h> #include <unistd.h> #include <sys/stat.h> #include "util.h" #include <prprf.h> #include <pr
error.h> #include <nss.h> #include <pk11func.h> /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications. */ typedef struct { enum { pw_none = 0, /* no password */ pw_fromfile = 1, /* password stored in a file */ pw_plaintext = 2 /* plain-text password passed in buffer ...
...lename, &stbuf); return stbuf.st_size; } /* * readderfromfile */ secstatus readderfromfile(secitem *der, const char *infilename, prbool ascii) { secstatus rv = secsuccess; prfiledesc *infile = null; infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "failed to open file \"%s\" (%ld, %ld).\n", infilename, pr_get
error(), pr_getos
error()); rv = secfailure; goto cleanup; } if (ascii) { /* first convert ascii to binary */ secitem filedata; char *asc, *body; /* read in ascii data */ rv = filetoitem(&filedata, infile); asc = (char *)filedata.data; if (!asc) { pr_fprintf(pr_stderr, "unable to read data from input file\n"); ...
... } else { pr_fprintf(pr_stderr, "input has header but no trailer\n"); port_free(filedata.data); rv = secfailure; goto cleanup; } } else { body = asc; } /* convert to binary */ rv = atob_convertasciitoitem(der, body); if (rv) { pr_fprintf(pr_stderr, "
error converting ascii to binary %s\n", port_get
error()); port_free(filedata.data); rv = secfailure; goto cleanup; } port_free(filedata.data); } else { /* read in binary der */ rv = filetoitem(der, infile); if (rv) { pr_fprintf(pr_stderr, "
error converting der \n"); rv = secfa...
NSS environment variables
ke if a server or client do not support safe renegotiation. the default setting for this option is false. 3.12.5 nss_ssl_server_cache_mutex_timeout integer (seconds) timeout time to detect dead or hung process in multi-process ssl server. default is 30 seconds. 3.4 nss_strict_nofork string ("1", "disabled", or any other non-empty value) it is an
error to try to use a pkcs#11 crypto module in a process before it has been initialized in that process, even if the module was initialized in the parent process. beginning in nss 3.12.3, softoken will detect this
error. this environment variable controls softoken's response to that
error. if set to to "1" or unset, softoken will trigger an assertion failure in debug builds, and will report a...
...o try to use a pkcs#11 crypto module in a process before it has been initialized in that process, even if the module was initialized in the parent process. beginning in nss 3.12.3, softoken will detect this
error. this environment variable controls softoken's response to that
error. if set to to "1" or unset, softoken will trigger an assertion failure in debug builds, and will report an
error in non-debug builds. if set to "disabled", softoken will ignore forks, and behave as it did in older versions. if set to any other non-empty value, softoken will report an
error in both debug and non-debug builds. 3.12.3 nss_strict_shutdown string (any non-empty value) will trigger an assertion failure in debug builds when a program tries to shutdown nss ...
...lean (1 to enable) on systems where gcc is not the default compiler, this tells nss to build with gcc. before 3.0 nss_allow_sslkeylogfile boolean (1 to enable) enable nss support in optimized builds for logging ssl/tls key material to a logfile if the sslkeylogfile environment variable. as of nss 3.24 this is disabled by default. 3.24 nss_build_continue_on_
error boolean (1 to enable) continue building nss source directories when a build
error occurs. 3.12.4 nss_use_system_sqlite boolean (1 to enable) use the system installed sqlite library instead of the in-tree version. 3.12.6 nss_disable_ecc (deprecated) boolean (1 to disable) disable elliptic curve cryptography features. as of nss 3.16, ecc fe...
sslcrt.html
ageusercertimport certusageverifyca certusageprotectedobjectsigner wincx the pin argument value to pass to pk11 functions. see description below for more information. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_get
error to obtain the
error code. description the cert_verifycertnow function must call one or more pk11 functions to obtain the services of a pkcs #11 module. some of the pk11 functions require a pin argument (see ssl_setpkcs11pinarg for details), which must be specified in the wincx parameter. to obtain the value to pass in the wincx parameter, call ssl_revealpinarg. cert_verifycertname compa...
... the hostname to be checked. returns the function returns one of these values: if the common name in the subject dn for the certificate matches the domain name passed in the hostname parameter, secsuccess. if the common name in the subject dn for the certificate is not identical to the domain name passed in the hostname parameter, secfailure. use pr_get
error to obtain the
error code. description the comparison performed by cert_verifycertname is not a simple string comparison. instead, it takes account of the following rules governing the construction of common names in ssl server certificates: * matches anything ? matches one character \ escapes a special character $ matches the end of the string [abc] matches one occurrence...
...e whose certificate chain is to be checked. canames a pointer to a structure that contains a list of distinguished names (dns) against which to check the dns for the signers in the certificate chain. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_get
error to obtain the
error code. manipulating certificates cert_dupcertificate cert_destroycertificate cert_dupcertificate makes a shallow copy of a specified certificate. syntax #include <cert.h> certcertificate *cert_dupcertificate(certcertificate *c) parameter this function has the following parameter: c a pointer to the certificate o...
ssltyp.html
ctions. syntax #include <seccomon.h> typedef enum { secwouldblock = -2, secfailure = -1, secsuccess = 0 } secstatus; enumerators the enum includes the following enumerators: secwouldblock reserved for internal use. secfailure the operation failed. to find out why, call pr_get
error. secsuccess the operation succeeded. in this case the value returned by pr_get
error is meaningless. managing secitem memory these functions are available for managing the memory associated with secitem structures and the structures to which they point. secitem_freeitem secitem_zfreeitem secitem_freeitem frees the ...
...tem a pointer to a secitem structure. freeitem when pr_false, free only the structure pointed to. otherwise, free both the structure pointed to and the secitem structure itself. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_get
error to retrieve the
error code. description this function frees the memory associated with the structure to which the specified item points, when that structure is no longer used. when freeitem is not pr_false, also frees the item structure itself. secitem_zfreeitem zeroes and frees the memory associated with a secitem structure. syntax #include <prtypes.h> secstatus secitem_zfreeitem (...
...tem a pointer to a secitem structure. freeitem when pr_false, free only the structure pointed to. otherwise, free both the structure pointed to and the secitem structure itself. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_get
error to retrieve the
error code. description this function is similar to secitem_freeitem, except that it overwrites the structures to be freed with zeroes before it frees them. zeros and frees the memory associated with the structure to which the specified item points, when that structure is no longer used. when freeitem is not pr_false, also zeroes and frees the item structure itself. ...
NSS tools : signtool
-c# option is not used with the -j option, the default compression value is 6. note that versions 1.1 and later of netscape signing tool correctly recognizes the codebase attribute, allows paths to be expressed for the class and src attributes instead of filenames only, processes link tags and parses html correctly, and offers clearer
error messages. -l lists the certificates in your database. an asterisk appears to the left of the nickname for any certificate that can be used to sign objects with signtool. --leavearc retains the temporary .arc (archive) directories that the -j option creates. these directories are automatically erased by default. retaining ...
... the ca's digital signature on the object-signing certificate is valid, that the relevant certificates have not expired, and so on. --verbosity value sets the quantity of information netscape signing tool generates in operation. a value of 0 (zero) is the default and gives full information. a value of -1 suppresses most messages, but not
error messages. -w archive displays the names of signers of any files in the archive. -x directory excludes the specified directory from signing. note that with netscape signing tool version 1.1 and later this option can appear multiple times on one command line, making it possible to specify several particular directories to e...
.... keysize same as -s option. token same as -t option. verify same as -v option. who same as -w option. exclude same as -x option. notime same as -z option. value is ignored, but = sign must be present. jarfile same as -z option. outfile name of a file to which output and
error messages will be redirected. this option has no command-line equivalent. extended examples the following example will do this and that listing available signing certificates you use the -l option to list the nicknames for all available certificates and check which ones are signing certificates. signtool -l using certificate directory: /u/jsmith/.netscape s certific...
Installing Pork
stead, make sure the commands will be found on the path, as above. svn co https://mcpp.svn.sourceforge.net/svnroot/mcpp/trunk mcpp cd mcpp ./configure --enable-replace-cpp make sudo make install note: if you followed the dehydra installation instructions for linux and compiled your own gcc, then you should not need to "sudo" make install. if you run simply "make install" and see file permission
errors, mcpp is likely trying to override your main gcc installation. make sure that (1) your "$path" is correct; (2) you passed the correct "cc=..." and "cxx=..." to "./configure". install the pork stack pork is a set of tools written at mozilla for refactoring c++. pork's aim is to simply doing c/c++ refactoring through elsa. hg clone http://hg.mozilla.org/rewriting-and-analysis/pork/ cd pork hg c...
...see the mcpp manual. in particular, -k tells mcpp to add the macro annotations we use to get exact source positions. c++ files from other projects can be preprocessed with gcc -e -wp,-w0,-k. building a 32-bit mcpp on a 64-bit system this is dark magic, and i hope i've got it right. first i built gcc in a separate --...
...see the mcpp manual. in particular, -k tells mcpp to add the macro annotations we use to get exact source positions. c++ files from other projects can be preprocessed with gcc -e -wp,-w0,-k. building a 32-bit mcpp on a 64-bit system this is dark magic, and i hope i've got it right. first i built gcc in a separate --prefix=/builds/gcc-3.4.6-i...
Pork Tools
outparamdel outparamdel converts functions to return via return value instead of an outparam. it takes a list of functions as input and rewrites the definition and call sites of those functions. <caption>rewrites performed</caption> nsresult getter(nsifoo **aresult) { *aresult = ... ...
...ion> nsresult getter(nsifoo **aresult) { *aresult = ... if (!*aresult) return ns_
error_failure; return ns_ok; } nsifoo* getter() { nsifoo *result = null; // aresult below is kept for complicated cases // typically it wont be needed and can be removed nsifoo **aresult = &result; // *aresult patterns are replaced with result result = ... ...
... nsresult rv2 = getter(&var); ns_ensure_success(rv2,rv2); } caller1 { // case 1 // figure out that rv was only used for the rewritten // outparam call + ns_ensure_success. then nuke the declaration // nsresult rv; // move outparam to lhs var = getter(); // detect ns_ensure_success immediately following // and change it to an equivalent ns_ensure_true ns_ensure_true(var, ns_
error_failure); // case 2 var = getter(); // case 3, eliminate rv2 decl given that it's not used elsewhere var = getter(); ns_ensure_true(var, ns_
error_failure) } outparamdel also support rewriting getters such that they return already_addrefed<nsifoo>. in this case all of the callsites are modified to: a) getter_addrefs case: getter(getter_addrefs(foo)) -> foo = getter() b) al...
Scripting Java
ote that java imports java.lang.* implicitly, while rhino does not. the reason is that javascript has its own top-level objects boolean, math, number, object, and string that are different from the classes by those names defined in the java.lang package. because of this conflict, it's a good idea not to use importpackage on the java.lang package. one thing to be careful of is rhino's handling of
errors in specifying java package or class names. if java.myclass is accessed, rhino attempts to load a class named java.myclass. if that load fails, it assumes that java.myclass is a package name, and no
error is reported: js> java.myclass [javapackage java.myclass] only if you attempt to use this object as a class will an
error be reported. external packages and classes external packages and cla...
...time. although this has the benefit of selecting a method that may be a better match for each call, it does have an impact on performance since more work is done at each call. in practice this performance cost hasn't been noticeable in real applications. because overload resolution occurs at runtime, it can fail at runtime. ...
...nal 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. ...
Exact Stack Rooting
ehandle<t> typedef js::mutablehandle<t> js::mutablehandlet; -> mutablehandleobject, mutablehandlestring, etc. the purpose of js::mutablehandlet is to allow out-parameters for rooted gcthings. this class solves two problems: c++ only allows one level of user-defined implicit type conversion. when passed to an out-param, &handle would convert correctly to js::handlet*, but &local is a compile
error. even though js::handlet is indirect, it implicitly behaves like the thing it is pointing to. this makes js::handlet and js::rootedt behave the same, allowing us to seamlessly weave js::handlets into the js api. the problem is that this requires us to overload operator->. if we have a method taking handle<value>*, then out->setobject(foo) will not work as expected. to solve these problems we h...
... (or nullptr) does not implicitly convert to a js::handlet. for places where you want to pass a null value into a function taking a js::handlet, you can construct and pass a new nullptr instance. you are free to use these as temporaries. rootedobject obj(cx, js_newobject(cx, clasp, nullptr(), nullptr()); common pitfalls the c++ type system allows us to eliminate the possibility of most common
errors; however, there are still a few things that you can get wrong that the compiler cannot help you with. there is basically never a good reason to do any of these. if you think you do need to do one of these, ask on one of spidermonkey's support forums: maybe we've already solved your problem using a different mechanism. storing a js::rootedt on the heap. it would be very easy to violate the lif...
...ove js::rootedt declarations above loops. modern c++ compilers are not smart enough to do licm on js::rootedt, so forward declaring a single js::rootedt above the loop and re-using it on every iteration can save some cycles. raw pointers. if you are 100% sure that there is no way for spidermonkey to gc while the pointer is on the stack, this is an option. note: spidermonkey can gc because of any
error, gc because of timers, gc because we are low on memory, gc because of environment variables, gc because of cosmic rays, etc. this is not a terribly safe option for embedder code, so only consider this as a very last resort. ...
JSExnType
this article covers features introduced in spidermonkey 17 possible exception types. value prototype in javascript jsexn_none an unthrowable
error. (lower bound) jsexn_err
error jsexn_internalerr internal
error jsexn_evalerr eval
error jsexn_rangeerr range
error jsexn_referenceerr reference
error jsexn_syntaxerr syntax
error jsexn_typeerr type
error jsexn_urierr uri
error jsexn_limit (upper bound) description these types are part of a js
errorformatstring structure. ...
... jsexn_internalerr internal
error jsexn_evalerr eval
error jsexn_rangeerr range
error jsexn_referenceerr reference
error jsexn_syntaxerr syntax
error jsexn_typeerr type
error jsexn_urierr uri
error jsexn_limit (upper bound) description these types are part of a js
errorformatstring structure. they define which
error to throw in case of a runtime
error. jsexn_none marks an unthrowable
error. ...
...referenceerr reference
error jsexn_syntaxerr syntax
error jsexn_typeerr type
error jsexn_urierr uri
error jsexn_limit (upper bound) description these types are part of a js
errorformatstring structure. they define which
error to throw in case of a runtime
error. jsexn_none marks an unthrowable
error. ...
JS_CompileFunction
to the function. argnames const char ** names to assign to the arguments passed to the function. body const char * or const jschar * string containing the body of the function to compile. length size_t the length, in characters, of body. filename const char * name of file or url containing the function. used to report filename or url in
error messages. lineno unsigned int line number. used to report the offending line in the file or url if an
error occurs. description js_compilefunction compiles a function from a text string, bytes, and optionally associates it with a js object, obj. js_compileucfunction is the unicode version of the function. name is the name to assign to the newly created function. nargs is t...
... takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. body is a string containing the source code of the function. length is the length of the source code in characters. filename is the name of the file (or url) containing the function. this information is used in
error messages if an
error occurs during compilation. 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...
...during compilation. 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 1089...
JS_ConvertArguments
ts to convert. added in spidermonkey 31 argc unsigned the number of arguments to convert. obsolete since jsapi 30 argv jsval * pointer to the vector of arguments to convert. obsolete since jsapi 30 this must be an argv pointer created by the js engine and passed to a jsnative or jsfastnative callback, not an array created by application code. in certain
error cases, js_convertarguments calls js_argv_callee(argv), which accesses memory outside the range [argv .. argv+argc). js_convertarguments may modify argv in place by replacing an argument with the converted value. (the purpose is to ensure gc safety.) format const char * null-terminated string describing the types of the out parameters and how to convert the values in argv. ...
...on safely. v jsval argument value (no conversion) * n/a none. if an asterisk (*) is present in format, it tells the conversion routine to skip converting the current argument. / n/a none. arguments after the slash are optional. if an optional argument is missing from argv, js_convertarguments neither assigns anything to any variable nor reports an
error. this function also takes in consideration any additional custom types defined on cx using js_addargumentformatter. for example, if format is "biob", then js_convertarguments converts the first js value in argv into a bool, the second value into a double, the third value into a jsobject *, and the last value into a bool. to skip a given argument, pass an asterisk in the corresponding pos...
...formatter. for example, if format is "biob", then js_convertarguments converts the first js value in argv into a bool, the second value into a double, the third value into a jsobject *, and the last value into a bool. to skip a given argument, pass an asterisk in the corresponding position in format. if argc is less than the number of arguments required by format, js_convertargument reports an
error and returns false. if argc is greater than the number of arguments described in format, the extraneous arguments are ignored. on success, js_convertargument returns true. if any argument conversion fails or there are not enough arguments, it returns false. to perform the opposite conversion, converting values of various c types to an array of jsvals, use js_pusharguments. see also mxr id se...
JS_DeleteProperty
ons are identical to js_deleteproperty2 and js_deletepropertybyid2 except that they do not have an out parameter. first, a property lookup is performed. then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then obj's jsclass.delproperty hook is called. no property is deleted, but this is not an
error. if obj has the specified property but it is permanent, nothing happens. no property is deleted, but this is not an
error. otherwise obj has a non-permanent own property with the given name or id. in this case, obj's jsclass.delproperty hook is called. if the hook returns false, the
error is propagated. otherwise, if obj is not configurable, an
error is raised. otherwise, the property is remove...
...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. ...
...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. ...
JS_DeleteProperty2
same but takes a js::handleid for the property name. first, a property lookup is performed. then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded). no property is deleted, but this is not an
error. if obj has the specified property but it is permanent, then *succeeded receives false. no property is deleted, but this is not an
error. otherwise obj has a non-permanent own property with the given name or id. in this case, *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded). if the hook returns false, the
error is propagated. otherwise, if obj...
...ed property but it is permanent, then *succeeded receives false. no property is deleted, but this is not an
error. otherwise obj has a non-permanent own property with the given name or id. in this case, *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded). if the hook returns false, the
error is propagated. otherwise, if obj is not configurable, an
error is raised. otherwise, *succeeded receives true and the property is removed. these functions return true on success, regardless of whether a property was actually deleted. on
error or exception, the return value is false, and the value left in *succeeded is unspecified. jsobjectops.deleteproperty implements this behavior. (in javascript 1.2 and earlier, attempting to delete a permanent propert...
...there is no longer any way to get this behavior.) to remove all properties from an object, call js_clearscope. ...
JS_GetPropertyAttributes
* name of the property from which to retrieve attributes. namelen size_t (only in js_getucpropertyattributes) the length of name in characters; or (size_t) -1 to indicate that name is null-terminated. attrsp unsigned int * out parameter. if the specified property is found on obj, *attrsp receives its attributes. foundp jsbool * out parameter. ...
...ertyattributes) the length of name in characters; or (size_t) -1 to indicate that name is null-terminated. attrsp unsigned int * out parameter. if the specified property is found on obj, *attrsp receives its attributes. foundp jsbool * out parameter. if no
error occurs, *foundp receives js_true if the specified property is found and js_false if it is not found. if an
error occurs, the value left in *foundp is unspecified. description js_getpropertyattributes retrieves the property attributes of the property with the given name on a given object, obj. js_getucpropertyattributes is the unicode version of the function. if an
error occurs, the return value is js_false, and the values left in *attrsp and *foundp are unspecified. if obj does not have the specif...
... if the property exists and belongs to obj, then *foundp is set to js_true, *attrsp is set to the logical or of zero or more property attributes flags, and the function returns js_true. ...
JS_PreventExtensions
ient to prohibit new properties. in javascript this may be accomplished using the object.preventextensions method. the similar jsapi method is js_preventextensions. the failure-mode information below is new as of spidermonkey 36. before then, js_preventextensions did not accept a succeeded argument; in those cases where *succeeded would be set to false, js_preventextensions would throw a type
error and return false. unlike object.preventextensions, js_preventextensions doesn't necessarily throw a type
error if the object couldn't be made non-extensible. there are instead two modes of failure: through internal
error, and because the object denied the attempt. the first case occurs when something went wrong internally, not necessarily because the object chose not to become non-extensible. ...
...tion fails, out-of-memory might be reported, and js_preventextensions would return false. this might also occur if the object is a proxy, and some internal state of the proxy means that no coherent behavior is possible. for example, if the object is a revocable proxy that has been revoked, it makes no sense to say that an attempt to prevent extensions either succeeded or failed: it's a category
error. ...
...tensions would return false. this might also occur if the object is a proxy, and some internal state of the proxy means that no coherent behavior is possible. for example, if the object is a revocable proxy that has been revoked, it makes no sense to say that an attempt to prevent extensions either succeeded or failed: it's a category
error. thus in this case js_preventextensions will throw an
error. var target = {}; var handler = {}; var pair = proxy.revocable(target, handler); var proxy = pair.proxy; var revoke = pair.revoke; revoke(); // bool succeeded; // bool rv = js_preventextensions(cx, proxy, &succeeded); // // rv == false, succeeded is indeterminate the second case occurs when no internal
error is encountered, but the object simply refuses to be made non-extensible. for exampl...
JS_SetProperty
nal method defined in es2015 (rev 29 9.1.9) is performed. if the lookup found no property with the given name, or if it found that obj inherits such a property from a non-native object, then a new own property is added to obj, as described below. the new property is jsprop_enumerate. otherwise, if the lookup found a read-only property or obj non-extensible, nothing happens, but this is not an
error. in strict mode, a warning is issued. otherwise, if obj has an own property with the given name, then the existing property's value is set as described below. creation of new properties one of the cases above involves creating a new own property on obj. the name of the new property is given by name or id. the initial stored value of the new property is undefined. its getter and setter are the...
...gn to v. if the hook succeeds and the property has a stored value, then the value left in v by the addproperty hook becomes the stored value of the property. setting the value. two of the cases above can involve setting the value of a new or existing property of obj. this is done as follows. ...
... internally, property assignment, including all the behavior described above, is implemented by obj's jsobjectops.setproperty callback. ...
Web Replay
er developer tool will step to the previous line executed and allow inspecting program state there. it is the opposite of the normal forward step button. rewind to breakpoint when paused, if there are any breakpoints set then the rewind button will run back and stop at the last time a breakpoint was set. it is the opposite of the normal button for playing forward. seek to console messages
errors and logged messages in the console developer tool can be clicked on to cause the tab to seek to the point in the recording where the
error was generated or the message was logged. the tab will pause at this point and allow state to be inspected, forward/reverse stepping, and so forth. timeline the timeline is shown above the developer tools and provides several features to help with navigatin...
...e to be inspected, forward/reverse stepping, and so forth. timeline the timeline is shown above the developer tools and provides several features to help with navigating the recording: the timeline changes color depending on whether the tab is currently recording (red) or replaying (blue). the current position within the recording is shown on the timeline with a progress indicator. console
error/messages are marked on the timeline and can be clicked to seek to that point. advanced options preferences devtools.recordreplay.enablerewinding when disabled, firefox records a page signifcantly faster. default true. devtools.recordreplay.fastlogpoints when enabled, firefox web replay evaluates logpoints consecutively. logpoints cannot have side-effects or diverge from the recording in a...
... when a call/message is intercepted, the wrapped call/message is not performed, but rather the results of the call/message are read from the data stream and returned to the caller, emulating the behavior of the call/message. this requires the process to be deterministic enough that events play out in the same order on each thread between recording and replay. the data stream should have enough
error checking in place that we can immediately detect if the replay has gone out of sync with the recording. the recorded data streams which specify the acquisition order for each lock are read from and used so that locks are acquired in the same order. when a thread tries to acquire a lock, it first waits until it is next in line to do so. similarly, atomic accesses which were included in the reco...
Redis Tips
hub.com/andymccurdy/redis-py#api-reference select statement not implemented del is 'delete' in python zadd argument order is wrong setex argument order is wrong the default redis port is 6379. in node, create client with explicit host and port like so: > var r = require('redis').createclient(6379, '127.0.0.1') commands are asynchronous. in standard node fashion, first return value is
error or null; second return value is result of redis command. > r.set('foo', 42, console.log) null 'ok' > r.get('foo', console.log) null '42' for the rest of this, i'm going to use the synchronous redis-cli for demonstrations. lines beginning with redis> are input to the redis-cli. things are strings, mostly as you can see from that last example, the values pointed to by keys are strings or th...
...chronous redis-cli for demonstrations. lines beginning with redis> are input to the redis-cli. things are strings, mostly as you can see from that last example, the values pointed to by keys are strings or they are nil. nil values will be given as null in node, not undefined. but some commands only work with numbers (like incr); for these, if your key can't be parsed as a number, it's an
error: redis> set foo pie ok redis> incr foo (
error) err value is not an integer or out of range atomic counters i guess that sounds like geiger counters. i mean counters you can update atomically. get key set key value exists key setnx key value incr key incrby key int incrbyfloat key float getset key value get and set are fairly obvious. setnx sets a value on a key only if there ...
... */ if(err) throw err; /** * if results === null, it means that a concurrent client * changed the key while we were processing it and thus * the execution of the multi command was not performed. * * notice: failing an execution of multi is not considered * an
error. so you will have err === null and results === null */ }); }); }); nice. you just have to be careful that you check the result type of an exec() when you're watching variables. it could be either a list or null. note also that it's not an
error for a transaction to be aborted, so err will be null in either case. do notice however that watch will only work fo...
Mozilla internal string guide
tion. .truncate(length) - shortens the string to the given length. complete documentation can be found in the appendix. read-only strings the const attribute on a string determines if the string is writable. if a string is defined as a const nsastring then the data in the string cannot be manipulated. if one tries to call a non-const method on a const string the compiler will flag this as an
error at build time. for example: void nsfoo::reversecharacters(nsastring& str) { ... str.assign(reversedstr); // modifies the string } this should not compile, because you're assigning to a const class: void nsfoo::reversecharacters(const nsastring& str) { ... str.assign(reversedstr); } as function parameters for methods which are exposed across modules, use nsastring ref...
...shed using it. fortunately, the getter_copies() function makes this very easy. a method may look like this: void getvalue(char16_t** avalue) { *avalue = tonewunicode(foo); } without getter_copies(), the caller would need to free the string: { char16_t* val; getvalue(&val); if (somecondition) { // don't forget to free the value! ns_free(val); return ns_
error_failure; } ... // and later, still don't forget to free! ns_free(val); } with getter_copies() you never have to worry about this. you can just use getter_copies() to wrap a string class argument, and the class will remember to free the buffer when it goes out of scope: { nsstring val; getvalue(getter_copies(val)); // val will free itself here if (somecondition...
... ... // and later, still don't forget to free! ns_free(val); } with getter_copies() you never have to worry about this. you can just use getter_copies() to wrap a string class argument, and the class will remember to free the buffer when it goes out of scope: { nsstring val; getvalue(getter_copies(val)); // val will free itself here if (somecondition) return ns_
error_failure; ... // and later, still nothing to free } the resulting code is much simpler, and easy to read. literal strings a literal string is a raw string value that is written in some c++ code. for example, in the statement printf("hello world\n"); the value "hello world\n" is a literal string. it is often necessary to insert literal string values when an nsastring or nsacstring is re...
Components.Exception
summary components.exception is a javascript constructor to create nsixpcexception 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 nsixpcexception. ...
...ese 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 nsixpcexception. ...
...alue will. see also nsixpcexception. ...
Components.utils
removed in gecko 31 returns an array created in specified compartment. createobjectin() creates a new object, created in the scope of the specified object's compartment. dispatch() dispatches a runnable to the current/main thread. if the parameter is passed, the runnable will be dispatch in the compartment of the parameter, which affects which
error reporter gets called. evalinsandbox() runs javascript code in a sandbox, usually used to run code with restricted privileges. evalinwindow() removed in gecko 34. evaluate javascript code in a less-privileged javascript context. exportfunction() export a javascript function from a more-privileged to a less-privileged scope, allowing it ...
...ing of the garbage collector and the cycle collector. this should only be used to write tests of the interaction of the gc and cc with weak maps. obsolete since gecko 45 the function was moved to threadsafechromeutils nukesandbox() recomputewrappers() to be called from js only. this is for gecko internal use only, and may disappear at any moment. report
error() reports a javascript
error object to the
error console. setwantxrays() to be called from js only. this is for gecko internal use only, and may disappear at any moment. scheduleprecisegc() schedules a garbage collection cycle for some time in the future at which no javascript code is running. this lets you specify a callback so you can be notified once the garbage col...
...erties property type description sandbox nsixpccomponents_utils_sandbox creates sandbox objects for use with evalinsandbox(). ion boolean read only. strict boolean strict mode is enabled. this reflects the value of the javascript environment's option by the same name. read only. strict_mode boolean read only. w
error boolean warnings should be treated as
errors. this reflects the value of the javascript environment's option by the same name. read only. ...
HOWTO
> print("doing async work"); gscriptdone = false; var gthreadmanager = cc["@mozilla.org/thread-manager;1"] .getservice(ci.nsithreadmanager); var mainthread = gthreadmanager.currentthread; while (!gscriptdone) mainthread.processnextevent(true); while (mainthread.haspendingevents()) mainthread.processnextevent(true); 2. in all callbacks where your script is finished, i.e. both success and
error callbacks, put: gscriptdone = true; if you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait). this is of course a massive, ugly hack prone to
error, but this is what the xpcshell test harness does. there should really be a better solution in xpcshell. using js modules and non-ui javascript chrome files problem you want to write...
...me 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... ...
... 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... ...
Language bindings
erties are classes indexed by cid.components.constructorcreates a javascript function which can be used to create or construct new instances of xpcom components.components.exceptioncomponents.exception is a javascript constructor to create nsixpcexception objects. ...
...stresultcomponents.managercomponents.manager is a convenience reflection of the global native component manager service. the scriptable methods on the nsicomponentmanager interface can be called directly on this object.components.resultscomponents.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at table of
errors), with the value of each corresponding to that constant's value.components.returncodecomponents.stackcomponents.stack is a read only property of type nsistackframe (idl definition) that represents a snapshot of the current javascript callstack. this can be used for various diagnostic purposes.components.utilscomponents.utils is a collection of various useful xpconnect features. its interface is ...
... for example, privileged code using an xray to a dom object sees only the original, native version of the dom object. any expando properties are not visible, and if any native properties have been redefined, this has no effect.components.utils.makeobjectpropsnormalensures that the specified object's methods are all in the object's scope, and aren't cross-component wrappers.components.utils.report
errorcomponents.utils.report
error 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.scheduleprecisegc...
nsresult
« xpcom api reference the nsresult data type is a strongly-typed enum used to represent a value returned by an xpcom function; these are typically
error or status codes. for a list of defined result values, see
error codes returned by mozilla apis. note: on compilers that do not support strongly-typed enums (that is, compilers that don't support this feature of c++11), it falls back to being an unsigned 32-bit integer, as in past versions of gecko. note: prior to gecko 19.0, nsresult was not strongly typed. as a result, it was possible for code to misuse it, such as returning an nsresult value from a function whose signature indicates it returns a boolean. because nsresult is strongly typed, code like the following will result in an
error at compile time: bool foo() { ... i...
... as in past versions of gecko. note: prior to gecko 19.0, nsresult was not strongly typed. ...
...: prior to gecko 19.0, nsresult was not strongly typed. ...
RefPtr
bug 756640 is on file to enforce this rule but hasn't yet been fixed. while refptr should not generally be used to hold a pointer to an xpcom interface, this is flexible. there are no technical problems with doing so, and in some cases it may be necessary (see bug 756640 comment 1). for example, we have template classes such as owningnullptr that can contain a refptr to an xp...
...for concrete classes: refptr<nsfoo> foo; // class that implements nsifoo; refptr<bar> bar; // some random class that i want ref-counted but has nothing to do with xpcom: // just implement addref() and release() and it will work with refptr it is important that nscomptr is not used to hold a pointer to a concrete class since this can cause compile time
errors or runtime
errors. bug 756640 is on file to enforce this rule but hasn't yet been fixed. while refptr should not generally be used to hold a pointer to an xpcom interface, this is flexible. there are no technical problems with doing so, and in some cases it may be necessary (see bug 756640 comment 1). for example, we have template classes such as owningnullptr that can contain a refptr to an xpcom interface. xx...
...rete class is assigned directly?). and it's not clear what happens when the compiler does accept this pattern. what goes wrong at runtime - uaf? memory leak? qi failure and null-deref crashes?. note: in the above example, "nscomptr<nsfoo>" might compile and work ok (it won't if your xpcom class multiply-inherits nsisupports). but this is considered bad form, and may soon be made a compile-time
error. don't do it! can i queryinterface a refptr to get a nscomptr from the object it points to? sure. instead of using "do_queryinterface()" (which is used for nscomptrs), use "do_queryobject()", which works with refptrs: // let's say nsfoo implements nsifoo and nsibar xpcom interfaces: refptr<nsfoo> foo = new nsfoo(); nscomptr<nsibar> bar(do_queryobject(foo)); moz_assert(bar, "yikes someone cha...
mozIStorageStatementCallback
the mozistoragestatementcallback interface represents a callback handler that the storage api calls with result,
error, and completion notifications while handling asynchronous database queries. storage/public/mozistoragestatementcallback.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview void handlecompletion(in unsigned short areason); void handle
error(in mozistorage
error a
error); void handleresult(in mozistorageresultset aresultset); constants constant value description reason_finished 0 the statement has finished executing normally. reason_canceled 1 the statement stopped executing bec...
...pletion(in unsigned short areason); void handle
error(in mozistorage
error a
error); void handleresult(in mozistorageresultset aresultset); constants constant value description reason_finished 0 the statement has finished executing normally. reason_canceled 1 the statement stopped executing because it was canceled. reason_
error 2 the statement stopped executing because an
error occurred. methods handlecompletion() called when a statement finishes executing. void handlecompletion( in unsigned short areason ); parameters areason the reason the statement stopped executing; see the list of possible values in the constants section. ...
...ped executing because it was canceled. reason_
error 2 the statement stopped executing because an
error occurred. methods handlecompletion() called when a statement finishes executing. void handlecompletion( in unsigned short areason ); parameters areason the reason the statement stopped executing; see the list of possible values in the constants section. handle
error() called when an
error occurs while executing a statement. this function may be called more than once with a different storagei
error each time for any given asynchronous statement, and handlecompletion will be called once the statement is complete. void handle
error( in mozistorage
error a
error ); parameters a
error a mozistorage
error object describing the
error that occurred. handle...
nsIArray
yelementat(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 ); parameters starti...
...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 position of elemen...
...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 ...
nsIBidiKeyboard
rd 9.0 / seamonkey 2.6) method overview boolean islangrtl(); void setlangfrombidilevel(in pruint8 alevel); attributes attribute type description havebidikeyboards boolean indicates whether or not the system has at least one keyboard for each direction (left-to-right and right-to-left) installed. read only. note: this throws ns_
error_not_implemented if the widget layer doesn't provide this information. currently, this is only implemented on windows. methods islangrtl() determines if the current keyboard language is right-to-left. (supported on: win32, mac, gtk2) note: prior to gecko 1.9 this method used a parameter 'out prbool aisrtl' to return the value. boolean islangrtl(); parameters none. return value true if ...
...is 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. ...
nsICachingChannel
l if the disk cache is not present. the value of this attribute is usually only settable during the processing of a channel's onstartrequest. the default value of this attribute depends on the particular implementation of nsicachingchannel. cachefile nsifile get the "file" where the cached data can be found. this is valid for as long as a reference to the cache token is held. this may return an
error if cacheasfile is false. read only. cacheforofflineuse boolean specifies whether or not the data should be placed in the offline cache, in addition to normal memory/disk caching. this may fail if the offline cache is not present. the value of this attribute should be set before opening the channel. cachekey nsisupports uniquely identifies the data in the cache for this channel. holding a re...
...n 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 cause validation of ...
...equest. unlike load_bypass_cache, it does not force an end-to-end load (that is, it does not affect proxy caches). load_bypass_local_cache_if_busy 1 << 29 this load flag causes the local cache to be skipped if the request would otherwise block waiting to access the cache. load_only_from_cache 1 << 30 this load flag inhibits fetching from the net if the data in the cache has been evicted. an
error of ns_
error_document_not_cached will be sent to the listener's onstoprequest in this case. this flag is set automatically when the application is offline. load_only_if_modified 1 << 31 this load flag controls what happens when a document would be loaded from the cache to satisfy a call to asyncopen. if this attribute is set to true, then the document will not be loaded from the cache. a stream...
nsIDNSService
e of the specified host will be queried. resolve_priority_medium (1 << 2) the query is given medium priority. if used with low, medium takes precedence. resolve_priority_low (1 << 3) the query is given lower priority. if used with medium, medium takes precedence. resolve_speculate (1 << 4) indicates request is speculative. speculative requests return
errors if prefetching is disabled by configuration. resolve_disable_ipv6 (1 << 5) if this flag is set, only ipv4 addresses will be returned by asyncresolve() and resolve(). methods asyncresolve() begins off an asynchronous host lookup. a specified nsidnslistener is invoked when the resolution process is completed. nsicancelable asyncresolve( in autf8string ahostname, in unsig...
... 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 would be unaffected by...
.../dns-service;1"] .createinstance(components.interfaces.nsidnsservice); let thread = components.classes["@mozilla.org/thread-manager;1"] .getservice(components.interfaces.nsithreadmanager).currentthread; let host = "www.mozilla.org"; let listener = { onlookupcomplete: function(request, record, status) { if (!components.issuccesscode(status)) { // handle
error here return; } let address = record.getnextaddrasstring(); console.log(host + " = " + address); } }; dnsservice.asyncresolve(host, 0, listener, thread); ...
nsIFocusManager
bool aneedsfocus); 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 acti...
...t 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 adocument, in nsicontent...
... 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. this will either be 0...
nsIIOService
(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() returns a protocol handl...
...for a given uri. nsichannel newchannelfromuri2( in nsiuri auri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in unsigned long asecurityflags, in unsigned long acontentpolicytype ); please note, if you provide both a loadingnode and a loadingprincipal, then loadingprincipal must be equal to loadingnode->nodeprincipal(). but less
error prone is to just supply a loadingnode. keep in mind that uris coming from a webpage should never use the systemprincipal as the loadingprincipal. parameters auri an nsiuri from which to make a channel. aloadingnode the loadingdocument of the channel. the element or document where the result of this request will be used. this is the document/element that will get access to the result of t...
...siuri newuri( in autf8string aspec, in string aorigincharset, in nsiuri abaseuri ); parameters aspec the spec for the desired uri. aorigincharset the charset for the uri. may be null. abaseuri the base uri for the spec. may be null. if aspec is an absolute url, this parameter is ignored. return value an nsiuri object corresponding to aspec and abaseuri. exceptions thrown ns_
error_malformed_uri if uri does not begin with a valid scheme (as defined by rfc 3986) followed by a colon. remarks note: the proper way to create a new nsiuri is with newuri() method defined above. do not create a new nsiuri with createinstance(). this was a frozen interface see bug 157131 for details. from gecko 2.0 interfaces are no longer frozen. see also rfc 3986 ...
nsINavHistoryObserver
note: this method was removed in gecko 21.0 as part of bug 826409. the specified page and all its visits are about to be deleted. note: the page does not necessarily have to have ever existed for this function to be called. delete notifications aren't quite 100% accurate. batch delete operations take place in two steps; the notifications come first, followed by a bulk delete. if an
error occurs in between these two steps (for example, an out of memory
error), then you may get a notification even though the page doesn't wind up getting deleted. note: see using onbeforedeleteuri() in gecko 1.9.1 for how to implement this in gecko 1.9.1 void onbeforedeleteuri( in nsiuri auri, in acstring aguid ); parameters auri the uri of the page about to be deleted. aguid ...
...() is called. void onbeginupdatebatch(); parameters none. onclearhistory() called just prior to all of history being cleared. void onclearhistory(); parameters none. ondeleteuri() the specified page and all its visits has been deleted. delete notifications are not quite 100% accurate. batch delete operations take place in two steps; the notifications come first, followed by a bulk delete. if an
error occurs in between these two steps (for example, an out of memory
error), then you may get a notification even though the page doesn't wind up getting deleted. note: the page does not necessarily have to have ever existed for this function to be called. notes the removepagesbyhost() and removepagesbytimeframe() functions call beginupdatebatch() and endupdatebatch() rather than onclearhistory() o...
...on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavhistoryobserver and nsinavhistoryobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { if (iid.equals(ci.nsinavhistoryobserver) || iid.equals(ci.nsinavhistoryobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_
error_no_interface; } see also nsinavhistoryresult ...
nsIOutputStream
acount the maximum number of bytes to write to the stream. return value this method returns the number of bytes written to the stream (may be less than acount). exceptions thrown ns_base_stream_would_block indicates that writing to the output stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. ns_
error_not_implemented indicates that the stream does not implement this method. typically, output streams that do not have an internal buffer will not implement this method since such an implementation would require an intermediate buffer unless afromstream supported nsiinputstream.readsegments(), but that is not guaranteed. native code only!writesegments low-level write method that has access to t...
...iate buffer unless afromstream supported nsiinputstream.readsegments(), but that is not guaranteed. native code only!writesegments low-level write method that has access to the stream's underlying buffer. the reader function may be called multiple times for segmented buffers. this method is expected to keep calling the reader until either there is nothing left to write or the reader returns an
error. this method should not call the reader with zero bytes to provide. note: a nsioutputstream is not required to implement this method. in some contexts, writesegments may be guaranteed to be implemented, but in general it is not. this method serves as an optimization. unsigned long writesegments( in nsreadsegmentfun areader, in voidptr aclosure, in unsigned long acount ); parameters a...
... acount the maximum number of bytes to write to the stream. return value this method returns the number of bytes written to the stream (may be less than acount). exceptions thrown ns_base_stream_would_block indicates that writing to the output stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. ns_
error_not_implemented indicates that the stream does not have an internal buffer that can be written to directly. example writesegments() example // copy data from a string to a stream static ns_method copysegment(nsiinputstream* astream, void* aclosure, char* atosegment, pruint32 afromoffset, ...
nsIPrintingPrompt
e. the service is automatically registered at start up. historically, platform toolkits with native dialogs have implemented them in the gfx layer usually they were displayed when a new devicecontextspec specific to that platform was created. windows: the gfx layer no longer supports default toolkit behavior for displaying the native print dialog. if an embedder implemented service returns any
error code (other than ns_
error_abort) printing will terminate. returning ns_ok assumes that the printsettings object was correctly filled in and if it does not have valid fields for printer name, and so on. it may also terminate. defaults for platform service: showprintdialog - displays a native dialog showpagesetup() - displays a xul dialog showprogress() - displays a xul dialog summary for ...
...t and registered for you. you can use it as an example. it is located at "mozilla/embedding/components/printingui/src/win". that service is capable of displaying a native print dialog and a xul progress dialog. to fly your own dialog you may: implement this service to display at least the print dialog and a print progress dialog or you may implement just one of the dialogs and pass back ns_
error_not_implemented for any of the others. for the print dialog: you may stub out this service by having all the methods return ns_
error_not_implemented. you can then fly you own dialog and then properly fill in the printsettings object before calling nsiwebbrowserprint's print method. if you stub out this service you must set "printsilent" to true, if you do not, printing will terminate and a...
...ot_implemented for any of the others. for the print dialog: you may stub out this service by having all the methods return ns_
error_not_implemented. you can then fly you own dialog and then properly fill in the printsettings object before calling nsiwebbrowserprint's print method. if you stub out this service you must set "printsilent" to true, if you do not, printing will terminate and an
error dialog will be displayed. mac: the gfx layer still supports default toolkit behavior for displaying the print dialog. if an embedder implemented service returns ns_
error_not_implemented for "showprintdialog" the toolkit will display the native print dialog. defaults for platform service: mac os x: showprintdialog - displays a native dialog showpagesetup() - displays a native dialog ...
nsISessionStore
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 possible. nsidomnode duplicatetab( in...
...igned 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 long getclosedtabcou...
...vious session if possible. this will not overwrite the current session. instead the previous session will be merged into the current session. current windows will be reused if they were windows that pinned tabs were previously restored into. new windows will be opened as needed. note: this will throw if there is no previous state to restore. check with canrestorelastsession first to avoid thrown
errors. void restorelastsession(); parameters none. setbrowserstate() sets the current browsing state. note: calling setbrowserstate immediately replaces the current session, restoring the state of the entire application to the state passed in the astate parameter. void setbrowserstate( in astring astate ); parameters astate a json string representing the session state to use. settabs...
nsIThread
t 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 thread itself, and n...
... 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. warning: calling...
...er 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 ...
nsITransportSecurityInfo
read only. securitystate unsigned long a flag detailing the security state of the connection. the possible values are defined in nsiwebprogresslistener. read only. ...
...read only. securitystate unsigned long a flag detailing the security state of the connection. the possible values are defined in nsiwebprogresslistener. read only. ...
...read only. securitystate unsigned long a flag detailing the security state of the connection. the possible values are defined in nsiwebprogresslistener. read only. ...
nsIWebContentHandlerRegistrar
f registerprotocolhandler void registerprotocolhandler( in domstring protocol, in domstring uri, in domstring title, in nsidomwindow contentwindow ); parameters protocol the protocol the site wishes to handle, specified as a string. uri the uri to the handler as a string. you must include "%s" to indicate where to insert the escaped uri of the document to be handled. otherwise ns_
error_dom_syntax_err will be thrown. this string must also be of either the http or https schemes. title the title of the handler presented to the user as a string. contentwindow the dom content window from which the method has been called. note: script must execute from same domain as uri or else it will throw permission
error. can bypass this by opening about:config and setting preference of g...
...must have a content window to pass to registerprotocolhandler as it prompts the user for permission'); } nsiwchr.registerprotocolhandler("mailto", registeruri, "outlook.com live mail", htmlcontentwindow); in this example the services.wm.getenumerator was used to find a window that had the same host name (contentwindow.locatio...
...); } nsiwchr.registerprotocolhandler("mailto", registeruri, "outlook.com live mail", htmlcontentwindow); in this example the services.wm.getenumerator was used to find a window that had the same host name (contentwindow.location.hostname) as the uri (uri.host) we are trying to add. if it does not find anything with host name of mail.live.com then it aborts. if the host names do not match, this
error will be thrown in the
error console. permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler'permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler' when calling method: [nsiwebcontenthandlerregistrar::registerprotocolhandler] if the host names do match then a confirmation like th...
nsIWebProgress
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 an nsiwebprogressli...
...hods 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 registered with a cal...
...ll 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. ...
nsIWifiListener
is implemented by clients interested in receiving notifications when the list of available wifi access points changes. ...
... by clients interested in receiving notifications when the list of available wifi access points changes. ...
... alen); void on
error(in long
error); methods onchange() called when the list of available access points changes. void onchange( [array, size_is(alen)] in nsiwifiaccesspoint accesspoints, in unsigned long alen ); parameters accesspoints an array of nsiwifiaccesspoint objects representing all currently-available wifi access points. alen the number of entries in the accesspoints array. on
error() called when an
error occurs while updating the wifi access point list. void on
error( in long
error ); parameters
error the nsresult value indicating the
error that occurred. see also monitoring wifi access points nsiwifimonitor nsiwifiaccesspoint ...
nsIXMLHttpRequest
ace, as seen below in example 2, we can get access to this. the most obvious benefit is that we can set nsirequest - constants in the xhr.channel.loadflags. for instance, as done in example 2, the flag of load_anonymous is added, this strips all user data (cookies, tokens, etc). using event handlers from native code (not sure if it's up-to-date) from native code, the way to set up onload and on
error handlers is a bit different. here is a comment from johnny stenback <jst@netscape.com>: the mozilla implementation of nsixmlhttprequest implements the interface nsidomeventtarget and that's how you're supported to add event listeners. try something like this: nscomptr<nsidomeventtarget> target(do_queryinterface(myxmlhttpreq)); target->addeventlistener(ns_literal_string("load"), mylistener, pr_fa...
...nsixmlhttprequest implements the interface nsidomeventtarget and that's how you're supported to add event listeners. try something like this: nscomptr<nsidomeventtarget> target(do_queryinterface(myxmlhttpreq)); target->addeventlistener(ns_literal_string("load"), mylistener, pr_false) where mylistener is your event listener object that implements the interface nsidomeventlistener. the 'onload', 'on
error', and 'onreadystatechange' attributes moved to nsijsxmlhttprequest, but if you're coding in c++ you should avoid using those. though actually, if you use addeventlistener from c++ weird things will happen too, since the result will depend on what js happens to be on the stack when you do it.... conclusion: do not use event listeners on xmlhttprequest from c++, unless you're aware of all the sec...
.../xmlextras/xmlhttprequest;1"].createinstance(ci.nsixmlhttprequest); let handler = ev => { evf(m => xhr.removeeventlistener(m, handler, !1)); switch (ev.type) { case 'load': if (xhr.status == 200) { cb(xhr.response); break; } default: services.prompt.alert(null, 'xhr
error', '
error fetching package: ' + xhr.statustext + ' [' + ev.type + ':' + xhr.status + ']'); break; } }; let evf = f => ['load', '
error', 'abort'].foreach(f); evf(m => xhr.addeventlistener(m, handler, false)); xhr.mozbackgroundrequest = true; xhr.open('get', url, true); xhr.channel.loadflags |= ci.nsirequest.load_anonymous | ci.nsirequest.load_bypass...
nsIXPConnect
. 2) the jsobject is in fact an nsixpconnectwrappednative and thus already has an underlying xpcom object. 3) the jsobject is of a jsclass which supports getting the nsisupports from the jsobject directly. this is used for idlc style objects (e.g., dom objects). it *might* be possible to queryinterface the resulting interface pointer to nsixpconnectwrappedjs. returns: success: ns_ok failure: ns_
error_xpc_bad_convert_js ns_
error_failure. void wrapjs( in jscontextptr ajscontext, in jsobjectptr ajsobj, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters ajscontext missing description ajsobj missing description aiid missing description result missing description exceptions thrown missing exception missing description wrapjsaggregatedtonative() ...
...missing description result missing description exceptions thrown missing exception missing description wrapjsaggregatedtonative() wrapjsaggregatedtonative() is just like wrapjs() except it is used in cases where the jsobject is also aggregated to some native xpcom object. at present xbl is the only system that might want to do this. xxx write more! returns: success: ns_ok failure: ns_
error_xpc_bad_convert_js ns_
error_failure. void wrapjsaggregatedtonative( in nsisupports aouter, in jscontextptr ajscontext, in jsobjectptr ajsobj, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aouter missing description ajscontext missing description ajsobj missing description aiid missing description result missing description exceptions thrown...
...m object for which we can call getscriptobject to get the jsobject it uses to represent itself into javascript. it *might* be possible to queryinterface the nsixpconnectjsobjectholder returned by the method into an nsixpconnectwrappednative or an nsixpconnectwrappedjs. this method will never wrap the jsobject involved in an xpcnativewrapper before returning. returns: success: ns_ok failure: ns_
error_xpc_bad_convert_native ns_
error_xpc_cant_get_jsobject_of_dom_object ns_
error_failure. nsixpconnectjsobjectholder wrapnative( in jscontextptr ajscontext, in jsobjectptr ascope, in nsisupports acomobj, in nsiidref aiid ); parameters ajscontext missing description ascope missing description acomobj missing description aiid missing description return value missing description ...
nsIZipReader
attributes attribute type description file nsifile the file that represents the zip with which this zip reader was initialized. read only. manifestentriescount pruint32 the number of entries in the manifest. read only. methods close() closes a zip reader. subsequent attempts to extract() files or read from its input stream will result in an
error. subsequent attempts to access a nsizipentry obtained from this zip reader will cause unspecified behavior. void close(); parameters none. example demonstrating this function: list contents of xpi and read file contents extract() extracts a zip entry into a local file specified by outfile. the entry must be stored in the zip in either uncompressed or deflate-compressed format for the ext...
... 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 (not yet implemented)...
...tstream(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
browser autocomplete nsiautocompletecontroller nsiautocompleteinput nsiautocompletesearch console nsiconsolelistener nsiconsolemessage nsiconsoleservice document nsidocshell dom device nsidomgeogeolocation nsidomgeoposition nsidomgeopositionaddress nsidomgeopositioncallback nsidomgeopositioncoords nsidomgeoposition
error nsidomgeoposition
errorcallback nsidomgeopositionoptions nsidomglobalpropertyinitializer element nsidomchromewindow nsidomclientrect nsidomelement nsidomhtmlaudioelement nsidomhtmlformelement nsidomhtmlmediaelement nsidomhtmlsourceelement nsidomhtmltimeranges nsidomjswindow nsidomnode nsidomnshtmldocument nsidomstorageitem nsi...
...cessibleimage nsiaccessibleprovider nsiaccessibleretrieval nsiaccessiblerole nsiaccessiblescrolltype nsiaccessibleselectable nsiaccessiblestates nsiaccessibletable nsiaccessibletext nsiaccessibletreecache nsiaccessiblevalue nsiaccessnode nsisyncmessagesender script nsiscriptableunescapehtml nsiscriptableunicodeconverter nsiscript
error nsiscript
error2 stylesheet nsistylesheetservice url nsiuri nsiurl util nsidomserializer nsidomxpathevaluator nsidomxpathexception nsidomxpathexpression nsidomxpathresult xslt nsixsltexception nsixsltprocessor download nsidownload nsidownloadmanager nsidownloadprogresslistener element internal ...
...okiepromptservice nsicookieservice nsicookiestorage nsisessionstore crypto nsicryptohash filter nsiparentalcontrolsservice nsipermission nsipermissionmanager nsisecuritycheckedcomponent ssl nsissl
errorlistener stream stream nsipipe nsitraceablechannel nsitransport nsitransporteventsink nsitransportsecurityinfo timer nsitimer nsitimercallback ui windows nsitaskbarprev...
Storage
la.dev.apps.platform on the news server news.mozilla.org. to report bugs, use bugzilla. the overall procedure for use is: get the storage service - mozistorageservice. open a connection to the database of your choice - mozistorageconnection. create statements to execute on the connection - mozistoragestatement. bind parameters to a statement as necessary. execute the statement. check for
errors. reset the statement. opening a connection javascript example of opening my_db_file_name.sqlite in the profile directory: components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/fileutils.jsm"); let file = fileutils.getfile("profd", ["my_db_file_name.sqlite"]); let dbconn = services.storage.opendatabase(file); // will also create the ...
...r mozistoragestatementcallback). after you create and bind a statement, your javascript should look something like this to execute a statement asynchronously: statement.executeasync({ handleresult: function(aresultset) { for (let row = aresultset.getnextrow(); row; row = aresultset.getnextrow()) { let value = row.getresultbyname("column_name"); } }, handle
error: function(a
error) { print("
error: " + a
error.message); }, handlecompletion: function(areason) { if (areason != components.interfaces.mozistoragestatementcallback.reason_finished) print("query canceled or aborted!"); } }); the call to executeasync takes an object that implements mozistoragestatementcallback. see its documentation for more details on each method. the callback...
... when it falls out of scope. if a transaction is already in progress, no transaction is obtained. if your function returns without calling commit on the helper object, the transaction will be rolled back. nsresult myclass::myfunction() { // mdbconn is a member variable of our mozistorageconnection. mozstoragetransaction transaction(mdbconn); // execute some statements. if we encounter an
error, the transaction will // be rolled back. return transaction.commit(); } collation (sorting) sqlite provides several collation methods (binary, nocase, and rtrim), but these are all very simple and have no support for various text encodings or the user's locale. gecko 1.9.2 added support for several new collation methods: locale case- and accent-insensitive collation. locale_case_s...
Xray vision
ut modifications made by content, the xray short-circuits the content completely. this also makes the semantics of xrays for dom objects clear: they are the same as the dom specification, since that is defined using the webidl, and the webidl also defines the c++ representation. xrays for javascript objects until recently, built-in javascript objects that are not part of the dom, such as date,
error, and object, did not get xray vision when accessed by more-privileged code. most of the time this is not a problem: the main concern xrays solve is with untrusted web content manipulating objects, and web content is usually working with dom objects. for example, if content code creates a new date object, it will usually be created as a property of a dom object, and then it will be filtered out b...
...it will usually be created as a property of a dom object, and then it will be filtered out by the dom xray: // content code // redefine date.getfullyear() date.prototype.getfullyear = function() {return 1000}; var date = new date(); // chrome code // contentwindow is an xray, and date is an expando on contentwindow // so date is filtered out gbrowser.contentwindow.date.getfullyear() // -> type
error: gbrowser.contentwindow.date is undefined the chrome code will only even see date if it waives xrays, and then, because waiving is transitive, it should expect to be vulnerable to redefinition: // chrome code components.utils.waivexrays(gbrowser.contentwindow).date.getfullyear(); // -> 1000 however, there are some situations in which privileged code will access javascript objects that are not...
...d // 6) accessing a value property of a value-property object is fine console.log("6) value property of a value-property object"); console.log(sandbox.me.address.street); // -> "main street" // 7) functions defined on the sandbox-defined object are not visible in the xray console.log("7) call a function defined on the object"); try { console.log(sandbox.me.fullname()); } catch (e) { console.
error(e); } // -> type
error: sandbox.me.fullname is not a function // now with waived xrays console.log("now with waived xrays"); console.log("1) property redefined in the prototype:"); console.log(components.utils.waivexrays(sandbox.me).tosource()); // -> "not what you expected?" console.log("2) property that shadows the prototype:"); console.log(components.utils.waivexrays(sandbox.me).constructor)...
Address book sync client design
localrecordid - local unique id, for mobile devices this // is assigned by the mobile device. // crc - crc of the record last time we synced. // flags - operation to apply to this record. add // if it's new, mod if it's been modified, // ret if it was already sent to the server // but an
error occured, etc. // // step 1: // when the user begins a sync, run through the local database and update the // sync mapping table. if the crc has changed, mark the entry modified, if // it's a new record, add an entry and mark it new, if a record was deleted, // mark the entry deleted, etc. // // sync approach - server handles all conflict resolution: // // step 2: // using the sync map...
...startauthoperation(); /** * notify the observer that the ab sync operation has been completed. * * this method is called regardless of whether the the operation was * successful. * * atransactionid - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the
error (if any). * acookie - hmmm...cooookies! */ void onstopauthoperation(in nsresult astatus, in wstring amsg, in string acookie); /** * notify the observer that the ab sync operation has begun. this method is * called only once, at the beginning of a sync transaction * */ void onstartoperation(in print32 atransactionid, in pruint32 amsgsiz...
...id, in wstring amsg); /** * notify the observer that the ab sync operation has been completed. * * this method is called regardless of whether the the operation was * successful. * * atransactionid - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the
error (if any). */ void onstopoperation(in print32 atransactionid, in nsresult astatus, in wstring amsg); }; ...
Declaring and Using Callbacks
ngs to crash. prerequiste understanding abi functiontype declaring callbacks a callback is declared by using ctypes.functiontype. the first argument is the calling convention, the second argument is the return type, and the third is an array of arguments the callback expects. the return type of the javascript callback must match the return type declared, otherwise js-ctypes will throw an
error saying "unexpected return type". examples example 1 this callback that returns bool and has two arguments. var myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myjscallback(cint, cptr) { return true; // as the return of the functiontype was ctypes.bool we must make our javascript callback return bool otherwise js-ctype...
...pected return type". examples example 1 this callback that returns bool and has two arguments. var myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myjscallback(cint, cptr) { return true; // as the return of the functiontype was ctypes.bool we must make our javascript callback return bool otherwise js-ctypes will throw
error saying unexpected type return } var myccallback = myfunctypedeclaration.ptr(myjscallback); example 2 this callback that returns void and no arguments. when void is the return type, the javascript callback must not return, or it should return undefined. var myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.void_t, []); function myjscallback() { return undefined; // a...
... void and no arguments. when void is the return type, the javascript callback must not return, or it should return undefined. var myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.void_t, []); function myjscallback() { return undefined; // as the return of the functiontype was ctypes.void_t we must return undefined or dont return at all otherwise js-ctypes will throw an
error saying unexpected type } var myccallback = myfunctypedeclaration.ptr(myjscallback); using callbacks since callbacks are function pointers in c, js-ctypes has special handling for function pointer types. consider the following code: function myjscallback(foo, bar) { .... }; var functype = ctypes.functiontype(...); var funcptrtype = functype.ptr; var regularfuncptr = funcptrtype(); var callbac...
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 type
error 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. ...
...ertype 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. ...
Mozilla
displaying places information using views views are one component of the places model-view-controller design. use them to display nsinavhistoryresult objects to the user. see querying places for information about obtaining and using nsinavhistoryresult objects, which this page assumes you are familiar with.
error codes returned by mozilla apis the following tables list
errors that can occur when calling various mozilla apis. each
error is listed by its name and an
error code in parentheses. an
error will typically be displayed on the
error console, but can be captured using a try-catch block in javascript. these constants can be accessed through components.results. for ...
... the following tables list
errors that can occur when calling various mozilla apis. each
error is listed by its name and an
error code in parentheses. an
error will typically be displayed on the
error console, but can be captured using a try-catch block in javascript. these constants can be accessed through components.results. for example, by using components.results.ns_
error_not_initialized firefox here you can learn about how to contribute to the firefox project and you will also find links to information about the construction of firefox add-ons, using the developer tools in firefox, and other topics. firefox operational information database: sqlite a large amount of opera...
... this article will guide you on how to investigate disconnect failures. an example of such a failure how to report a hung firefox is your firefox not responding? or are you regularly seeing the "firefox is running but is not responding..." dialog? this usually means that something in firefox is hung. this may be because of a code
error within firefox itself, such as a deadlock or infinite loop, or it may be caused by 3rd-party software such as a firefox extension, antivirus software, or even malware or a virus on your computer. http cache httpd.js ime handling guide this document explains how gecko handles ime. implementing do...
AudioNode.connect() - Web APIs
the destination 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. otherwise, a notsupported
error exception is thrown. this parameter is not allowed if the destination is an audioparam. return value if the destination is a node, connect() returns a reference to the destination audionode object, allowing you to chain multiple connect() calls. in some browsers, older implementations of this interface return undefined. if the destination is an audioparam, connect() returns undefined. except...
...own. this parameter is not allowed if the destination is an audioparam. return value if the destination is a node, connect() returns a reference to the destination audionode object, allowing you to chain multiple connect() calls. in some browsers, older implementations of this interface return undefined. if the destination is an audioparam, connect() returns undefined. ...
...nect() returns a reference to the destination audionode object, allowing you to chain multiple connect() calls. in some browsers, older implementations of this interface return undefined. if the destination is an audioparam, connect() returns undefined. exceptions indexsize
error the value specified as outputindex or inputindex doesn't correspond to an existing input or output. invalidaccess
error the destination node is not part of the same audio context as the source node. notsupported
error the specified connection would create a cycle (in which the audio loops back through the same nodes repeatedly) and there are no delaynodes in the cycle to prevent the resulting waveform from getting stuck constructing the same audio frame indefinitely. examples connecting to an audio input the...
BaseAudioContext.decodeAudioData() - Web APIs
nd filereader. the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise. this is the preferred method of creating an audio source for web audio api from an audio track. this method only works on complete file data, not fragments of audio file data. syntax older callback syntax: baseaudiocontext.decodeaudiodata(arraybuffer, successcallback,
errorcallback); newer promise-based syntax: promise<decodeddata> baseaudiocontext.decodeaudiodata(arraybuffer); parameters arraybuffer an arraybuffer containing the audio data to be decoded, usually grabbed from xmlhttprequest, windoworworkerglobalscope.fetch() or filereader. successcallback a callback function to be invoked when the decoding successfully finishes. the single argument to this ...
...prequest, windoworworkerglobalscope.fetch() or filereader. successcallback a callback function to be invoked when the decoding successfully finishes. the single argument to this callback is an audiobuffer representing the decodeddata (the decoded pcm audio data). usually you'll want to put the decoded data into an audiobuffersourcenode, from which it can be played and manipulated how you want.
errorcallback an optional
error callback, to be invoked if an
error occurs when the audio data is being decoded. return value void, or a promise object that fulfills with the decodeddata. example in this section we will first cover the older callback-based system and then the newer promise-based syntax. older callback syntax in this example, the getdata() function uses xhr to load an audio trac...
...ar request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { source.buffer = buffer; source.connect(audioctx.destination); source.loop = true; }, function(e){ console.log("
error with decoding audio data" + e.err); }); } request.send(); } // wire up buttons to stop and play audio play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); } stop.onclick = function() { source.stop(0); play.removeattribute('disabled'); } // dump script to pre element pre.innerhtml = myscript.innerhtml; new promise-based syntax c...
Bluetooth.requestDevice() - Web APIs
ice 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 type
error 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 []. notfound
error there is no bluetooth device that matches the specified options. security
error this operation is not permitted in this context due to security concerns. for ex...
... specifications specification status comment web bluetooththe definition of 'requestdevice()' in that specification. draft initial definition. ...
... specifications specification status comment web bluetooththe definition of 'requestdevice()' in that specification. draft initial definition. ...
ClipboardItem.getType() - Web APIs
examples in the following example, we're returning all items on the clipboard via the clipboard.read() method. ...
... examples in the following example, we're returning all items on the clipboard via the clipboard.read() method. ...
... argument and return the corresponding blob object. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.
error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification. working draft initial definition. ...
ClipboardItem - Web APIs
arditem() creates a new clipboarditem object, with the mime type as the key and blob as the value properties this interface provides the following properties. types read only returns an array of mime types available within the clipboarditem. methods this interface defines the following methods. gettype() returns a promise that resolves with a blob of the requested mime type, or an
error if the mime type is not found. examples writing to clipboard here we're writing a new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the new clipboarditem. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await da...
...n turn, the responses' blob() method, to create the new clipboarditem. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.
error(err.name, err.message); } } reading from the clipboard here we're returning all items on the clipboard via the clipboard.read() method. then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboardite...
... argument and return the corresponding blob object. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.
error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification. working draft initial definition. ...
DOMParser - Web APIs
ldocument application/xml xmldocument application/xhtml+xml xmldocument image/svg+xml xmldocument examples parsing xml once you have created a parser object, you can parse xml from a string using the parsefromstring() method: let parser = new domparser() let doc = parser.parsefromstring(stringcontainingxmlsource, "application/xml")
error handling note that if the parsing process fails, the domparser does not throw an exception, but instead returns an
error document: <parser
error xmlns="http://www.mozilla.org/newlayout/xml/parser
error.xml"> (
error description) <sourcetext>(a snippet of the source xml)</sourcetext> </parser
error> the parsing
errors are also reported to the
error console, with the document uri (see below) as...
... parsing svg or html the domparser can also be used to parse an svg document (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7) or an html document (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9). there are three different results possible, selected by the mime type given. ...
... html extension /* * domparser html extension * 2012-09-04 * * by eli grey, http://eligrey.com * public domain. * no warranty expressed or implied. use at your own risk. ...
Element.classList - Web APIs
e.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. ...
...plement the barebones domtokenlist livelyness polyfill if (typeof domtokenlist !== "function") (function(window){ var document = window.document, object = window.object, hasownprop = object.prototype.hasownproperty; var defineproperty = object.defineproperty, allowtokenlistconstruction = 0, skippropchange = 0; function domtokenlist(){ if (!allowtokenlistconstruction) throw type
error("illegal constructor"); // internally let it through } domtokenlist.prototype.tostring = domtokenlist.prototype.tolocalestring = function(){return this.value}; domtokenlist.prototype.add = function(){ a: for(var v=0, arglen=arguments.length,val="",ele=this[" ucl"],proto=ele[" uclp"]; v!==arglen; ++v) { val = arguments[v] + "", checkifvalidclasslistentry("add", val)...
...var i=clen-sub; i < oldlen; ++i) delete restokenlist[i]; //remove trailing indexs if(prop !== "classlist") return; skippropchange = 1, target.classlist = restokenlist, target.classname = strval; skippropchange = 0, restokenlist.length = tokens.length - sub; } } function polyfillclasslist(ele){ if (!ele || !("innerhtml" in ele)) throw type
error("illegal invocation"); ele.detachevent( "onpropertychange", whenpropchanges ); // prevent duplicate handler infinite loop allowtokenlistconstruction = 1; try{ function protoobj(){} protoobj.prototype = new domtokenlist(); } finally { allowtokenlistconstruction = 0 } var protoobjproto = protoobj.prototype, restokenlist = new protoobj(); a: for(var to...
Element - Web APIs
ement representing the <slot> the node is inserted in. event handlers element.onfullscreenchange an event handler for the fullscreenchange event, which is sent when the element enters or exits full-screen mode. this can be used to watch both for successful expected transitions, but also to watch for unexpected changes, such as when your app is running in the background. element.onfullscreen
error an event handler for the fullscreen
error event, which is sent when an
error occurs while attempting to change into full-screen mode. methods inherits methods from its parents node, and its own parent, eventtarget, and implements those of parentnode, childnode, nondocumenttypechildnode, and animatable. eventtarget.addeventlistener() registers an event handler to a specific event type on th...
...ener() or by assigning an event listener to the oneventname property of this interface. cancel fires on a <dialog> when the user instructs the browser that they wish to dismiss the current open dialog. for example, the browser might fire this event when the user presses the esc key or clicks a "close dialog" button which is part of the browser's ui. also available via the oncancel property.
error fired when a resource failed to load, or can't be used. for example, if a script has an execution
error or an image can't be found or is invalid. also available via the on
error property. scroll fired when the document view or an element has been scrolled. also available via the onscroll property. select fired when some text has been selected. also available via the onselect property. sho...
...the onblur property. focus fired when an element has gained focus. also available via the onfocus property focusin fired when an element is about to gain focus. focusout fired when an element is about to lose focus. fullscreen events fullscreenchange sent to an element when it transitions into or out of full-screen mode. also available via the onfullscreenchange property. fullscreen
error sent to an element if an
error occurs while attempting to switch it into or out of full-screen mode. also available via the onfullscreen
error property. keyboard events keydown fired when a key is pressed. also available via the onkeydown property. keypress fired when a key that produces a character value is pressed down. also available via the onkeypress property. keyup fired when...
FileException - Web APIs
in the file system api, a fileexception object represents
error conditions that you might encounter while accessing the file system using the synchronous api. it extends the fileexception interface described in file writer and adds several new
error codes. 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 on
error(e) { postmessage('
error:' + e.tostring()); } try { //
error is thrown if "log.txt" already exists. var fileentry = fs.root.getfile('log.txt', {create: true, exclu...
... 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 encoding_err 5 the url is malformed. make sure that the url is complete and valid. ...
... there's not enough remaining storage space or the storage quota was reached and the user declined to give more space to the database. security_err 2 access to the files were denied for one of the following reasons: the files might be unsafe for access within a web application. too many calls are being made on file resources. other unspecified security
error code or situations. type_mismatch_err 11 the user has attempted to look up a file or directory, but the entry found is of the wrong type. for example, the app is accessing a directoryentry when the user is requesting a fileentry. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, pl...
FileReader - Web APIs
pathname from a file system. 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 domexception 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. ...
...s been completed. filereader.result read only the file's contents. this property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation. event handlers filereader.onabort a handler for the abort event. this event is triggered each time the reading operation is aborted. filereader.on
error a handler for the
error event. this event is triggered each time the reading operation encounter an
error. filereader.onload a handler for the load event. this event is triggered each time the reading operation is successfully completed. filereader.onloadstart a handler for the loadstart event. this event is triggered each time the reading is starting. filereader.onloadend a handler for th...
...result attribute contains the contents of the file as a text string. an optional encoding name can be specified. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort fired when a read has been aborted, for example because the program called filereader.abort(). also available via the onabort property.
error fired when the read failed due to an
error. also available via the on
error property. load fired when a read has completed successfully. also available via the onload property. loadend fired when a read has completed, successfully or not. also available via the onloadend property. loadstart fired when a read has started. also available via the onloadstart property. progress fired peri...
FileSystemEntry.getMetadata() - Web APIs
} the filesystementry interface's method getmetadata() obtains a metadata object with information about the file system entry, such as its modification date and time and its size. syntax filesystementry.getmetadata(successcallback[,
errorcallback]); parameters successcallback a function which is called when the copy operation is succesfully completed. receives a single input parameter: a metadata object with information about the file.
errorcallback optional an optional callback which is executed if an
error occurs while looking up the metadata. ...
...stementry.getmetadata(successcallback[,
errorcallback]); parameters successcallback a function which is called when the copy operation is succesfully completed. receives a single input parameter: a metadata object with information about the file.
errorcallback optional an optional callback which is executed if an
error occurs while looking up the metadata. there's a single parameter: a file
error describing what went wrong. return value undefined.
errors file
error.not_found_err the filesystementry refers to an item which doesn't exist. file
error.security_err security restrictions prohibit obtaining the requested metadata. example this example checks the size of a log file in a temporary folder and, if it exceeds a megabyte, moves it into a different directory. workingdirecto...
... this example checks the size of a log file in a temporary folder and, if it exceeds a megabyte, moves it into a different directory. workingdirectory.getfile("tmp/log.txt", {}, function(fileentry) { fileentry.getmetadata(function(metadata) { if (metadata.size > 1048576) { workingdirectory.getdirectory("log", {}, function(direntry) { fileentry.moveto(direntry); }, handle
error); } }); }, handle
error); 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. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossa...
Geolocation.watchPosition() - Web APIs
the geolocation method watchposition() method is used to register a handler function that will be called automatically each time the position of the device changes. you can also, optionally, specify an
error handling callback function. syntax navigator.geolocation.watchposition(success[,
error[, options]]) parameters success a callback function that takes a geolocationposition object as an input parameter.
error optional an optional callback function that takes a geolocationposition
error object as an input parameter. options optional an optional positionoptions object that provides configuration options for the location watch. return value an integer id that identifies the registered handler. the id can be passed to the geolocation.clearwatch() to unregister the handler. examp...
... identifies the registered handler. the id can be passed to the geolocation.clearwatch() to unregister the handler. ...
...ndler. the id can be passed to the geolocation.clearwatch() to unregister the handler. examples var id, target, options; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulations, you reached the target'); navigator.geolocation.clearwatch(id); } } function
error(err) { console.warn('
error(' + err.code + '): ' + err.message); } target = { latitude : 0, longitude: 0 }; options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0 }; id = navigator.geolocation.watchposition(success,
error, options); specifications specification status comment geolocation apithe definition of 'watchposition()' in that specification. recommendation ...
Geolocation API - Web APIs
s a handler function that will be called automatically each time the position of the device changes, returning the updated location. in both cases, the method call takes up to three arguments: a mandatory success callback: if the location retrieval is successful, the callback executes with a geolocationposition object as its only parameter, providing access to the location data. an optional
error callback: if the location retrieval is unsuccessful, the callback executes with a geolocationposition
error object as its only parameter, providing access information on what went wrong. an optional positionoptions object, which provides options for retrieval of the position data. for further information on geolocation usage, read using the geolocation api. interfaces geolocation the main ...
...osition instance is returned by a successful call to one of the methods contained inside geolocation, inside a success callback, and contains a timestamp plus a geolocationcoordinates object instance. geolocationcoordinates represents the coordinates of a user's position; a geolocationcoordinates instance contains latitude, longitude, and other important related information. geolocationposition
error a geolocationposition
error is returned by an unsuccessful call to one of the methods contained inside geolocation, inside an
error callback, and contains an
error code and message. navigator.geolocation the entry point into the api. returns a geolocation object instance, from which all other functionality can be accessed. dictionaries positionoptions represents an object containing optio...
...link'); maplink.href = ''; maplink.textcontent = ''; function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; status.textcontent = ''; maplink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`; maplink.textcontent = `latitude: ${latitude} °, longitude: ${longitude} °`; } function
error() { status.textcontent = 'unable to retrieve your location'; } if(!navigator.geolocation) { status.textcontent = 'geolocation is not supported by your browser'; } else { status.textcontent = 'locating…'; navigator.geolocation.getcurrentposition(success,
error); } } document.queryselector('#find-me').addeventlistener('click', geofindme); result specifications ...
GlobalEventHandlers - Web APIs
t event is sent, indicating that a css animation has started playing. globaleventhandlers.onauxclick an eventhandler called when an auxclick event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button). globaleventhandlers.onblur is an eventhandler representing the code to be called when the blur event is raised. globaleventhandlers.on
error is an on
erroreventhandler representing the code to be called when the
error event is raised. globaleventhandlers.onfocus is an eventhandler representing the code to be called when the focus event is raised. globaleventhandlers.oncancel is an eventhandler representing the code to be called when the cancel event is raised. globaleventhandlers.oncanplay is an eventhandler representing the cod...
... is an eventhandler representing the code to be called when the pointerenter event is raised. globaleventhandlers.onpointerleave is an eventhandler representing the code to be called when the pointerleave event is raised. globaleventhandlers.onpointerlockchange is an eventhandler representing the code to be called when the pointerlockchange event is raised. globaleventhandlers.onpointerlock
error is an eventhandler representing the code to be called when the pointerlock
error event is raised. globaleventhandlers.onprogress is an eventhandler representing the code to be called when the progress event is raised. globaleventhandlers.onratechange is an eventhandler representing the code to be called when the ratechange event is raised. globaleventhandlers.onreset is an eventhandler re...
...his interface defines no methods. specifications specification status comment selection apithe definition of 'extension to globaleventhandlers' in that specification. working draft adds onselectionchange. pointer lockthe definition of 'extension of document' in that specification. candidate recommendation adds onpointerlockchange and onpointerlock
error on document. it is experimentally implemented on globaleventhandlers. html living standardthe definition of 'globaleventhandlers' in that specification. living standard no change since the latest snapshot, html 5.1. html 5.1the definition of 'globaleventhandlers' in that specification. recommendation snapshot of html living standard. added onsort since the html5 snap...
HTMLBodyElement - Web APIs
sed. windoweventhandlers.onhashchange is an eventhandler representing the code to be called when the hashchange event is raised. windoweventhandlers.onlanguagechange is an eventhandler representing the code to be called when the languagechange event is raised. windoweventhandlers.onmessage is an eventhandler called whenever an object receives a message event. windoweventhandlers.onmessage
error is an eventhandler called whenever an object receives a message
error event. windoweventhandlers.onoffline is an eventhandler representing the code to be called when the offline event is raised. windoweventhandlers.ononline is an eventhandler representing the code to be called when the online event is raised. windoweventhandlers.onpagehide is an eventhandler representing the code to be call...
...not handled. windoweventhandlers.onunload is an eventhandler representing the code to be called when the unload event is raised. specifications specification status comment html living standardthe definition of 'htmlbodyelement' in that specification. living standard technically, the event-related properties onafterprint, onbeforeprint, onbeforeunload, onblur, on
error, onfocus, onhashchange, onlanguagechange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload, have been moved to windoweventhandlers. htmlbodyelement implements this interface. html 5.1the definition of 'htmlbodyelement' in that specification. recommendation html5the definition of 'htmlbodyelement' in that specification. recommendatio...
...s interface. html 5.1the definition of 'htmlbodyelement' in that specification. recommendation html5the definition of 'htmlbodyelement' in that specification. recommendation the following properties are now obsolete: alink, bgcolor, background, link, text, and vlink. the following properties have been added: onafterprint, onbeforeprint, onbeforeunload, onblur, on
error, onfocus, onhashchange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload. document object model (dom) level 2 html specificationthe definition of 'htmlbodyelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 specificationthe definition of 'htmlbody...
HTMLMediaElement - Web APIs
ion floating-point value indicating the total duration of the media in seconds. if no media data is available, the returned value is nan. if the media is of indefinite length (such as streamed live media, a webrtc call's media, or similar), the value is +infinity. htmlmediaelement.ended read only returns a boolean that indicates whether the media element has finished playing. htmlmediaelement.
error read only returns a media
error object for the most recent
error, or null if there has not been an
error. htmlmediaelement.loop a boolean that reflects the loop html attribute, which indicates whether the media element should start over when it reaches the end. htmlmediaelement.mediagroup a domstring that reflects the mediagroup html attribute, which indicates the name of the group of elemen...
...ents share downloaded data, so data downloaded by either element is available to both. events inherits methods from its parent, htmlelement , defined in the globaleventhandlers mixin. listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort fired when the resource was not fully loaded, but not as the result of an
error. canplay fired when the user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content canplaythrough fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content. dur...
...g of content. durationchange fired when the duration attribute has been updated. emptied fired when the media has become empty; for example, when the media has already been loaded (or partially loaded), and the htmlmediaelement.load() method is called to reload it. ended fired when playback stops when end of the media (<audio> or <video>) is reached or because no further data is available.
error fired when the resource could not be loaded due to an
error. loadeddata fired when the first frame of the media has finished loading. loadedmetadata fired when the metadata has been loaded loadstart fired when the browser has started to load a resource. pause fired when a request to pause play is handled and the activity has entered its paused state, most commonly occurring when the medi...
IDBDatabase.onabort - Web APIs
the onabort event handler of the idbdatabase interface handles the abort event, fired when a transaction is aborted and bubbles up to the connection object. note: this feature is available in web workers. syntax idbdatabase.onabort = function(event) { ... ...
... the connection object. note: this feature is available in web workers. syntax idbdatabase.onabort = function(event) { ... }; example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes on
error and onabort functions to handle non-success cases. ...
...vailable in web workers. syntax idbdatabase.onabort = function(event) { ... }; example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes on
error and onabort functions to handle non-success cases. ...
IDBDatabase.onversionchange - Web APIs
ase) was requested elsewhere (most probably in another window/tab on the same computer). this is different from the versionchange transaction (but it is related). note: this feature is available in web workers. syntax idbdatabase.onversionchange = function(event) { ... ...
...ase.onversionchange = function(event) { ... } example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes on
error and onabort functions to handle non-success cases, and an onversionchange function to notify when a database structure change has occurred. ...
...e this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes on
error and onabort functions to handle non-success cases, and an onversionchange function to notify when a database structure change has occurred. ...
IDBDatabase.transaction() - Web APIs
transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. details optional dictionary of other settings, supported only by chrome: return value an idbtransaction object. exceptions this method may raise a domexception of one of the following types: exception description invalidstate
error the close() method has previously been called on this idbdatabase instance. notfound
error an object store specified in in the storenames parameter has been deleted or removed. type
error the value for the mode parameter is invalid. invalidaccess
error the function was called with an empty list of store names. example in this example we o...
...duplicate items not allowed.</li>'; }; // you would then go on to do something to this database // via an object store var objectstore = transaction.objectstore("todolist"); // etc. specification specification status comment indexed database api 2.0the definition of 'transaction()' in that...
...n a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // you would then go on to do something to this database // via an object store var objectstore = transaction.objectstore("todolist"); // etc. specification specification status comment indexed database api 2.0the definition of 'transaction()' in that specification. recommendation indexed database api draftthe defi...
IDBDatabaseException - Web APIs
obsolete: this interface was removed from the specification and was replaced by usage of domexception. in the indexeddb api, an idbdatabaseexception object represents exception conditions that can be encountered while performing database operations. attributes attribute type description code unsigned short the most appropriate
error code for the condition. message domstring
error message describing the exception raised. 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. ...
... 4 a mutation operation in the transaction failed because a constraint was not satisfied. for example, an object, such as an object store or index, already exists and a request attempted to create a new one. data_err 5 data provided to an operation does not meet requirements. non_transient_err 2 an operation was not allowed on an object. unless the cause of the
error is corrected, retrying the same operation would result in failure. not_allowed_err 6 an operation was called on an object where it is not allowed or at a time when it is not allowed. it also occurs if a request is made on a source object that has been deleted or removed. more specific variants of this
error includes: transaction_inactive_err and read_only_err. ...
...a read_only transaction. timeout_err 10 a lock for the transaction could not be obtained in a reasonable time. transaction_inactive_err 7 a request was made against a transaction that is either not currently active or is already finished. unknown_err 1 the operation failed for reasons unrelated to the database itself, and it is not covered by any other
error code--for example, a failure due to disk io
errors. ver_err 12 a request to open a database with a version lower than the one it already has. this can only happen with idbopendbrequest. 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-...
IDBObjectStore.name - Web APIs
operty 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. invalidstate
error 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". transactioninactive
error the current transaction is not active. constraint
error an object store is already using the specified name. example in the following code snippet, we open a read/write...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.name); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorer...
.../write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.name); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request ...
IDBOpenDBRequest: blocked event - Web APIs
versionchange transaction on the same database. ...
...same database. ...
...n const req2 = indexeddb.open('todolist', 5); // in this case the onblocked handler will be executed req2.addeventlistener('blocked', () => { console.log('request was blocked'); }); }; using the onblocked property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; db.on
error = () => { console.log('
error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createinde...
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 abort
error. note: this feature is available in web workers. syntax transaction.abort(); exceptions this method may raise a domexception of the following type: exception description invalidstate
error 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 suc...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // repor...
...db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored su...
IDBTransaction: complete event - Web APIs
e handler is executed when a transaction successfully completed. ...
...saction successfully completed. ...
...saction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequest = objectstore.add(newitem); }; using the oncomplete property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.on
error = () => { console.log('
error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createinde...
IDBTransaction.objectStore() - Web APIs
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 domexception of one of the following types: exception description notfound
error the requested object store is not in this transaction's scope. invalidstate
error 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/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handl...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // repor...
... db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored su...
IDBVersionChangeEvent.newVersion - Web APIs
the newversion read-only property of the idbversionchangeevent interface returns the new version number of the database. note: this feature is available in web workers. syntax var newversion = idbversionchangeevent.newversion value a 64-bit integer. example in the following code snippet, we make a request to open a database, and include handlers for the success and
error cases. these events are fired via the custom idbversionchangeevent interface. for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of // implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use ...
... // this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification ...
... // this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0...
IDBVersionChangeEvent - Web APIs
roperty is still implemented in older browsers, the latest specification replaces it with the oldversion and newversion attributes. see the compatibility table to know what browsers support them. methods no specific method, but inherits properties from its parent, method. example in the following code snippet, we make a request to open a database, and include handlers for the success and
error cases. upon a version change (after an upgradedneeded event), the success event will implement the idbversionchangeevent interface. for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of implementations you want to test. window.indexeddb = window.indexeddb || window.mo...
...this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification statu...
...this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the d...
ImageCapture - Web APIs
an be called. finally, it shows how to apply the results of these calls to a canvas object. ...
..., it shows how to apply the results of these calls to a canvas object. ...
...cument.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(
error => console.log(
error)); } function ongrabframebuttonclick() { imagecapture.grabframe() .then(imagebitmap => { const canvas = document.queryselector('#grabframecanvas'); drawcanvas(canvas, imagebitmap); }) .catch(
error => console.log(
error)); } function ontakephotobuttonclick() { imagecapture.takephoto() .then(blob => createimagebitmap(blob)) .then(imagebitmap => { const canvas = document.queryselector('#takephotocanvas'); drawcanvas(canvas, imagebitmap); }) .catch(
error => console.log(
error)); } /* utils */ function drawcanvas(canvas, img) { canvas.width = getcomputedstyle(canvas).width.
msExtendedCode - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. in the event of an
error, the media element's
error event will be fired. ...
... non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. in the event of an
error, the media element's
error event will be fired. ...
... a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. in the event of an
error, the media element's
error event will be fired. the element's
error property will then contain an msextendedcode read-only property with platform-specific
error code information. msextendedcode is a read-only proprietary property specific to internet explorer and microsoft edge. value type: long; the platform specific
error code. example var video1 = object.getelementbyid("video1"); video1.addeventlistener('
error', function () { var
error = video1.
error.msextendedcode; //... }, false); video.addeventlistener('canplay', function () { video1.p...
MediaRecorder.requestData() - Web APIs
questdata() method (part of the mediarecorder api) is used to raise a dataavailable event containing a blob object of the captured media as it was when the method was called. this can then be grabbed and manipulated as you wish. ...
... example ... ...
... example ... ...
MediaRecorder - Web APIs
able called to handle the dataavailable event, which is periodically triggered each time timeslice milliseconds of media have been recorded (or when the entire media has been recorded, if timeslice wasn't specified). the event, of type blobevent, contains the recorded media in its data property. you can then collect and act upon that recorded media data using this event handler. mediarecorder.on
error 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 mediarecorder
errorevent interface, whose
error property contains a domexception that describes the actual
error that occurred. mediarecorder.onpause an eventhandler called to handle the pause event, which oc...
...e start event, which occurs when media recording starts. mediarecorder.onstop an eventhandler called to handle the stop event, which occurs when media recording ends, either when the mediastream ends — or after the mediarecorder.stop() method is called. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
error fired when an
error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. also available via the on
error property. example if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var mediarecor...
...some lines have been omitted for brevity; refer to the source for the complete code. specifications specification status comment mediastream recording working draft initial definition ...
MediaSettingsRange - Web APIs
working draft initial definition. ...
... working draft initial definition. ...
... working draft initial definition. ...
Recording a media element - Web APIs
we always record no more than the specified nu...
... event handler simply pushes the blob onto the data array. lines 6-7 starts the recording process by calling recorder.start(), and outputs a message to the log with the updated state of the recorder and the number of seconds it will be recording. lines 9-12 creates a new promise, named stopped, which is resolved when the mediarecorder's onstop event handler is called, and is rejected if its on
error event handler is called. the rejection handler receives as input the name of the
error that occurred. lines 14-16 creates a new promise, named recorded, which is resolved when the specified number of milliseconds have elapsed. upon resolution, it stops the mediarecorder if it's recording. lines 18-22 these lines create a new promise which is fulfilled when both of the two promises (stopped an...
...le. so by setting the download link's download attribute to "recordedvideo.webm", we tell the browser that clicking the button should download a file named "recordedvideo.webm" whose contents are the recorded video. lines 17-18 the size and type of the recorded media are output to the log area below the two videos and the download button. line 20 the catch() for all the promises outputs the
error to the logging area by calling our log() function. handling the stop button the last bit of code adds a handler for the click event on the stop button using addeventlistener(): stopbutton.addeventlistener("click", function() { stop(preview.srcobject); }, false); this simply calls the stop() function we covered earlier. result when put all together with the rest of the html and the css n...
Using the MediaStream Recording API - Web APIs
next, we call getusermedia() and inside it define: the constraints: only audio is ...
...next, we call getusermedia() and inside it define: the constraints: only audio is to be captured for our dictaphone. the success callback: this code is run once the getuserme...
...onsole.log('getusermedia not supported on your browser!'); } the whole thing is wrapped in a test that checks whether getusermedia is supported before running anything else. next, we call getusermedia() and inside it define: the constraints: only audio is to be captured for our dictaphone. the success callback: this code is run once the getusermedia call has been completed successfully. the
error/failure callback: the code is run if the getusermedia call fails for whatever reason. note: all of the code below is placed inside the getusermedia success callback. capturing the media stream once getusermedia has created a media stream successfully, you create a new media recorder instance with the mediarecorder() constructor and pass it the stream directly. this is your entry point into ...
Payment Request API - Web APIs
ld also adjust the font size or color contrast of the payment sheet, making it more comfortable for the user to make a payment. credentials management: users can manage their credit cards and shipping addresses directly in the browser. a browser can also sync these "credentials" across devices, making it easy for users to jump from desktop to mobile and back again when buying things. consistent
error handling: the browser can check the validity of card numbers, and can tell the user if a card has expired (or is about to expire). the browser can automatically suggest which card to use based on past usage patterns or restrictions from the merchant (e.g, "we only accept visa or mastercard"), or allow the user to say which is their default/favorite card. to request a payment, a web page creates...
...instrument (e.g., switching from a credit card to debit card). paymentresponse an object returned after the user selects a payment method and approves a payment request. merchantvalidationevent represents the browser requiring the merchant (website) to validate themselves as allowed to use a particular payment handler (e.g., registered as allowed to use apple pay). dictionaries address
errors a dictionary containing strings providing descriptive explanations of any
errors in any paymentaddress entries which have
errors. payer
errors a dictionary containing strings providing descriptive explanations of any
errors in related to paymentresponse's email, phone, and name attributes. paymentdetailsupdate an object describing changes that need to be made to the payment details in the ev...
...ate information following the instantiation of the payment interface but before the user begins to interact with it. related dictionaries for the basic card specification basiccardchangedetails an object providing redacted address information that is provided as the methoddetails on the paymentmethodchange event sent to the paymentrequest when the user changes payment information. basiccard
errors an object providing any
error messages associated with the fields in the basiccardresponse object that are not valid. this is used as the value of the paymentmethod property on the paymentvalidation
errors object sent to the paymentrequest when an
error occurs. basiccardrequest defines an object structure for containing payment request details such as card type. basiccardresponse defines an ...
PhotoCapabilities - Web APIs
working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check...
... working draft initial definition. 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/br...
... working draft initial definition. 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-d...
Pointer Lock API - Web APIs
document.exitpointerlock = document.exitpointerlock || document.mozexitpointerlock; // attempt to unlock document.exitpointerlock(); pointerlockchange event when the pointer lock state changes—for example, when calling requestpointerlock(), exitpointerlock(), the user pressing the esc key, etc.—the pointerlockchange...
...'mozpointerlockchange', lockchangealert, false); } function lockchangealert() { if(document.pointerlockelement === canvas || document.mozpointerlockelement === canvas) { console.log('the pointer lock status is now locked'); // do something useful in response } else { console.log('the pointer lock status is now unlocked'); // do something useful in response } } pointerlock
error event when there is an
error caused by calling requestpointerlock() or exitpointerlock(), the pointerlock
error event is dispatched to the document. this is a simple event and contains no extra data. document.addeventlistener('pointerlock
error', lock
error, false); document.addeventlistener('mozpointerlock
error', lock
error, false); function lock
error(e) { alert("pointer lock failed"); } note:...
...ions: function canvasdraw() { ctx.fillstyle = "black"; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = "#f00"; ctx.beginpath(); ctx.arc(x, y, radius, 0, degtorad(360), true); ctx.fill(); } iframe limitations pointer lock can only lock one iframe at a time. if you lock one iframe, you cannot try to lock another iframe and transfer the target to it; pointer lock will
error out. to avoid this limitation, first unlock the locked iframe, and then lock the other. while iframes work by default, "sandboxed" iframes block pointer lock. the ability to avoid this limitation, in the form of the attribute/value combination <iframe sandbox="allow-pointer-lock">, is expected to appear in chrome soon. specifications specification status comment poi...
RTCDataChannel.send() - Web APIs
different browsers have different limitations on the size of the message you can send. ...
...dditional 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 invalidstate
error 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. network
error the specified data would need to be buffered, and there isn't room for it in the buffer. in this scenario, the underlying transport i...
...es 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. network
error the specified data would need to be buffered, and there isn't room for it in the buffer. in this scenario, the underlying transport is immediately closed. type
error the specified data is too large for the other peer to receive. since there are multiple techniques for breaking up large data into smaller pieces for transfer, it's possible to encounter scenarios in which the other peer does not support the same ones. for example, if one peer is a modern browser that supports using the eor (end of record) flag to indicate when a received message is the last pie...
RTCDataChannel - Web APIs
sing property is an eventhandler which specifies a function to be called by the browser when the closing event is received by the rtcdatachannel. this is a simple event which indicates that the data channel is being closed, that is, rtcdatachannel transitions to "closing" state. ...
...dler which specifies a function to be called by the browser when the closing event is received by the rtcdatachannel. this is a simple event which indicates that the data channel is being closed, that is, rtcdatachannel transitions to "closing" state. for example, after rtcdatachannel.close() was called but the underlying data transport might not have been closed yet.on
error the rtcdatachannel.on
error property is an eventhandler which specifies a function to be called when the
error event is received. when an
error occurs on the data channel, the function receives as input an
errorevent object describing the
error which occurred.onmessage the rtcdatachannel.onmessage property stores an eventhandler which specifies a function to be called when the message event is fired on the channel. this ev...
...he send() method of the rtcdatachannel interface sends data across the data channel to the remote peer. events bufferedamountlow sent to the channel's onbufferedamountlow event handler when the number of bytes of data in the outgoing data buffer falls below the value specified by bufferedamountlowthreshold. close sent to the onclose event handler when the underlying data transport closes.
error sent to the on
error event handler when an
error occurs on the data channel. message sent to the onmessage event handler when a message has been received from the remote peer. the message contents can be found in the event's data property. open sent to the onopen event handler when the data channel is first opened, or when an existing data channel's underlying connection re-opens. data form...
RTCPeerConnection.addIceCandidate() - Web APIs
esn't return a value. failurecallback a function to be called if attempting to add the ice candidate fails. receives as input a domexception 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. ...
...put a domexception 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 domexception object passed to the rejection handler. ...
... 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 domexception object passed to the rejection handler. type
error the specified candidate's sdpmid and sdpmlineindex are both null. invalidstate
error the rtcpeerconnection currently has no remote peer established (remotedescription is null). operation
error this can happen for a number of reasons: the value specified for sdpmid is non-null and doesn't match the media description id of any media description included within the remotedescription. the sp...
RTCPeerConnection.createAnswer() - Web APIs
couraged. you should update any existing code to 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. ...
...descriptioncallback which will be passed a single rtcsessiondescription object describing the newly-created answer. failurecallback an rtcpeerconnection
errorcallback which will be passed a single domexception object explaining why the request to create an answer failed. options optional an optional rtcofferoptions object providing options requested for the answer. exceptions notreadable
error the identity provider wasn't able to provide an identity assertion. operation
error generation of the sdp failed for some reason; this is a general failure catch-all exception. return value a promise whose fulfillment handler is called with an object conforming to the rtcsessiondescriptioninit dictionary which contains the sdp answer to be delivered to the other peer. example here is a seg...
...h sent the offer to connect. the contents of the object being passed to the sendtoserver() function, along with everything else in the promise fulfillment handler, depend entirely on your design pc.createanswer().then(function(answer) { return pc.setlocaldescription(answer); }) .then(function() { // send the answer to the remote peer through the signaling server. }) .catch(handlegetusermedia
error); this asks rtcpeerconnection to create and return a new answer. in our promise handler, the returned answer is set as the description of the local end of the connection by calling setlocaldescription(). once that succeeds, the answer is sent to the signaling server using whatever protocol you see fit. promise.catch() is used to trap and handle
errors. see handling the invitation in signalin...
RTCPeerConnection.createDataChannel() - Web APIs
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. ...
... 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 invalidstate
error the rtcpeerconnection is closed. type
error 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. syntax
error values were specified for both the maxpacketlifetime and maxretransmits options. you may only specify a non-null v...
...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. syntax
error values were specified for both the maxpacketlifetime and maxretransmits options. you may only specify a non-null value for one of these. resourceinuse an id was specified, but another rtcdatachannel is already using the same value. operation
error either the specified id is already in use or, if no id was specified, the webrtc layer was unable to automatically generate an id because all ids are in use. examples this example shows how to create a data channel and set up handlers for the open and message events to send and receive messages on it (for brievity, the example assumes onnegotiationneeded is set up). // offerer side var pc =...
RTCRtpSender.replaceTrack() - Web APIs
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: invalidmodification
error replacing the rtcrtpsender's current track with the new one would require negotiation. invalidstate
error the track on which this method was called is stopped rather than running. type
error the new track's kind doesn't match the original track. usage notes things that trigger negotiation not all track replacements require renegotiation. in fact, even changes that seem huge can be done wit...
... candidate recommendation ...
... candidate recommendation ...
RTCSessionDescription - Web APIs
candidate recommendation initial definition. ...
... candidate recommendation initial definition. ...
... candidate recommendation initial definition. ...
ReadableStream.pipeThrough() - Web APIs
d bytes written to it and uncompressed video frames read from it. options optional the options that should be used when piping to the writable stream. available options are: preventclose: if this is set to true, the source readablestream closing will no longer cause the destination writablestream to be closed. the method will return a fulfilled promise once this process completes, unless an
error is encountered while closing the destination in which case it will be rejected with that
error. preventabort: if this is set to true,
errors in the source readablestream will no longer abort the destination writablestream. the method will return a promise rejected with the source’s
error, or with any
error that occurs during aborting the destination. preventcancel: if this is set to true, e...
...lestream will no longer abort the destination writablestream. the method will return a promise rejected with the source’s
error, or with any
error that occurs during aborting the destination. preventcancel: if this is set to true,
errors in the destination writablestream will no longer cancel the source readablestream. in this case the method will return a promise rejected with the source’s
error, or with any
error that occurs during canceling the source. in addition, if the destination writable stream starts out closed or closing, the source readable 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 abortsigna...
... 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. ...
ServiceWorkerContainer.register() - Web APIs
example.com/index.html, as well as pages underneath it, like example.com/product/description.html. if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope. navigator.serviceworker.register('/sw.js').then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(
error) { console.log('service worker registration failed:',
error); }); } else { console.log('service workers are not supported.'); } the following code, if included in example.com/index.html, at the root of a site, would apply to exactly the same pages as the example above. remember the scope, when included, uses the page's location as its base. alternatively, if this code were included in a...
... with the javascript file residing at example.com/product/sw.js, then the service worker would only apply to resources under example.com/product. if ('serviceworker' in navigator) { // declaring scope manually navigator.serviceworker.register('/sw.js', {scope: './'}).then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(
error) { console.log('service worker registration failed:',
error); }); } else { console.log('service workers are not supported.'); } there is frequent confusion surrounding the meaning and use of scope. since a service worker can't have a scope broader than its own location, only use the scope option when you need a scope that is narrower than the default. the following code, if included in...
...the following code, if included in example.com/index.html, at the root of a site, would only apply to resources under example.com/product. if ('serviceworker' in navigator) { // declaring scope manually navigator.serviceworker.register('/sw.js', {scope: '/product/'}).then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(
error) { console.log('service worker registration failed:',
error); }); } else { console.log('service workers are not supported.'); } however, servers can remove this restriction by setting a service-worker-allowed header on the service worker script, and then you can specify a max scope for that service worker above the service worker's location. specifications specification sta...
Using readable streams - Web APIs
in the pump() function seen above we first invoke read(), which returns a promise containing a results object — this has the results of our read in it, in the form { done, value }: return reader.read().then(({ done, value }) => { the results can be one of three different types: if a chunk is available to read, the promise will be fulfil...
...n the form { done, value }: return reader.read().then(({ done, value }) => { the results can be one of three different types: if a chunk is available to read, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes
errored, the promise will be rejected with the relevant
error. next, we check whether done is true. if so, there are no more chunks to read (the value is undefined) so we return out of the function and close the custom stream with readablestreamdefaultcontroller.close(): if (done) { controller.close(); return; } note: close() is part of the new custom stream, not the original stream we are dis...
...ed when reading has finished. reading from custom streams in our simple stream pump example, we consume the custom readable stream by passing it into a response constructor call, after which we consume it as a blob(). .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.createobjecturl(blob)) .then(url => console.log(image.src = url)) .catch(err => console.
error(err)); but a custom stream is still a readablestream instance, meaning you can attach a reader to it. as an example, have a look at our simple random stream demo (see it live also), which creates a custom stream, enqueues some random strings into it, and then reads the data out of the stream again once the stop string generation button is pressed. note: in order to consume a stream using fetch...
SubtleCrypto.unwrapKey() - Web APIs
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. ...
... supported algorithms the unwrapkey() method supports the same algorithms as the wrapkey() method. ...
... supported algorithms the unwrapkey() method supports the same algorithms as the wrapkey() method. examples note: you can try the working examples on github. unwrapping a "raw" key in this example we unwrap an aes-gcm symmetric key. ...
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 specification...
...'utf-16be' "utf-16", "utf-16le" 'utf-16le' "x-user-defined" 'x-user-defined' "iso-2022-cn", "iso-2022-cn-ext" 'replacement' optionsoptional is a textdecoderoptions dictionary with the property: fatal a boolean flag indicating if the textdecoder.decode() method must throw a domexception with the "encoding
error" 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 encoding
error exception to be thrown. var textdecoder4 = new textdecoder("iso-2022-cn"); // throw a type
error exception. specifications specification status comment ...
URL() - Web APIs
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. ...
...ill 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 type
error 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://developer.mozilla.org/' new url('docs', b); ...
...org/docs' new url('/docs', a); // => 'https://developer.mozilla.org/docs' new url('/docs', "https://developer.mozilla.org/fr-fr/toto"); // => 'https://developer.mozilla.org/docs' new url('/docs', ''); // raises a type
error exception as '' is not a valid url new url('/docs'); // raises a type
error 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'...
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
ode, the enablehold() method below is called. it accepts as input a mediastream containing the audio to play while the call is on hold. async function enablehold(audiostream) { try { await audiotransceiver.sender.replacetrack(audiostream.getaudiotracks()[0]); audiotransceiver.receiver.track.enabled = false; audiotransceiver.direction = "sendonly"; } catch(err) { /* handle the
error */ } } the three lines of code within the try block perform the following steps: replace their outgoing audio track with a mediastreamtrack containing hold music. disable the incoming audio track. switch the audio transceiver into send-only mode. this triggers renegotiation of the rtcpeerconnection by sending it a negotiationneeded event, which your code responds to generating an sdp of...
... offer with the directionality set to "sendonly", we handle it using the holdrequested() method, which accepts as input an sdp offer string. async function holdrequested(offer) { try { await peerconnection.setremotedescription(offer); await audiotransceiver.sender.replacetrack(null); audiotransceiver.direction = "recvonly"; await sendanswer(); } catch(err) { /* handle the
error */ } } the steps taken here are: set the remote description to the specified offer by calling rtcpeerconnection.setremotedescription(). replace the audio transceiver's rtcrtpsender's track with null, meaning no track. this stops sending audio on the transceiver. set the audio transceiver's direction property to "recvonly", instructing the transceiver to only accept audio and not to send ...
...r. remote peer when the "sendrecv" offer is received by the remote peer, it calls its holdended() method: async function holdended(offer, micstream) { try { await peerconnection.setremotedescription(offer); await audiotransceiver.sender.replacetrack(micstream.getaudiotracks()[0]); audiotransceiver.direction = "sendrecv"; await sendanswer(); } catch(err) { /* handle the
error */ } } the steps taken inside the try block here are: the received offer is stored as the remote description by calling setremotedescription(). the audio transceiver's rtcrtpsender's replacetrack() method is used to set the outgoing audio track to the first track of the microphone's audio stream. the transceiver's direction is set to "sendrecv", indicating that it should resume both send...
A simple RTCDataChannel sample - Web APIs
t (for example, udp, udp with a relay, tcp, etc.) by calling rtcpeerconnection.addicecandidate(), and they go back and forth until agreement is reached. but here, we just accept the first offer on each side, since there's no actual networking involved. localconnection.onicecandidate = e => !e.candidate || remoteconnection.addicecandidate(e.candidate) .catch(handleaddcandidate
error); remoteconnection.onicecandidate = e => !e.candidate || localconnection.addicecandidate(e.candidate) .catch(handleaddcandidate
error); we configure each rtcpeerconnection to have an event handler for the icecandidate event. start the connection attempt the last thing we need to do in order to begin connecting our peers is to create a connection offer. localconnection.
... first, we call rtcpeerconnection.createoffer() method to create an sdp (session description protocol) blob describing the connection we want to make. this method accepts, optionally, an object with constraints to be met for the connection to meet your needs, such as whether the connection should support audio, video, or both. in...
...te's end of the connection (which, to the remote peer, is its local end. this stuff can be confusing, but you get used to it). again, this would normally be exchanged through a signalling server. finally, the local connection's remote description is set to refer to the remote peer by calling localconnection's rtcpeerconnection.setremotedescription(). the catch() calls a routine that handles any
errors that occur. note: once again, this process is not a real-world implementation; in normal usage, there's two chunks of code running on two machines, interacting and negotiating the connection. a side channel, commonly called a “signalling server,” is usually used to exchange the description (which is in application/sdp form) between the two peers. handling successful peer connection as ...
Window.open() - Web APIs
indowfeatures parameter is an empty string), then the new secondary window will render the default toolbars of the main window. tip: note that in some browsers, users can override the windowfeatures settings and enable (or prevent the disabling of) features position and size features windowfeatures parameter can specify the position and size of the new window. note on position and dimension
error correction position if only one of them is specified, the behavior is implementation-dependent, and web author should not rely on it. left or screenx specifies the distance the new window is placed from the left side of the work area for applications of the user's operating system to the leftmost border (resizing handle) of the browser window. the new window cannot be initially positioned...
...ed to open. however, for most other popup blockers, there 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 propertie...
...sions, etc. "javascript:" links will interfere with the process of indexing webpages by search engines. "javascript:" links interfere with assistive technologies (e.g. voice browsers) and several web-aware applications (e.g. pdas and mobile browsers). "javascript:" links also interfere with "mouse gestures" features implemented in browsers. protocol scheme "javascript:" will be reported as an
error by link validators and link checkers. further reading: top ten web-design mistakes of 2002, 6. javascript in links, jakob nielsen, december 2002 links & javascript living together in harmony, jeff howden, february 2002 comp.lang.javascript newsgroup discussion faq on "javascript:" links never use <a href="#" onclick="window.open(...);"> such pseudo-link also breaks accessibility of link...
Window: unhandledrejection event - Web APIs
the unhandledrejection event is sent to the global scope of a script when a javascript promise that has no rejection handler is rejected; typically, this is the window, but may also be a worker. this is useful for debugging and for providing fallback
error handling for unexpected situations. bubbles no cancelable yes interface promiserejectionevent event handler property onunhandledrejection usage notes allowing the unhandledrejection event to bubble will eventually result in an
error message being output to the console. you can prevent this by calling preventdefault() on the promiserejectionevent; see preventing default handling below for an example. examples here we have a few examples showing ways you can make use of the unhandledre...
... an example. examples here we have a few examples showing ways you can make use of the unhandledrejection event. the event includes two useful pieces of information: promise the actual promise which was rejected with no handler available to deal with the rejection. reason the reason that would have been passed into the rejection handler if one had existed. see catch() for details. basic
error logging this example simply logs information about the unhandled promise rejection to the console. window.addeventlistener("unhandledrejection", event => { console.warn(`unhandled promise rejection: ${event.reason}`); }); you can also use the onunhandledrejection event handler property to set up the event listener: window.onunhandledrejection = event => { console.warn(`unhandled promise ...
...ny other tasks you wish to perform—calls preventdefault() to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code. this works because unhandledrejection is cancelable. window.addeventlistener('unhandledrejection', function (event) { // ...your code here to handle the unhandled rejection... // prevent the default handling (such as outputting the //
error to the console) event.preventdefault(); }); specifications specification status comment html living standardthe definition of 'unhandledrejection' in that specification. living standard initial definition. ...
Window - Web APIs
ent handler property for change events on the window. globaleventhandlers.onclick called after the any mouse button is pressed & released globaleventhandlers.ondblclick called when a double click is made with any mouse button. globaleventhandlers.onclose called after the window is closed globaleventhandlers.oncontextmenu called when the right mouse button is pressed globaleventhandlers.on
error called when a resource fails to load or when an
error occurs at runtime. see
error event. globaleventhandlers.onfocus called after the window receives or regains focus. see focus events. windoweventhandlers.onhashchange an event handler property for hashchange events on the window; called when the part of the url after the hash mark ("#") changes. globaleventhandlers.oninput called when th...
...rage event globaleventhandlers.onsubmit called when a form is submitted windoweventhandlers.onunhandledrejection an event handler for unhandled promise rejection events. windoweventhandlers.onunload called when the user navigates away from the page. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
error fired when a resource failed to load, or can't be used. for example, if a script has an execution
error or an image can't be found or is invalid. also available via the on
error property. languagechange fired at the global scope object when the user's preferred language changes. also available via the onlanguagechange property. orientationchange fired when the orientation of the device has ...
...so available via the onappinstalled property. beforeinstallprompt fired when a user is about to be prompted to install a web application. also available via the onbeforeinstallprompt property. messaging events message fired when the window receives a message, for example from a call to window.postmessage() from another browsing context. also available via the onmessage property. message
error fired when a window object receives a message that can't be deserialized. also available via the onmessage
error property. print events afterprint fired after the associated document has started printing or the print preview has been closed. also available via the onafterprint property. beforeprint fired when the associated document is about to be printed or previewed for printing. als...
WindowOrWorkerGlobalScope.btoa() - Web APIs
ication 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 invalidcharacter
error 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 represented using the utf-16 cha...
... a sequence of 16-bit (2 byte) units. every ascii character fits into the first byte of one of these units, but many other characters don't. base64, by design, expects binary data as its input. in terms of javascript strings, this means strings in which each character occupies only one byte. ...
...you pass a string into btoa() containing characters that occupy more than one byte, you will get an
error, because this is not considered binary data: const ok = "a"; console.log(ok.codepointat(0).tostring(16)); // 61: occupies < 1 byte const notok = "✓" console.log(notok.codepointat(0).tostring(16)); // 2713: occupies > 1 byte console.log(btoa(ok)); // yq== console.log(btoa(notok)); //
error if you need to encode unicode text as ascii using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte. for example: // convert a unicode string to a string in which // each 16-bit unit occupies only one byte function tobinary(string) { const codeunits = new uint16array(string.length); for (let i = 0; i < codeunits.length; i++) { codeunits[i] = s...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
"undefined" after 1.5 seconds the myarray.mymethod function is passed to settimeout, then when it's called, its this is not set so it defaults to the window object. there's also no option to pass a thisarg to settimeout as there is in array methods like foreach, reduce, etc. and as shown below, using call to set this doesn't work either. ...
..." after 1.5 seconds the myarray.mymethod function is passed to settimeout, then when it's called, its this is not set so it defaults to the window object. there's also no option to pass a thisarg to settimeout as there is in array methods like foreach, reduce, etc. and as shown below, using call to set this doesn't work either. ...
...object. there's also no option to pass a thisarg to settimeout as there is in array methods like foreach, reduce, etc. and as shown below, using call to set this doesn't work either. ...
WritableStream.WritableStream() - Web APIs
r failure. this method will be called only after all queued-up writes have succeeded. the controller parameter passed to this method is a writablestreamdefaultcontroller, which can be used to control the stream at the end of writing. abort(reason) optional this method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an
errored state. it can clean up any held resources, much like close(), but abort() will be called even if writes are queued up — those chunks will be thrown away. if this process is asynchronous, it can return a promise to signal success or failure. the reason parameter contains a domstring describing why the stream was aborted. queuingstrategy optional an object that optionally defines a queuin...
...nst defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk
error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream
error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy ...
... backpressure because of how backpressure is supported in the api, its implementation in code may be less than obvious. to see how backpressure is implemented look for three things. the highwatermark property, which is set when creating the counting strate...
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 type
error 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() ...
...nst defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk
error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream
error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy ...
... specifications specification status comment streamsthe definition of 'getwriter()' in that specification. living standard initial definition. ...
WritableStream - Web APIs
built-in backpressure and queuing. constructor writablestream() creates a new writablestream object. properties writablestream.locked read only a boolean indicating whether the writablestream is locked to a writer. methods writablestream.abort() aborts 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. writablestream.close() closes the stream. writablestream.getwriter() 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. examples the following example illustrates several features of this interface. it shows the creatio...
...nst defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk
error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream
error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy ...
... backpressure because of how backpressure is supported in the api, its implementation in code may be less than obvious. to see how backpressure is implemented look for three things. the highwatermark property, which is set when creating the counting strate...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
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 type
error 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, which returns an ...
...nst defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk
error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream
error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy ...
... specifications specification status comment streamsthe definition of 'writablestreamdefaultwriter()' in that specification. living standard initial definition. ...
WritableStreamDefaultWriter.close() - Web APIs
the close() method of the writablestreamdefaultwriter interface closes the associated writable stream. the underlying sink will finish processing any previously-written chunks, before 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 type
error 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. i...
...nst defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk
error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream
error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy ...
... specifications specification status comment streamsthe definition of 'close()' in that specification. living standard initial definition. ...
WritableStreamDefaultWriter.write() - Web APIs
t indicate simply that the chunk has been accepted, 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 type
error 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 th...
...nst defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk
error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream
error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy ...
... specifications specification status comment streamsthe definition of 'write()' in that specification. living standard initial definition. ...
HTML in XMLHttpRequest - Web APIs
ot available in the synchronous mode. also, html support is only available if the responsetype property has been set to "document". this limitation avoids wasting time parsing html uselessly when legacy code uses xmlhttprequest in the default mode to retrieve responsetext for text/html resources. also, this limitation avoids problems with legacy code that assumes that responsexml is null for http
error pages (which often have a text/html response body). usage retrieving an html resource as a dom using xmlhttprequest works just like retrieving an xml resource as a dom using xmlhttprequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responsetype property of the xmlhttprequest object after calling open() but b...
...but before calling send(). var xhr = new xmlhttprequest(); xhr.onload = function() { console.log(this.responsexml.title); } xhr.open("get", "file.html"); xhr.responsetype = "document"; xhr.send(); feature detection method 1 this method relies on the "force async" nature of the feature. when you try to set responsetype of an xmlhttprequest object after it is opened as "sync". this throws an
error in the browsers that implement the feature and works on others. function htmlinxhr() { if (!window.xmlhttprequest) return false; var req = new window.xmlhttprequest(); req.open('get', window.location.href, false); try { req.responsetype = 'document'; } catch(e) { return true; } return false; } view on jsfiddle this method is synchronous, does not rely on external a...
... if (!window.xmlhttprequest) { window.settimeout(function() { callback(false); }, 0); return; } var done = false; var xhr = new window.xmlhttprequest(); xhr.onreadystatechange = function() { if (this.readystate == 4 && !done) { done = true; callback(!!(this.responsexml && this.responsexml.title && this.responsexml.title == "&&<")); } } xhr.onabort = xhr.on
error = function() { if (!done) { done = true; callback(false); } } try { xhr.open("get", "detect.html"); xhr.responsetype = "document"; xhr.send(); } catch (e) { window.settimeout(function() { if (!done) { done = true; callback(false); } }, 0); } } the argument callback is a function that will be called asynchronously with t...
XRSystem: requestSession() - Web APIs
ion. see specifying session options for details on how to configure a webxr session. return value a promise that resolves with an xrsession object if the device and user agent support the requested mode and features. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: invalidstate
error 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. notsupported
error there is no webxr-compatible device available, or the device does not support the specified sessionmode; this can also be thrown if any of the required options are unsupported. ...
...this can happen for a number of reasons, which are covered in more detail in permissions and security in webxr device api. ...
...on() requesting an "immersive-vr" session. if the promise resolves, it sets up a session and initiates the animation loop. navigator.xr.requestsession("immersive-vr") .then((xrsession) => { xrsession.addeventlistener('end', onxrsessionended); // do necessary session setup here. // begin the session’s animation loop. xrsession.requestanimationframe(onxranimationframe); }).catch(function(
error) { // "immersive-vr" sessions are not supported console.warn("'immersive-vr' isn't supported, or an
error occurred activating vr!"); }); verifying webxr support and using a button to start vr mode the following example shows how to use both issessionsupported() and requestsession(). first, it checks to see if webxr is available by verifying the existence of navigator.xr. next, it calls isse...
font-weight - CSS: Cascading Style Sheets
e any number between 1 and 1000. ...
...0. ...
.../> <label for="weight">weight</label> </header> <div class="container"> <p class="sample">...it would not be wonderful to meet a megalosaurus, forty feet long or so, waddling like an elephantine lizard up holborn hill.</p> </div> css /* mutator sans is created by lett
error (https://github.com/lett
error/mutatorsans) and is used here under the terms of its license: https://github.com/lett
error/mutatorsans/blob/master/license */ @font-face { src: url('https://mdn.mozillademos.org/files/16011/mutatorsans.ttf'); font-family:'mutatorsans'; font-style: normal; } label { font: 1rem monospace; white-space: nowrap; } .container { max-height: 150px; overflow-y: auto; } .sample { text-transform: uppercase; font: 1.5rem 'mutatorsans', sans-serif; } html, body { max-heig...
<input type="date"> - HTML: Hypertext Markup Language
entered value beyond its format. the interfaces generally don't let you enter anything that isn't a date — which is helpful — but you can leave the field empty or enter an invalid date in browsers where the input falls back to type text (like the 32nd of april). if you use min and max to restrict the available dates (see setting maximum and minimum dates), supporting browsers will display an
error if you try to submit a date that is out of bounds. however, you'll need to double-check the submitted results to ensure the value is within these dates, if the date picker isn't fully supported on the user's device. you can also use the required attribute to make filling in the date mandatory — an
error will be displayed if you try to submit an empty date field. this should work in most browse...
...a field required: <form> <label> choose your preferred party date (required, april 1st to 20th): <input type="date" name="party" min="2017-04-01" max="2017-04-20" required> <span class="validity"></span> </label> <p> <button>submit</button> </p> </form> if you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an
error. try playing with the example now: here's a screenshot for those of you who aren't using a supporting browser: here's the css used in the above example. we make use of the :valid and :invalid pseudo-elements to add an icon next to the input, based on whether or not the current value is valid. we had to put the icon on a <span> next to the input, not on the input itself, because in chrome at...
...te picker doesn't use it, the text input fallback will. for example, try viewing the following in a unsupporting browser: <form> <label for="bday">enter your birthday: <input type="date" name="bday" required pattern="\d{4}-\d{2}-\d{2}"> <span class="validity"></span> </label> <p> <button>submit</button> </p> </form> if you submit it, you'll see that the browser displays an
error and highlights the input as invalid if your entry doesn't match the pattern ####-##-## (where # is a digit from 0 to 9). of course, this doesn't stop people from entering invalid dates, or incorrect formats. so we still have a problem. span { position: relative; } span::after { right: -18px; position: absolute; } input:invalid + span::after { content: '✖'; } input:valid + span::aft...
<input type="datetime-local"> - HTML: Hypertext Markup Language
ything that isn't a date/time — which is helpful — but a user might still fill in no value and submit, or enter an invalid date and/or time (e.g. the 32nd of april). you can use min and max to restrict the available dates (see setting maximum and minimum dates), and you can use the required attribute to make filling in the date/time mandatory. as a result, supporting browsers will display an
error if you try to submit a date that is outside the set bounds, or an empty date field. let's look at an example; here we've set minimum and maximum date/time values, and also made the field required: <form> <div> <label for="party">choose your preferred party date and time (required, june 1st 8.30am to june 30th 4.30pm):</label> <input id="party" type="datetime-local" name="par...
...to june 30th 4.30pm):</label> <input id="party" type="datetime-local" name="partydate" min="2017-06-01t08:30" max="2017-06-30t16:30" required> <span class="validity"></span> </div> <div> <input type="submit" value="book party!"> </div> </form> if you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an
error. try playing with the example now: here's a screenshot for those of you who aren't using a supporting browser: here's the css used in the above example. here we make use of the :valid and :invalid css properties to style the input based on whether or not the current value is valid. we had to put the icons on a <span> next to the input, not on the input itself, because in chrome the generate...
...of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates and times. and what user is going to understand the pattern they need to enter the time and date in? we still have a problem. div { margin-bottom: 10px; } inpu...
<input type="email"> - HTML: Hypertext Markup Language
ver.com—to demonstrate what constitutes a valid entry. this string demonstrates both that an e-mail address should be entered, and suggests that it should be a corporate beststartupever.com account. this is in addition to the fact that using type email will validate the text to ensure that it's formatted like an e-mail address. if the text in the input box isn't an e-mail address, you'll get an
error message that looks something like this: if we left things at that, we would at least be validating on legitimate e-mail addresses. but we want to go one step farther: we want to make sure that the e-mail address is in fact in the form "username@beststartupever.com". this is where we'll use pattern. we set pattern to .+@beststartupever.com. this simple regular expression requests a string that ...
...ake sure this resembles a valid e-mail address, and if it is, make sure it's also a beststartupever.com address." it's advisable to use the title attribute along with pattern. if you do, the title must describe the pattern. that is, it should explain what format the data should take on, rather than any other information. that's because the title may be displayed or spoken as part of a validation
error message. for example, the browser might present the message "the entered text doesn't match the required pattern." followed by your specified title. if your title is something like "e-mail address", the result would be the message "the entered text doesn't match the required pattern. e-mail address", which isn't very good. that's why, instead, we specify the string "please provide only a best st...
...ed text doesn't match the required pattern." followed by your specified title. if your title is something like "e-mail address", the result would be the message "the entered text doesn't match the required pattern. e-mail address", which isn't very good. that's why, instead, we specify the string "please provide only a best startup ever corporate e-mail address" by doing that, the resulting full
error message might be something like "the entered text doesn't match the required pattern. please provide only a best startup ever corporate e-mail address." note: if you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful
error messages there to aid you in solving the problem. examples here we h...
<input type="month"> - HTML: Hypertext Markup Language
isn't a date — which is helpful — but you can still submit the form with the month input empty, or enter an invalid date (e.g. the 32nd of april). to help avoid this, you can use min and max to restrict the available dates (see setting maximum and minimum dates), and in addition use the required attribute to make filling in the date mandatory. as a result, supporting browsers will display an
error if you try to submit a date that is outside the set bounds, or an empty date field. let's look at an example; here we've set minimum and maximum dates, and also made the field required: <form> <div> <label for="month">what month would you like to visit us (summer months only, please)?</label> <input id="month" type="month" name="month" min="2017-06" max="2017-09" required> ...
... visit us (summer months only, please)?</label> <input id="month" type="month" name="month" min="2017-06" max="2017-09" required> <span class="validity"></span> </div> <div> <input type="submit" value="submit form"> </div> </form> if you try to submit the form without both the month and year specified (or with a date outside the set bounds), the browser displays an
error. try playing with the example now: here's a screenshot for those of you who aren't using a supporting browser: here's the css used in the above example. here we make use of the :valid and :invalid css properties to style the input based on whether or not the current value is valid. we had to put the icons on a <span> next to the input, not on the input itself, because in chrome the generate...
...of course, this doesn't stop people from entering invalid dates (such as 0000-42), or incorrectly formatted dates that follow the pattern. there's also the problem that the user won't necessarily know which of the many date formats is expected. we have work left to do. ...
<input type="time"> - HTML: Hypertext Markup Language
= 'time'; input.min = '23:00'; input.max = '01:00'; input.value = '23:59'; if (input.validity.valid && input.type === 'time') { // <input type=time> reversed range supported } else { // <input type=time> reversed range unsupported } making times required in addition, you can use the required attribute to make filling in the time mandatory. as a result, supporting browsers will display an
error if you try to submit a time that is outside the set bounds, or an empty time field. let's look at an example; here we've set minimum and maximum times, and also made the field required: <form> <div> <label for="appt-time">choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required> ...
...e an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required> <span class="validity"></span> </div> <div> <input type="submit" value="submit form"> </div> </form> if you try to submit the form with an incomplete time (or with a time outside the set bounds), the browser displays an
error. try playing with the example now: here's a screenshot for those of you who aren't using a browser that supports time inputs: important: html form validation is not a substitute for scripts that ensure that the entered data is in the proper format. it's far too easy for someone to make adjustments to the html that allow them to bypass the validation, or to remove it entirely. it's also pos...
...of course, this doesn't stop people from entering invalid times, or incorrectly formatted times that follow the pattern. then there's the problem of the user having no idea exactly what format the time is expected to be in. div { margin-bottom: 10px; position: relati...
<u>: The Unarticulated Annotation (Underline) element - HTML: Hypertext Markup Language
in html 4; however, <u> was restored in html 5 with a new, semantic, meaning: to mark text as having some form of non-textual annotation applied. be careful to avoid using the <u> element with its default styling (of underlined text) in such a way as to be confused with a hyperlink, which is also underlined by default. use cases valid use cases for the <u> element include annotating spelling
errors, applying a proper name mark to denote proper names in chinese text, and other forms of annotation. you should not use <u> to simply underline text for presentation purposes, or to denote titles of books. other elements to consider using in most cases, you should use an element other than <u>, such as: <em> to denote stress emphasis <b> to draw attention to text <mark> to mark key words ...
...es of books or other publications <i> to denote technical terms, transliterations, thoughts, or names of vessels in western texts to provide textual annotations (as opposed to the non-textual annotations created with <u>), use the <ruby> element. to apply an underlined appearance without any semantic meaning, use the text-decoration property's value underline. examples indicating a spelling
error this example uses the <u> element and some css to display a paragraph which includes a misspelled
error, with the
error indicated in the red wavy underline style which is fairly commonly used for this purpose. html <p>this paragraph includes a <u class="spelling">wrnogly</u> spelled word.</p> in the html, we see the use of <u> with a class, spelling, which is used to indicate the misspelling ...
...pelling">wrnogly</u> spelled word.</p> in the html, we see the use of <u> with a class, spelling, which is used to indicate the misspelling of the word "wrongly". css u.spelling { text-decoration: red wavy underline; } this css indicates that when the <u> element is styled with the class spelling, it should have a red wavy underline underneath its text. this is a common styling for spelling
errors. another common style can be presented using red dashed underline. result the result should be familiar to anyone who has used any of the more popular word processors available today. avoiding <u> most of the time, you actually don't want to use <u>. here are some examples that show what you should do instead in several cases. non-semantic underlines to underline text without implying an...
Global attributes - HTML: Hypertext Markup Language
h <foo> is not a valid html element. in addition to the basic html global attributes, the following global attributes also exist: xml:lang and xml:base — these are inherited from the xhtml specifications and deprecated, but kept for compatibility purposes. the multiple aria-* attributes, used for improving accessibility. ...
... purposes. the multiple aria-* attributes, used for improving accessibility. ...
...ss to select and style specific elements in a shadow tree via the ::part pseudo-element. slot assigns a slot in a shadow dom shadow tree to an element: an element with a slot attribute is assigned to the slot created by the <slot> element whose name attribute's value matches that slot attribute's value. spellcheck an enumerated attribute defines whether the element may be checked for spelling
errors. it may have the following values: true, which indicates that the element should be, if possible, checked for spelling
errors; false, which indicates that the element should not be checked for spelling
errors. style contains css styling declarations to be applied to the element. note that it is recommended for styles to be defined in a separate file or files. this attribute and the <...
A typical HTTP session - HTTP
200: ok. the request has ...
... 200: ok. the request has succeeded. 301: moved permanently. this response code means that the uri of requested resource has been changed. 404: not found. ...
... 200: ok. the request has succeeded. 301: moved permanently. this response code means that the uri of requested resource has been changed. 404: not found. ...
412 Precondition Failed - HTTP
status 412 precondition failed examples etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" etag: w/"0815" avoiding mid-air collisions with the help of the etag and the if-match headers, you can detect mid-air edit collisions. ...
... status 412 precondition failed examples etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" etag: w/"0815" avoiding mid-air collisions with the help of the etag and the if-match headers, you can detect mid-air edit collisions. ...
... specifications specification title rfc 7232, section 4.2: 412 precondition failed hypertext transfer protocol (http/1.1): conditional requests ...
JavaScript Guide - JavaScript
ut a language feature, have a look at the javascript reference. ...
...nce. ...
...nationalization regular expressions indexed collections arrays typed arrays keyed collections map weakmap set weakset working with objects objects and properties creating objects defining methods getter and setter details of the object model prototype-based oop creating object hierarchies inheritance promises guarantees chaining
error propagation composition timing iterators and generators iterators iterables generators meta programming proxy handlers and traps revocable proxy reflect javascript modules exporting importing default exports renaming features aggregating modules dynamic module loading next » ...
Method definitions - JavaScript
generator methods generator methods can be defined using the shorthand syntax as well. when doing so: the asterisk (*) in the shorthand syntax must be before the generator property name. (that is, * g(){} will work, but g *(){} will not.) non-generator method definitions cannot contain the yield keyword. this means that legacy generator functions won't work either, and will throw a syntax
error. always use yield in conjunction with the asterisk (*). // using a named property const obj2 = { g: function* () { let index = 0 while (true) { yield index++ } } }; // the same object using shorthand syntax const obj2 = { * g() { let index = 0 while (true) { yield index++ } } }; const it = obj2.g() console.log(it.next().value) // 0 console.log(it...
... async f() { await some_promise } } async generator methods generator methods can also be async. ...
...o be async. const obj4 = { f: async function* () { yield 1 yield 2 yield 3 } }; // the same object using shorthand syntax const obj4 = { async* f() { yield 1 yield 2 yield 3 } } method definitions are not constructable methods cannot be constructors! they will throw a type
error if you try to instantiate them. const obja = { method() {} } new obja.method // type
error: obj.method is not a constructor const objb = { * g() {} } new objb.g // type
error: obj.g is not a constructor (changed in es2016) examples simple test case const obj = { a: 'foo', b() { return this.a } }; console.log(obj.b()) // "foo" computed property names the shorthand syntax also supports computed property names. const bar = { foo0: function() { return 0 }, foo1() {...
Functions - JavaScript
ion. here is an example of an anonymous function expression (the name is not used): var myfunction = function() { statements } it is also possible to provide a name inside the definition in order to create a named function expression: var myfunction = function namedfunction(){ statements } one of the benefits of creating a named function expression is that in case we encountered an
error, the stack trace will contain the name of the function, making it easier to find the origin of the
error. as we can see, both examples do not start with the function keyword. statements involving functions which do not start with function are function expressions. when functions are used only once, a common pattern is an iife (immediately invoked function expression). (function() { stateme...
...ences all do approximately the same thing, with a few subtle differences: there is a distinction between the function name and the variable the function is assigned to. the function name cannot be changed, while the variable the function is assigned to can be reassigned. the function name can be used only within the function's body. attempting to use it outside the function's body results in an
error (or undefined if the function name was previously declared via a var statement). for example: var y = function x() {}; alert(x); // throws an
error the function name also appears when the function is serialized via function's tostring method. on the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function...
...tion' does not have a function name. however, in the spidermonkey javascript engine, the serialized form of the function shows as if it has the name "anonymous". for example, alert(new function()) outputs: function anonymous() { } since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. for example, the following would result in an
error: var foo = new function("alert(anonymous);"); foo(); unlike functions defined by function expressions or by the function constructor, a function defined by a function declaration can be used before the function declaration itself. for example: foo(); // alerts foo! function foo() { alert('foo!'); } a function defined by a function expression or by a function declaration inherits the curr...
Array.prototype.indexOf() - JavaScript
string.prototype.indexof(). polyfill indexof() was added to the ecma-262 standard in the 5th edition; as such it may not be present in all browsers. you can work around this by utilizing the following code at the beginning of your scripts. this will allow you to use indexof() when there is still no native support. this algorithm matches the one specified in ecma-262, 5th edition, assuming type
error and math.abs() have their original values. // this version tries to optimize by only checking for "in" when looking for undefined and // skipping the definitely fruitless nan search. other parts are merely cosmetic conciseness. // whether it is actually faster remains to be seen. if (!array.prototype.indexof) array.prototype.indexof = (function(object, max, min) { "use strict" return f...
...n" when looking for undefined and // skipping the definitely fruitless nan search. other parts are merely cosmetic conciseness. // whether it is actually faster remains to be seen. ...
...olyfill to be more useful. // production steps of ecma-262, edition 5, 15.4.4.14 // reference: http://es5.github.io/#x15.4.4.14 if (!array.prototype.indexof) { array.prototype.indexof = function(searchelement, fromindex) { "use strict"; var k; // 1. let o be the result of calling toobject passing // the this value as the argument. if (this == null) { throw new type
error('"this" is null or not defined'); } 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 len is 0, return -1. if (len === 0) { return -1; } // 5. if argument fromindex was passed let n be // toi...
Array.prototype.map() - JavaScript
polyfill map was added to the ecma-262 standard in the 5th edition. therefore, it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. ...
...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. ...
...ll or 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 type
error exception. // see: http://es5.github.com/#x9.11 if (typeof callback !== 'function') { throw new type
error(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 arr...
Array.prototype.some() - JavaScript
polyfill some() was added to the ecma-262 standard in the 5th edition, and it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it. ...
...-262, 5th edition, assuming object and type
error have their original values and that fun.call evaluates to the original value of function.prototype.call(). ...
...ue of function.prototype.call(). // production steps of ecma-262, edition 5, 15.4.4.17 // reference: http://es5.github.io/#x15.4.4.17 if (!array.prototype.some) { array.prototype.some = function(fun, thisarg) { 'use strict'; if (this == null) { throw new type
error('array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw new type
error(); } var t = object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisarg, t[i], i, t)) { return true; } } return false; }; } examples testing value of array elements the following example tests whether any element in the array is bigger than 10. function isbiggerthan10(element, index, array) { retur...
ArrayBuffer() constructor - JavaScript
n 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. ...
...new arraybuffer object of the specified size. its contents are initialized to 0. exceptions a range
error 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 type
error from now on. ...
...tents are initialized to 0. exceptions a range
error 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 type
error from now on. ...
Function.prototype.bind() - JavaScript
th `new (funca.bind(thisarg, args))` if (!function.prototype.bind) (function(){ var slice = array.prototype.slice; function.prototype.bind = function() { var thatfunc = this, thatarg = arguments[0]; var args = slice.call(arguments, 1); if (typeof thatfunc !== 'function') { // closest thing possible to the ecmascript 5 // internal iscallable function throw new type
error('function.prototype.bind - ' + 'what is trying to be bound is not callable'); } return function(){ var funcargs = args.concat(slice.call(arguments)) return thatfunc.apply(thatarg, funcargs); }; }; })(); you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of bind() in ...
...lementations that do not natively support it. ...
...xhaustive) between this algorithm and the specified algorithm are: the partial implementation relies on array.prototype.slice(), array.prototype.concat(), function.prototype.call() and function.prototype.apply(), built-in methods to have their original values. the partial implementation creates functions that do not have immutable "poison pill" caller and arguments properties that throw a type
error upon get, set, or deletion. (this could be added if the implementation supports object.defineproperty, or partially implemented [without throw-on-delete behavior] if the implementation supports the __definegetter__ and __definesetter__ extensions.) the partial implementation creates functions that have a prototype property. (proper bound functions have none.) the partial implementation creates ...
JSON - JavaScript
orted. any json text is a valid javascript expression... ...but only in javascript engines that have implemented the proposal to make all json text valid ecma-262. in engines that haven't implemented the proposal, u+2028 line separator and u+2029 paragraph separator are allowed in string literals and property keys in json; but their use in these features in javascript string literals is a syntax
error. consider this example where json.parse() parses the string as json and eval executes the string as javascript: let code = '"\u2028\u2029"' json.parse(code) // evaluates to "\u2028\u2029" in all engines eval(code) // throws a syntax
error in old engines other differences include allowing only double-quoted strings and having no provisions for undefined or comments. for those who wish ...
...the tab character (u+0009), carriage return (u+000d), line feed (u+000a), and space (u+0020) characters are the only valid whitespace characters. static methods json.parse(text[, reviver]) parse the string text as json, optionally transform the produced value and its properties, and return the value. any violations of the json syntax, including those pertaining to the differences between j...
...riage return (u+000d), line feed (u+000a), and space (u+0020) characters are the only valid whitespace characters. static methods json.parse(text[, reviver]) parse the string text as json, optionally transform the produced value and its properties, and return the value. any violations of the json syntax, including those pertaining to the differences between javascript and json, cause a syntax
error to be thrown. the reviver option allows for interpreting what the replacer has used to stand in for other datatypes. json.stringify(value[, replacer[, space]]) return a json string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner. by default, all instances of undefined are replaced with null, and other unsup...
Object.assign() - JavaScript
ore it assigns properties, versus copying or defining new properties. this may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. for copying property definitions (including their enumerability) into prototypes, use object.getownpropertydescriptor() and object.defineproperty() instead. both string and symbol properties are copied. in case of an
error, for example if a property is non-writable, a type
error is raised, and the target object is changed if any properties are added before the
error is raised. note: object.assign() does not throw on null or undefined sources. polyfill this polyfill doesn't support symbol properties, since es5 doesn't have symbols anyway: if (typeof object.assign !== 'function') { // must be writable: true, e...
...l doesn't support symbol properties, since es5 doesn't have symbols anyway: if (typeof object.assign !== 'function') { // must be writable: true, enumerable: false, configurable: true object.defineproperty(object, "assign", { value: function assign(target, varargs) { // .length of function is 2 'use strict'; if (target === null || target === undefined) { throw new type
error('cannot convert undefined or null to object'); } var to = object(target); for (var index = 1; index < arguments.length; index++) { var nextsource = arguments[index]; if (nextsource !== null && nextsource !== undefined) { for (var nextkey in nextsource) { // avoid bugs when hasownproperty is shadowed if (object.prototype.hasown...
...d will be ignored. // note, only 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 }); // type
error: "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. con...
Object.defineProperties() - JavaScript
eproperties(obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } function iscallable(v) { // nb: modify as necessary if other values than functions are callable. ...
... d.enumerable = !!desc.enumerable; if (hasproperty(desc, 'configurable')) d.configurable = !!desc.configurable; if (hasproperty(desc, 'value')) d.value = desc.value; if (hasproperty(desc, 'writable')) d.writable = !!desc.writable; if (hasproperty(desc, 'get')) { var g = desc.get; if (!iscallable(g) && typeof g !== 'undefined') throw new type
error('bad get'); d.get = g; } if (hasproperty(desc, 'set')) { var s = desc.set; if (!iscallable(s) && typeof s !== 'undefined') throw new type
error('bad set'); d.set = s; } if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) throw new type
error('identity-confused descriptor'); return d; } if (typeof obj !== 'object' || o...
... } if (hasproperty(desc, 'set')) { var s = desc.set; if (!iscallable(s) && typeof s !== 'undefined') throw new type
error('bad set'); d.set = s; } if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) throw new type
error('identity-confused descriptor'); return d; } if (typeof obj !== 'object' || obj === null) throw new type
error('bad obj'); properties = object(properties); var keys = object.keys(properties); var descs = []; for (var i = 0; i < keys.length; i++) descs.push([keys[i], converttodescriptor(properties[keys[i]])]); for (var i = 0; i < descs.length; i++) object.defineproperty(obj, descs[i][0], descs[i][1]); return obj; } examples using object.defineproperties var obj = {}; object.def...
Object.setPrototypeOf() - JavaScript
about 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 type
error 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 p...
...") *** object.appendchain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_body") * * appends the first non-native prototype of a chain to the native function.prototype object, then appends a * new function(["@arg"(s)], "@function_body") to that chain. * returns the function. ...
...type of a chain to the native function.prototype object, then appends a * new function(["@arg"(s)], "@function_body") to that chain. * returns the function. ...
Promise() constructor - JavaScript
resolutionfunc includes a value parameter. the value is passed back to the tethered promiseobj. the promiseobj (asynchronously) invokes any .then() associated with it. the value received by promiseobj.then() is passed to the invocation of handlefulfilled as an input parameter (see "chained promises" section). the executor might also include a try{} catch() block that invokes rejectionfunc upon
error. the signatures of these two functions are simple, they accept a single parameter of any type. of course, the actual names of these functions can be whatever is desired, i.e. they are named as the parameters of executor. each function is used by simply calling it when appropriate. resolutionfunc(value) // call on fulfilled rejectionfunc(reason) // call on rejected the returned value can...
...or. this constructor takes a function, called the "executor function", as its parameter. this function should take two functions as parameters. the first of these functions (resolve) is called when the asynchronous task completes successfully and returns the results of the task as a value. the second (reject) is called when the task fails, and returns the reason for failure, which is typically an
error object. const myfirstpromise = new promise((resolve, reject) => { // do something asynchronous which eventually calls either: // // resolve(somevalue) // fulfilled // or // reject("failure reason") // rejected }); making functions return a promise to provide a function with promise functionality, have it return a promise: function myasyncfunction(url) { return new pro...
... ...
Promise.race() - JavaScript
}); var p2 = new promise(function(resolve, reject) { settimeout(() => resolve('two'), 100); }); promise.race([p1, p2]) .then(function(value) { console.log(value); // "two" // both fulfill, but p2 is faster }); var p3 = new promise(function(resolve, reject) { settimeout(() => resolve('three'), 100); }); var p4 = new promise(function(resolve, reject) { settimeout(() => reject(new
error('four')), 500); }); promise.race([p3, p4]) .then(function(value) { console.log(value); // "three" // p3 is faster, so it fulfills }, function(reason) { // not called }); var p5 = new promise(function(resolve, reject) { settimeout(() => resolve('five'), 500); }); var p6 = new promise(function(resolve, reject) { settimeout(() => reject(new
error('six')), 100); }); promise.race([p5,...
... ...
... ...
handler.construct() - JavaScript
constructor. newtarget the constructor that was originally called, p above. return value the construct method must return an object. description the handler.construct() method is a trap for the new operator. interceptions this trap can intercept these operations: new proxy(...args) reflect.construct() invariants if the following invariants are violated, the proxy will throw a type
error: the result must be an object. examples trapping the new operator the following code traps the new operator. const p = new proxy(function() {}, { construct: function(target, argumentslist, newtarget) { console.log('called: ' + argumentslist.join(', ')); return { value: argumentslist[0] * 10 }; } }); console.log(new p(1).value); // "called: 1" // 1...
...t, argumentslist, newtarget) { console.log('called: ' + argumentslist.join(', ')); return { value: argumentslist[0] * 10 }; } }); console.log(new p(1).value); // "called: 1" // 10 the following code violates the invariant. ...
...nction() {}, { construct: function(target, argumentslist, newtarget) { return 1; } }); new p(); // type
error is thrown the following code improperly initializes the proxy. the target in proxy initialization must itself be a valid constructor for the new operator. const p = new proxy({}, { construct: function(target, argumentslist, newtarget) { return {}; } }); new p(); // type
error is thrown, "p" is not a constructor specifications specification ecmascript (ecma-262)the definition of '[[construct]]' in that specification. ...
handler.getPrototypeOf() - JavaScript
this is bound to the handler. target the target object. return value the getprototypeof() method must return an object or null. description interceptions this trap can intercept these operations: object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof invariants if the following invariants are violated, the proxy will throw a type
error: getprototypeof() method must return an object or null. if target is not extensible, object.getprototypeof(proxy) method must return the same value as object.getprototypeof(target). examples basic usage const obj = {}; const proto = {}; const handler = { getprototypeof(target) { console.log(target === obj); // true console.log(this === handler); // true retur...
... ...
... ...
handler.set() - JavaScript
jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. that proxy's set() handler will be called, and obj will be passed as the receiver. return value the set() method should return a boolean value. return true to indicate that assignment succeeded. ...
... 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. ...
...nt from 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 type
error 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);...
Proxy - JavaScript
erly forwarded!) note that while this "no-op" works for javascript objects, it does not work for native browser objects like dom elements. validation with a proxy, you can easily validate the passed value for an object. this example uses the set handler. ...
...rk for native browser objects like dom elements. validation with a proxy, you can easily validate the passed value for an object. this example uses the set handler. ...
...p]; if (prop === 'selected') { if (oldval) { oldval.setattribute('aria-selected', 'false'); } if (newval) { newval.setattribute('aria-selected', 'true'); } } // the default behavior to store the value obj[prop] = newval; // indicate success return true; } }); let i1 = view.selected = document.getelementbyid('item-1'); //giving
error here, i1 is null console.log(i1.getattribute('aria-selected')); // 'true' let i2 = view.selected = document.getelementbyid('item-2'); console.log(i1.getattribute('aria-selected')); // 'false' console.log(i2.getattribute('aria-selected')); // 'true' note: even if selected: !null, then giving oldval.setattribute is not a function value correction and an extra property the products proxy obj...
Reflect.getOwnPropertyDescriptor() - JavaScript
m/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 type
error, 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: 'hello'}, 'x') // ...
...value: "hello", writable: true, enumerable: true, configurable: true} reflect.getownpropertydescriptor({x: 'hello'}, 'y') // undefined reflect.getownpropertydescriptor([], 'length') // {value: 0, writable: true, enumerable: false, configurable: false} difference to object.getownpropertydescriptor() if the target argument to this method is not an object (a primitive), then it will cause a type
error. ...
...riptor([], 'length') // {value: 0, writable: true, enumerable: false, configurable: false} difference to object.getownpropertydescriptor() if the target argument to this method is not an object (a primitive), then it will cause a type
error. with object.getownpropertydescriptor, a non-object first argument will be coerced to an object at first. reflect.getownpropertydescriptor('foo', 0) // type
error: "foo" is not non-null object object.getownpropertydescriptor('foo', 0) // { value: "f", writable: false, enumerable: true, configurable: false } specifications specification ecmascript (ecma-262)the definition of 'reflect.getownpropertydescriptor' in that specification. ...
TypedArray.prototype.findIndex() - JavaScript
the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that findindex visits that element's index; elements that are deleted are not visited. ...
...tor, thisarg) { 'use strict'; if (!this) { throw new type
error('array.prototype.some called on null or undefined'); } if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // attempt to convert it to a function if ( ! ...
... type
error('array.prototype.some called on null or undefined'); } if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // attempt to convert it to a function if ( ! ...
WebAssembly.instantiate() - JavaScript
tobject); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. 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 the compiled module or else a webassembly.link
error 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 pa...
...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 type
error is thrown. if the operation fails, the promise rejects with a webassembly.compile
error, webassembly.link
error, or webassembly.runtime
error, depending on the cause of the failure. secondary overload — taking a module object instance promise<webassembly.instance> webassembly.instantiate(module, importobject); parameters module the webassembly.module object to be instantiated. importobj...
...romise<webassembly.instance> webassembly.instantiate(module, importobject); parameters module the webassembly.module object to be instantiated. importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of module or else a webassembly.link
error 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 type
error is thrown. if the operation fails, the promise rejects with a webassembly.compile
error, webassembly.link
error, or webassembly.runtime
error, depending on the cause of the failure. examples note: you'll probably wa...
decodeURIComponent() - JavaScript
e 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. ...
...it needs a bit of preparation. ...
...ror ("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'); } catch(e) { console.
error(e); } // uri
error: malformed uri sequence decoding query parameters from a url decodeuricomponent cannot be used directly to parse query parameters from a url. it needs a bit of preparation. function decodequeryparam(p) { return decodeuricomponent(p.replace(/\+/g, ' ')); } decodequeryparam('search+query%20%28correct%29'); // 'search query (correct)' specifications specification...
encodeURI() - JavaScript
odeuricomponent(set3)); // abc%20abc%20123 (the space gets encoded as %20) note that encodeuri() by itself cannot form proper http get and post requests, such as for xmlhttprequest, because "&", "+", and "=" are not encoded, which are treated as special characters in get and post requests. encodeuricomponent(), however, does encode these characters. ...
...", and "=" are not encoded, which are treated as special characters in get and post requests. encodeuricomponent(), however, does encode these characters. ...
...euricomponent(), however, does encode these characters. ...
Iteration protocols - JavaScript
if the iterator has completed its sequence. in this case, value optionally specifies the return value of the iterator. value any javascript value returned by the iterator. can be omitted when done is true. the next() method must always return an object with appropriate properties including done and value. if a non-object value gets returned (such as false or undefined), a type
error ("iterator.next() returned a non-object value") will be thrown. note: it is not possible to know reflectively whether a particular object implements the iterator protocol. however, it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below). doing so allows an iterator to be consumed by the various syntaxes expecting iterable...
...'abc']); // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } console.log(gen().next()); // { value: "a", done: false } [a, b, c] = new set(['a', 'b', 'c']); console.log(a); // "a" non-well-formed iterables if an iterable's @@iterator method doesn't return an iterator object, then it's considered a non-well-formed iterable. ...
...c] = new set(['a', 'b', 'c']); console.log(a); // "a" non-well-formed iterables if an iterable's @@iterator method doesn't return an iterator object, then it's considered a non-well-formed iterable. ...
Nullish coalescing operator (??) - JavaScript
"c was called" and then "foo" // as a() returned undefined so both expressions are evaluated console.log( b() ?? c() ); // logs "b was called" then "false" // as b() returned false (and not null or undefined), the right // hand side expression was not evaluated no chaining with and or or operators it is not possible to combine both the and (&&) and or operators (||) directly with ??. ...
... evaluated console.log( b() ?? ...
...s called" then "false" // as b() returned false (and not null or undefined), the right // hand side expression was not evaluated no chaining with and or or operators it is not possible to combine both the and (&&) and or operators (||) directly with ??. a syntax
error will be thrown in such cases. null || undefined ?? "foo"; // raises a syntax
error true || undefined ?? "foo"; // raises a syntax
error however, providing parenthesis to explicitly indicate precedence is correct: (null || undefined) ?? "foo"; // returns "foo" relationship with the optional chaining operator (?.) the nullish coalescing operator treats undefined and null as specific values and so does the optional chaining operator (?.) which is useful to access a property of an object which may be null or undefined. let foo ...
class expression - JavaScript
declaration (statement). as with class statements, the body of a class expression is executed in strict mode. there are several differences between class expressions and class statements, however: class expressions may omit the class name ("binding identifier"), which is not possible with class statements. class expressions allow you to redefine (re-declare) classes without throwing a syntax
error. this is not the case with class statements. the constructor method is optional. classes generated with class expressions will always respond to typeof with the value "function". 'use strict'; let foo = class {}; // constructor property is optional foo = class {}; // re-declaration is allowed typeof foo; // returns "function" typeof class {}; // returns "function" fo...
...th class expressions will always respond to typeof with the value "function". 'use strict'; let foo = class {}; // constructor property is optional foo = class {}; // re-declaration is allowed typeof foo; // returns "function" typeof class {}; // returns "function" foo instanceof object; // true foo instanceof function; // true class foo {} // throws syntax
error (class declarations do not allow re-declaration) examples a simple class expression this is just a simple anonymous class expression which you can refer to using the variable foo. const foo = class { constructor() {} bar() { return 'hello world!'; } }; const instance = new foo(); instance.bar(); // "hello world!" foo.name; // "foo" named class expressions if you want to...
.../ "foo" named class expressions if you want to refer to the current class inside the class body, you can create a named class expression. the name is only visible within the scope of the class expression itself. const foo = class namedfoo { constructor() {} whoisthere() { return namedfoo.name; } } const bar = new foo(); bar.whoisthere(); // "namedfoo" namedfoo.name; // reference
error: namedfoo is not defined foo.name; // "namedfoo" specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification. ...
super - JavaScript
quare. class rectangle { constructor(height, width) { this.name = 'rectangle'; this.height = height; this.width = width; } sayname() { console.log('hi, i am a ', this.name + '.'); } get area() { return this.height * this.width; } set area(value) { this._area = value; } } class square extends rectangle { constructor(length) { this.height; // reference
error, super needs to be called first! // here, it calls the parent class's constructor with lengths // provided for the rectangle's width and height super(length, length); // note: in derived classes, super() must be called before you // can use 'this'. leaving this out will cause a reference
error. this.name = 'square'; } } super-calling static methods you are also able ...
... you are also able to call super on static methods. class rectangle { constructor() {} static lognbsides() { return 'i have 4 sides'; } } class square extends rectangle { constructor() {} static logdescription() { return super.lognbsides() + ' which are all equal'; } } square.logdescription(); // 'i have 4 sides which are all equal' deleting super properties will throw an
error you cannot use the delete operator and super.prop or super[expr] to delete a parent class' property, it will throw a reference
error. class base { constructor() {} foo() {} } class derived extends base { constructor() {} delete() { delete super.foo; // this is bad } } new derived().delete(); // reference
error: invalid delete involving 'super'. super.prop cannot overwrite non-wri...
...operties with e.g. object.defineproperty, super cannot overwrite the value of the property. class x { constructor() { object.defineproperty(this, 'prop', { configurable: true, writable: false, value: 1 }); } } class y extends x { constructor() { super(); } foo() { super.prop = 2; // cannot overwrite the value. } } var y = new y(); y.foo(); // type
error: "prop" is read-only console.log(y.prop); // 1 using super.prop in object literals super can also be used in the object initializer / literal notation. in this example, two objects define a method. in the second object, super calls the first object's method. this works with the help of object.setprototypeof() with which we are able to set the prototype of obj2 to obj1, so that super is able to...
this - JavaScript
they are properties of the class itself. derived classes unlike base class constructors, derived constructors have no initial this binding. calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where base is the inherited class: this = new base(); warning: referring to this before calling super() will throw an
error. ...
...var obj = {a: 'custom'}; // we declare a variable and the variable is assigned to the global window as its property. ...
... specifications specification ecmascript (ecma-262)the definition of 'the this keyword' in that specification. ...
typeof - JavaScript
s can be used for determining the data type of expressions. let idata = 99; typeof idata + ' wisen'; // 'number wisen' typeof (idata + ' wisen'); // 'string' regular expressions callable regular expressions were a non-standard addition in some browsers. typeof /s/ === 'function'; // chrome 1-12 non-conform to ecmascript 5.1 typeof /s/ === 'object'; // firefox 5+ conform to ecmascript 5.1
errors before ecmascript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. even with undeclared identifiers, typeof will return 'undefined'. using typeof could never generate an
error. but with the addition of block-scoped let and statements/const using typeof on let and const variables (or using typeof on a class) in a block before they are declared will thr...
...script 2015, typeof was always guaranteed to return a string for any operand it was supplied with. even with undeclared identifiers, typeof will return 'undefined'. using typeof could never generate an
error. but with the addition of block-scoped let and statements/const using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a reference
error. block scoped 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. ...
...tatements/const using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a reference
error. block scoped 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; // reference
error typeof newconstvariable; // reference
error typeof newclass; // reference
error 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 ...
break - JavaScript
bel it references. notice that inner_block is nested within outer_block. ...
...onsole.log(':-('); // skipped } console.log('2'); // skipped } break in labeled blocks that throw the following code also uses break statements with labeled blocks, but generates a syntax
error because its break statement is within block_1 but references block_2. a break statement must always be nested within any label it references. block_1: { console.log('1'); break block_2; // syntax
error: label not found } block_2: { console.log('2'); } break within functions syntax
errors are also generated in the following code examples which use break statements within functions that are nested within a loop, or labeled block that the break statements are intended to break out of. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { (function() { break;...
...ns syntax
errors are also generated in the following code examples which use break statements within functions that are nested within a loop, or labeled block that the break statements are intended to break out of. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { (function() { break; })(); } i += 1; } return i * x; } testbreak(1); // syntax
error: illegal break statement block_1: { console.log('1'); ( function() { break block_1; // syntax
error: undefined label 'block_1' })(); } specifications specification ecmascript (ecma-262)the definition of 'break statement' in that specification. ...
class - JavaScript
rce for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. you can also define a class using a class expression. but unlike a class expression, a class declaration doesn't allow an existing class to be declared again and will throw a syntax
error if attempted. syntax class name [extends othername] { // class body } description the class body of a class declaration is executed in strict mode. the constructor method is optional. class declarations are not hoisted (unlike function declarations). examples a simple class declaration in the following example, we first define a class named polygon, then extend it to create a class na...
...must be called before the this keyword can be used. class polygon { constructor(height, width) { this.name = 'polygon'; this.height = height; this.width = width; } } class square extends polygon { constructor(length) { super(length, length); this.name = 'square'; } } attempting to declare a class twice re-declaring a class using the class declaration throws a syntax
error. ...
...lass polygon { constructor(height, width) { this.name = 'polygon'; this.height = height; this.width = width; } } class square extends polygon { constructor(length) { super(length, length); this.name = 'square'; } } attempting to declare a class twice re-declaring a class using the class declaration throws a syntax
error. class foo {}; class foo {}; // uncaught syntax
error: identifier 'foo' has already been declared the same
error is thrown when a class has been defined before using the class expression. let foo = class {}; class foo {}; // uncaught syntax
error: identifier 'foo' has already been declared specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification. ...
MathML element reference - MathML
28). if you want to learn more about content markup you should consider chapter 4 in the mathml 3 specification. mathml elements implement the mathmlelement class. ...
...n more about content markup you should consider chapter 4 in the mathml 3 specification. mathml elements implement the mathmlelement class. ...
...matrix) u <munder> (underscript) <munderover> (underscript-overscript pair) other elements <semantics> (container for semantic annotations) <annotation> (data annotations) <annotation-xml> (xml annotations) mathml presentation elements by category top-level elements <math> token elements <mglyph> <mi> <mn> <mo> <ms> <mspace> <mtext> general layout <menclose> <m
error> <mfenced> <mfrac> <mpadded> <mphantom> <mroot> <mrow> <msqrt> <mstyle> script and limit elements <mmultiscripts> <mover> <mprescripts> <msub> <msubsup> <msup> <munder> <munderover> <none> tabular math <maligngroup> <malignmark> <mlabeledtr> <mtable> <mtd> <mtr> elementary math <mlongdiv> <mscarries> <mscarry> <msgroup> <msline> <msrow> <mstack> uncat...
Autoplay guide for media and Web Audio APIs - Web media technologies
en autoplay fails, you likely will want to offer a way for the user to manually tell the browser to ask the user to grant permission to play media. you might use code like this to accomplish the job: let startplaypromise = videoelem.play(); if (startplaypromise !== undefined) { startplaypromise.then(() => { // start whatever you need to do only after playback // has begun. }).catch(
error => { if (
error.name === "notallowed
error") { showplaybutton(videoelem); } else { // handle a load or playback
error } }); } the first thing we do with the result of play() is make sure it's not undefined. we check for this because in earlier versions of the html specification, play() didn't return a value. returning a promise to allow you to determine success or failur...
...ndle a load or playback
error } }); } the first thing we do with the result of play() is make sure it's not undefined. we check for this because in earlier versions of the html specification, play() didn't return a value. returning a promise to allow you to determine success or failure of the operation was added more recently. checking for undefined prevents this code from failing with an
error on older versions of web browsers. if the promise returned by play() is resolved without
error, the then() clause is run and can begin whatever needs to be done when autoplay has begun. we then add a catch() handler to the promise. this looks at the
error's name to see if it's notallowed
error. this indicates that playback failed due to a permission issue, such as autoplay being denied. if that'...
... autoplay using the web audio api in the web audio api, a web site or app can start playing audio using the start() method on a source node linked to the audiocontext. doing so outside the context of handling a user input event is subject to autoplay rules. ...
The "codecs" parameter in common media types - Web media technologies
hvxc (harmonic vector excitation coding) main, scalable, speech, ld 10 – 11 reserved 12 ttsi (text to speech interface) main, scalable, speech, synthetic, ld 13 main synthetic main, synthetic 14 wavetable synthesis 15 general midi 16 algorithmic synthesis and audio effects 17 er aac lc (
error resilient aac low-complexity) hq, mobile internetworking 18 reserved 19 er aac ltp (
error resilient aac long term prediction) hq 20 er aac scalable (
error resilient aac scalable) mobile internetworking 21 er twinvq (
error resilient twinvq) mobile internetworking 22 er bsac (
error reslient bit-sliced arithmetic coding) ...
...rnetworking 18 reserved 19 er aac ltp (
error resilient aac long term prediction) hq 20 er aac scalable (
error resilient aac scalable) mobile internetworking 21 er twinvq (
error resilient twinvq) mobile internetworking 22 er bsac (
error reslient bit-sliced arithmetic coding) mobile internetworking 23 er aac ld (
error resilient aac low-delay; used for two-way communication) ld, mobile internetworking 24 er celp (
error resilient code-excited linear prediction) hq, ld 25 er hvxc (
error resilient harmonic vector excitation coding) ld 26 er hiln (
error resilient harmonic and individual line plus noise) 27 er parametric (
error resilient parametric) ...
...-aac v2 30 mpeg surround 31 escape 32 mpeg-1 layer-1 33 mpeg-1 layer-2 (mp2) 34 mpeg-1 layer-3 (mp3) 35 dst (direct stream transfer) 36 als (audio lossless) 37 sls (scalable lossless) 38 sls non-core (scalable lossless non-core) 39 er aac eld (
error resilient aac enhanced low delay) 40 smr simple (symbolic music representation simple) 41 smr main (symbolic music representation main) 42 reserved 43 saoc (spatial audio object coding)[1] 44 ld mpeg surround (low delay mpeg surround)[1] 45 and up reserved [1] saoc and ld mpeg surround are d...
OpenSearch description format
nsearchdescription+xml" rel="self" template="https://example.com/mysearchdescription.xml" /> note: at this time, addons.mozilla.org (amo) doesn't support automatic updating of opensearch plugins. if you want to put your search plugin on amo, remove the auto-updating feature before submitting it. troubleshooting tips if there is a mistake in your search plugin xml, you could run into
errors when adding a discovered plugin. if the
error message isn't be helpful, the following tips could help you find the problem. your server should serve opensearch plugins using content-type: application/opensearchdescription+xml. be sure that your search plugin xml is well formed. you can check by loading the file directly into firefox. ampersands (&) in the template url must be escaped as &...
...ver should serve opensearch plugins using content-type: application/opensearchdescription+xml. be sure that your search plugin xml is well formed. you can check by loading the file directly into firefox. ampersands (&) in the template url must be escaped as &, and tags must be closed with a trailing slash or matching end tag. the xmlns attribute is important — without it you could get the
error message "firefox could not download the search plugin". you must include a text/html url — search plugins including only atom or rss url types (which is valid, but firefox doesn't support) will also generate the "could not download the search plugin"
error. remotely fetched favicons must not be larger than 10kb (see bug 361923). in addition, the search plugin service provides a logging mech...
...d, but firefox doesn't support) will also generate the "could not download the search plugin"
error. remotely fetched favicons must not be larger than 10kb (see bug 361923). in addition, the search plugin service provides a logging mechanism that may be useful to plugin developers. use about:config to set the pref 'browser.search.log' to true. then, logging information will appear in firefox's
error console (tools 〉
error console) when search plugins are added. reference material opensearch documentation safari 8.0 release notes: quick website search microsoft edge dev guide: search provider discovery the chromium projects: tab to search imdb.com has a working osd.xml opensearch plugin generator ready2search - create opensearch plugins. customized search through ready2search ...
Namespaces crash course - SVG: Scalable Vector Graphics
prefix parameter and element names. this is done by putting the namespace prefix and a colon before the parameter name as shown on the <script> element in the example above. this tells the user agent that that particular parameter belongs to the namespace assigned to the namespace prefix (xlink), and is a parameter that can be used with the same meaning on other elements. note that it is an xml
error to use a prefix that hasn't been bound to a namespace name. the binding created by the xmlns:xlink parameter in the example above is absolutely essential for the xlink:href parameter to not cause an
error. this xlink parameter is also frequently used in svg on the <a>, <use> and <image> elements among others, so it's a good idea to always include the xlink declaration in your documents. as an as...
...entns(svg_ns, 'image'); image.setattributens(null, 'width', '100'); image.setattributens(null, 'height', '100'); image.setattributens(xlink_ns, 'xlink:href', 'flower.png'); conclusion make sure you always declare the namespaces you use in your xml files. if you don't, user agents such as firefox won't recognize your content and will simply show the xml markup or inform the user that there's an
error in the xml. it's a good idea to use a template that includes all the commonly used namespace declarations when creating new svg files. if you don't already have one, make one up starting with the following code: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> even if you don't use all those namespaces in a particular document, there's no harm in ...
...monly used namespace declarations when creating new svg files. if you don't already have one, make one up starting with the following code: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> even if you don't use all those namespaces in a particular document, there's no harm in including the namespace declarations. it may save you from some annoying
errors if you end up adding content from one of the unused namespaces at a later date. a full example for a full example see svg: namespaces crash course: example. ...
SVG In HTML Introduction - SVG: Scalable Vector Graphics
css can be used to manipulate the picture in the same way you would script regular html. ...
....setattribute("class", "invalid"); } </script> </head> <body id="body" style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;"> <form> <fieldset> <legend>html form</legend> <p><label>enter something:</label> <input type="text"> <span id="err">incorrect value!</span></p> <p><input type="button" value="activate!" onclick="signal
error();"></p> </fieldset> </form> <svg viewbox="0 0 100 100" preserveaspectratio="xmidymid slice" style="width:100%; height:100%; position:absolute; top:0; left:0; z-index:-1;"> <lineargradient id="gradient"> <stop class="begin" offset="0%"/> <stop class="end" offset="100%"/> </lineargradient> <rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" /> <circle cx="...
.... this element and its children are declared to be in the svg namespace. the element contains a gradient and two shapes filled with the gradient. the gradient color stops have their colors set by css. when the user enters something incorrect into the form, the script sets the invalid attribute on the <body>, and a style rule changes the gradient end-stop color to red. ...
Introduction to using XPath in JavaScript - XPath
ath interface will not automatically convert the numerical result if the stringvalue property is requested, so the following code will not work: var paragraphcount = document.evaluate('count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.stringvalue + ' paragraph elements' ); instead, it will return an exception with the code ns_dom_type_
error. 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 as an iterator, allowing us to ...
...access the individual nodes contained by using the iteratenext() method of the xpathresult. once we have iterated over all of the individual matched nodes, iteratenext() will return null. ...
...f xpathresult is set to true, and a ns_
error_dom_invalid_state_err exception is thrown. ...
Logging - Archive of obsolete content
you don't have to require() anything to get access to the console. it is automatically made available to you. ...
...ment.body.innerhtml);" }); }); console output if you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used. if you've installed the add-on in firefox then the messages appear in firefox's browser console. but note that by default, calls to console.log() will not result in any output in the
error console for any installed add-ons: this includes add-ons installed using the add-on builder or using tools like the extension auto-installer. see "logging levels" in the console reference documentation for more information on this. learning more for the complete console api, see its api reference. ...
Canvas code snippets - Archive of obsolete content
g class first creates a hidden iframe element and attaches a listener to the frame's load event. once the remote page has loaded, the remotepageloaded method fires. this method gets a reference to the iframe's window and draws this window to a canvas object. note that this only works if you are running the page from chrome. if you try running the code as a plain webpage, you will get a 'security
error" code: "1000'
error. remotecanvas = function() { this.url = 'http://developer.mozilla.org'; }; remotecanvas.canvas_width = 300; remotecanvas.canvas_height = 300; remotecanvas.prototype.load = function() { var windowwidth = window.innerwidth - 25; var iframe; iframe = document.createelement('iframe'); iframe.id = 'test-iframe'; iframe.height = '10px'; iframe.width = ...
...; remotecanvas.load(); convert image files to base64 strings the following code gets a remote image and converts its content to data uri scheme. ...
Downloading Files - Archive of obsolete content
for example, with empty dummy methods if you are not interested about the progress. instead of using qi like above, you can also implement nsiinterfacerequestor and return nsiauthprompt from there, like nsiwebbrowserpersist.progresslistener documentation suggests. downloading images sample function for fe...
...using qi like above, you can also implement nsiinterfacerequestor and return nsiauthprompt from there, like nsiwebbrowserpersist.progresslistener documentation suggests. downloading images sample function for fetching an image file from a url. // this function is for fetching an image file from a url. // accepts a url and returns the file. // returns empty if the file is not found (with an 404
error for instance). // tried with .jpg, .ico, .gif (even .html). function getimagefromurl(url) { var ioserv = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var channel = ioserv.newchannel(url, 0, null); var stream = channel.open(); if (channel instanceof components.interfaces.nsihttpchannel && channel.responsestatus !=...
File I/O - Archive of obsolete content
read and therefore block the ui for periods of time. this sample code uses netutil.jsm. so therefore for the first parameter, file, you can pass an nsifile object or a string (such as a jar path) see: netutil.asyncfetch: components.utils.import("resource://gre/modules/netutil.jsm"); netutil.asyncfetch(file, function(inputstream, status) { if (!components.issuccesscode(status)) { // handle
error! return; } // the file data is contained within inputstream. // you can read it into a string with var data = netutil.readinputstreamtostring(inputstream, inputstream.available()); }); read with content type hint it's useful to provide a content type hint to prevent the file system from doing a potentially expensive content type look up (which would be synchronous i/o). in this ca...
...r = components.classes["@mozilla.org/intl/scriptableunicodeconverter"]. createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = "utf-8"; var istream = converter.converttoinputstream(data); // the last argument (the callback) is optional. netutil.asynccopy(istream, ostream, function(status) { if (!components.issuccesscode(status)) { // handle
error! return; } // data has been written to the file. }); copy a stream to a file this function copies all of the data from an input stream to a file asyncronously. it overwrites the file if it is there, and if it is not there it creates a file then writes into it. it takes an nsiinputstream and an nsifile as arguments, and uses netutil.jsm and fileutils.jsm. the callback argument is optio...
StringView - Archive of obsolete content
o and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer. however, this is slow and
error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently. the stringview constructor is one level above typed arrays. the code stringview.js "use strict"; /*\ |*| |*| :: number.isinteger() polyfi...
...ngview.prototype.encoding = "utf-8"; /* default encoding... ...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
idl \ myisecondcomponent.idl \ $(null) include $(topsrcdir)/config/rules.mk xpidl_module is the name of the generated xpt file that contains type information about your idl interfaces. if you have multiple modules, make absolutely sure that you use a different value for xpidl_module for each one. otherwise the first module's xpt file will be overwritten by the second and you'll get ns_
error_xpc_bad_iid
errors when you try to access its idl interfaces from your code. the files under exports are copied directly to the /mozilla/$(moz_objdir)/dist/include/ directory and are thus accessible from other modules (the value of moz_objdir is defined in /mozilla/.mozconfig). xpidlsrcs are run through the idl processor, and the generated c++ headers are copied into the same include directory. i...
...ace the javascript file that implements the component. the component implementation will include the methods for retrieving the path or file for the extension's home directory: mylocation.prototype = { queryinterface: function(iid) { if (iid.equals(nsisupports)) return this; if (iid.equals(myilocation)) return this; components.returncode = components.results.ns_
error_no_interface; return null; }, get locationfile() { return __location__.parent.parent; } } this assumes that the component resides in a subdirectory of the extension directory (by convention, this directory is called components/). the parent property of __location__ returns the components/, and the parent of this is the extension directory. the last step is to modif...
Enhanced Extension Installation - Archive of obsolete content
installed from the web, via xpinstall, upgraded by xpinstall or dropped into a directory-based install location), the install manifest supplied by the item is expanded into a temporary location and read. the guid and version supplied are validated, and then compatibility is checked for by the new _getinstalldata function. this function returns the guid, version, and type of the item, and also an
error code listing either success, or the reason for a failure, such as invalid guid, version, or incompatible item. depending on the failure, the install function may take several steps. if the item is found incompatible, a version update check is performed as before. if updated compatibility information is found this is written into the in-memory representation of the the temporary install manifest ...
...stalling into restricted install locations can specify that their item does not show up in the extensions ui by using the <em:hidden>true<em:hidden> property in their install manifests. this property is ignored for extensions installed into unrestricted locations, such as the profile location, to prevent abuse. there is more logging for failures in the installation and update process. the set of
error logs written is still neither perfect nor complete, but it's a very good start. log strings are written to the application's
error console (in anticipation of that api automatically logging to a file) and to the terminal window. we now check more effectively for system integrity during startup. we ask each install location if it is functioning (for a directory install location such as app-profil...
Jetpack Processes - Archive of obsolete content
the handle is still valid or not. read-only. isrooted whether the handle is gc rooted or not. read-write. oninvalidate a callback to call when the handle is garbage collected, either through an explicit call to invalidate() or being unrooted and then unreachable. the callback is only called from the process that the handle was not garbage collected in. read-write. ...
...nrooted 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 ...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
kage will not be available in firefox 3. this document is a guide to common code patterns that may need to change to work with frozen linkage. strings the most obvious change required by frozen linkage is using the frozen string api. - #include "nsastring.h"- #include "nsstring.h"- #include "nsreadableutils.h"- #include "nsescape.h" + #include "nsstringapi.h" on windows, if you see the following
error, you are including a header you shouldn't be: nsstringfwd.h(60) : fatal
error c1001: internal compiler
error to debug this
error, make in the failing directory, adding the /showincludes directive to figure out what is being included incorrectly: make -c directory/that/failed os_cppflags=-showincludes the frozen string api is similar but not identical to the nonfrozen string api. the frozen stri...
...e conversion yourself. the adopt and getter_copies methods do not work on abstract strings. instead of passing getter_copies(astring) to a method expecting a character pointer out parameter, you will need to use a temporary variable and copy the result.missing headers some headers are included from idl files only when mozilla_internal_api is defined (actually, they shouldn't be there at all). for
errors about undeclared do_createinstance: #include "nscomponentmanagerutils.h" for
errors about undeclared do_getservice: #include "nsservicemanagerutils.h" for
errors about undeclared ns_getspecialdirectory: #include "nsdirectoryserviceutils.h" utility classes some utility classes could previously be created with ns_new* utility functions. these classes must now be created using xpcom: // nsisup...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
when you run it, you should see a red bar, showing that it failed. implement in calc.js we need to flesh out calc.js. update it with the contents of listing 3. run test run the test again. you should see a green bar showing that the test succeeded. implement the subtraction operation now let’s add subtraction. create test case first, add the tes...
...e looking for (see figures 6, 7).4 this results in the file nsilocalfile.idl. let’s display it. every method includes explanatory comments. in initwithpath, the nsilocalfile object gets initialized, and any information already in it gets reset. also be aware of a potential problem when using paths not representing entities.5 this requires a full path as an argument. relative paths will throw
errors. this should help you understand the initwithpath specification. fixme: figure 6: searching without a trailing space fixme: figure 7: searching with a trailing space fixme: listing 7: source-code fragment var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(hoge); how is this actually implemented? if ...
Setting Up a Development Environment - Archive of obsolete content
a file location, in case you want to see dump output from firefox, or other extensions. the last & prevents automator from waiting for your firefox session to finish. save this as an application, not a workflow. and you probably want to have these on your desktop or dock, for easy access. there are also some configuration changes you should make in your testing profiles, so that you get detailed
error information in case something fails. the firefox
error console (tools >
error console) normally displays javascript
errors that occur on web pages, but with some tweaking you can get
error information from your extension. read this piece on development preferences. developer extensions there's a wide variety of firefox extensions that aid web development and add-on development. a good place to ...
...hat they take memory usage seriously, improving performance on several critical areas and removing all kinds of memory leaks. however, extensions are also capable of causing memory leaks. if you want your extension to be included in the mozilla add-ons site, you better not have any memory leaks. using xpcom in javascript has some guidelines you should follow to avoid them. one of the most common
errors developers make is to register a js event listener or observer, and never removing it. the simple practice of always including removal code for everything you add makes a big difference. to make sure your extension doesn't leak, you should use the leak monitor extension when testing it. always test opening and closing windows. leaks usually surface when doing this. exercise set up a new fir...
The Essentials of an Extension - Archive of obsolete content
sers can disable version checks through preferences or installing add-ons like the add-on compatibility reporter. beginning with firefox 11, add-ons will default to compatible and firefox will mostly ignore the version range. testing your add-ons with every firefox version is always recommended, though. this is the information firefox and other mozilla applications need to install an add-on. any
errors or missing information will cause the installation process to fail, or the extension to be installed in a disabled state. the chrome.manifest file chrome is the set of user interface elements of the application window that are outside of a window's content area. toolbars, menu bars, progress bars, and window title bars are all examples of elements that are typically part of the chrome. take...
... and in the dtd file you can see the association between keys and localized strings: <!entity xulschoolhello.hello.label "hello world!"> <!entity xulschoolhello.hellomenu.accesskey "l"> <!entity xulschoolhello.helloitem.accesskey "h"> notice that on the xul file you enclose the string key with & and ; while on the dtd file you only specify the key. you may get weird parsing
errors or incorrect localization if you don't get this right. access keys are the shortcuts that allow you to quickly navigate a menu using only the keyboard. they are also the only way to navigate a menu for people with accessibility problems, such as partial or total blindness, or physical disabilities that make using a mouse very difficult or impossible. you can easily recognize the access keys on ...
Install.js - Archive of obsolete content
xtskinnames[skin] + '/' + this.extshortname + '/'; install.registerchrome(install.skin | installtype, jarpath, regpath); } // perform install var err = install.performinstall(); if (err == install.success || err == install.reboot_needed) { if (!this.silentinstall && this.extpostinstallmessage) { install.alert(this.extpostinstallmessage); } } else { this.handle
error(err); return; } }, parsearguments: function() { // can't use string handling in install, so use if statement instead var args = install.arguments; if (args == 'p=0') { this.profileinstall = false; this.silentinstall = true; } else if (args == 'p=1') { this.profileinstall = true; this.silentinstall = true; } }, handle
error: function(err) { if (!this.sil...
...arguments: function() { // can't use string handling in install, so use if statement instead var args = install.arguments; if (args == 'p=0') { this.profileinstall = false; this.silentinstall = true; } else if (args == 'p=1') { this.profileinstall = true; this.silentinstall = true; } }, handle
error: function(err) { if (!this.silentinstall) { install.alert('
error: could not install ' + this.extfullname + ' ' + this.extversion + ' (
error code: ' + err + ')'); } install.cancelinstall(err); } }; xpiinstaller.install(); ...
Monitoring WiFi access points - Archive of obsolete content
netscape.security.privilegemanager.enableprivilege('universalxpconnect'); var d = document.getelementbyid("d"); d.innerhtml = ""; for (var i=0; i<accesspoints.length; i++) { var a = accesspoints[i]; d.innerhtml += "<p>" + a.mac + " " + a.ssid + " " + a.signal + "</p>"; } var c = document.getelementbyid("c"); c.innerhtml = "<p>" + count++ + "</p>"; }, on
error: function (value) { alert("
error: " +value); }, queryinterface: function(iid) { netscape.security.privilegemanager.enableprivilege('universalxpconnect'); if (iid.equals(components.interfaces.nsiwifilistener) || iid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_
error_no_interface; }, } netscape.se...
...nchange() method (lines 13 through 27) begins by enabling universalxpconnect privileges, then clearing out the div (d) that will receive the updated list of access points. then the loop in lines 19-22 iterates over the list of access points received in the accesspoints array and adds them to the html in the div. then the c div is updated with the number of times the list has been refreshed. the on
error() method simply opens an alert that displays the
error code received. starting to monitor access points to start monitoring the access points, we instantiate the listener (on line 44), then get access to the wifi monitor interface on line 45. the monitoring is started up on line 47, by calling the wifi monitoring service's startwatching() method. ...
Helper Apps (and a bit of Save As) - Archive of obsolete content
decides whether the data should be content-decoded (based on some not-so-great heuristics). decides whether the user should be prompted (based on a preference). calls show() on the nsihelperapplauncherdialog, which asynchronously puts up the helper app dialog. nsexternalapphandler::ondataavailable here we just copy the newly arrived data over into our temporary file. if any read or write
errors occur, abort the whole process: cancel the channel. pull down the helper app dialog (if any). remove the temp file. nsexternalapphandler::onstoprequest set a flag that we're done, then do whatever the user wants if the user has decided (save to disk and open in helper are the current options the user has). helper app dialog this is our implementation of nsihelperapplauncherdialog it c...
...ser has decided (save to disk and open in helper are the current options the user has). helper app dialog this is our implementation of nsihelperapplauncherdialog it calls back to the nsexternalapphandler to let it know what the user picked saving to disk if a user decides to "save to disk", we just move/copy the temporary file over to the chosen location once the download completes. if an
error occurs while we do this we delete the temp file and put up an
error dialog. launching a helper application this is delegated to the nspiexternalapplauncher (also implemented by the nsexternalhelperapphandler): windows: launch either directly via nsiprocess or via the ::shellexecute() method depending on where the mimeinfo came from. last-ditch check for executable files here. mac: use the l...
JavaScript crypto - Archive of obsolete content
e, this flag should always be set to 0; otherwise, mozilla might exhibit unpredictable behavior. ...
...eturn values js_ok_add_module = 3 // successfully added a module js_err_other = -1 //
errors other than the following js_err_user_cancel_action = -2 // user aborted an action js_err_incorrect_num_of_arguments = -3 // calling a method w/ incorrect # of // arguments js_err_add_module = -5 //
error adding a module js_err_bad_module_name = -6 // the module name is invalid js_err_add_module_duplicate = -10 // the module being installed has the // same name as one of the modules that // has already been installed miscellaneous domstring random(in long numbytes); unimplementedyou can use windo...
Nanojit - Archive of obsolete content
= out.insskip(sizeof(guardrecord) + sizeof(sideexit)); guardrecord *guard = (guardrecord *) rec_ins->payload(); memset(guard, 0, sizeof(*guard)); sideexit *exit = (sideexit *)(guard + 1); guard->exit = exit; guard->exit->target = f; f->lastins = out.insguard(lir_loop, out.insimm(1), rec_ins); // compile the fragment. compile(assm, f, *alloc verbose_only(, fragmento->labels)); if (assm->
error() != none) { fprintf(stderr, "
error compiling fragment\n"); return 1; } printf("compilation successful.\n"); // call the compiled function. typedef js_fastcall int32_t (*addtwofn)(int32_t); addtwofn fn = reinterpret_cast<addtwofn>(f->code()); printf("2 + 5 = %d\n", fn(5)); return 0; } code explanation interesting part are the lines 46-50: // write a few lir instructions to the buf...
...he code provided above is doing is feeding raw lir into the lir buffer, using the lirwriter's writer object. from an operational point of view, it is creating a function, which takes an integer input, and adds it to two, and outputs the result. the function is created here on lines 57-69: // compile the fragment. compile(assm, f, *alloc verbose_only(, fragmento->labels)); if (assm->
error() != none) { fprintf(stderr, "
error compiling fragment\n"); return 1; } printf("compilation successful.\n"); // call the compiled function. typedef js_fastcall int32_t (*addtwofn)(int32_t); addtwofn fn = reinterpret_cast<addtwofn>(f->code()); printf("2 + 5 = %d\n", fn(5)); return 0;</addtwofn> this upper half of this snippet includes code where the raw lir is first converted into ...
File object - Archive of obsolete content
programs generating output on stdout) begin with the pipe symbol; writeable pipelines end with the pipe symbol. bi-directional pipelines are not supported. properties static properties file.input a file object that represents the standard input (stdin). file.currentdir a file object that represents the standard output (stdout). file.currentdir a file object that represents the standard
error (stderr). file.currentdir a file object referring to the current directory; this property may be set. file.separator the system name separator (slash on unix). instance properties file.length the length of the file in bytes, or the number of entries in the directory. note: calculating the length of the directory is very expensive. file.parent the directory containing the file. file.p...
...s true if random access is supported for this file. binary (utf-8) files and pipelines (including file.intput) do not support random access. file.hasautoflush force a flush on each line break? (readonly) file.position the file position. writing to the property moves the file pointer. file.isnative true if the file is backed by a native stdio file stream. (i.e. file.input, file.output, file.
error or a pipeline) methods file.open() opens the file, specifying file mode and type. file.close() closes the file. file.remove() removes the file, provided it is not open. file.copyto() creates a verbatim copy of the file at a new location. file.renameto() removes the file. file.flush() flushes the operating system's write buffers for the file and blocks until any pending data has be...
Running Tamarin performance tests - Archive of obsolete content
it's unreliable, losing its adb connection frequently. an emulator is ok for testing a few abc files but fo...
...ts to run performance tests on android you don't need to pass --androidthreads or --threads=1 as with the acceptance tests; in fact, a usage
error will result. just type the following commands after making sure you've set the environment variables correctly. $ cd /test/performance $ ./runtests.py note on using an emulator: the emulator does seem to support hardware floating point but gives a bus
error when running avmshell -darm_vfp. it's unreliable, losing its adb connection frequently. an emulator is ok for testing a few abc files but for any consistency a real device is better. ...
Tamarin build documentation - Archive of obsolete content
ice in the makefile (near line 65) to point to your sdk/ndk top folder. - find the two instances of "android-ndk" and make sure they match your ndk's name (they should already). - in a terminal window change to your /openssl folder and run make build_libs to create the necessary 'libcrypto.a' and 'libssl.a' static libraries. alternatively, run make, in which case the process will complete with
errors when it tries to create the shared lib crt0.o: $ /android-public/android-ndk/toolchains/arm-eabi-4.4.0/prebuilt/darwin-x86/bin/../lib/gcc/arm-eabi/4.4.0/../../../../arm-eabi/bin/ld: crt0.o: no such file: no such file or directory collect2: ld returned 1 exit status make[2]: *** [link_app.]
error 1 make[1]: *** [openssl]
error 2 make: *** [build_apps]
error 1 you can ignore these
errors. the ne...
...be project_root/build_name/avm note: as discussed above, the c++ indexer has been setup to track the current build config, so the correct conditional compiles are highlighted in the editor run/debug from eclipse for test purposes, a launch config (running the helloworld test from esc) has been included for each of the build configs. all are available from the run menu. note: if you receive an
error when trying to run/debug a newly imported project, try opening a file in the project first - eclipse can sometimes get confused as to what the 'current project' actually is. additional things to try are clicking on the project name then refreshing it (file/refresh or right-click/refresh) and/or quitting and restarting eclipse. linux and unix tamarin is tested on linux but not on other unix flav...
URIs and URLs - Archive of obsolete content
be escaped more than once. necko will not escape an already escaped character unless forced by a special mask that can be used if it is known that a string is not escaped. parsing urls rfc 2396 defines an url parser that can deal with the syntax that is common to most url schemes that are currently in existence. sometimes scheme specific parsing is required. also to be somewhat tolerant to syntax
errors the parser has to know more about the specific syntax of the urls for that scheme. to stay almost generic necko contains three parsers for the main classes of standard urls. which one has to be used is defined by the implementation of nsiprotocolhandler for the scheme in question. the three main classes are: authority the urls have an authority segment, like "http". noauthority ...
...rsing of non-hierarchical uri. for backwards compatibility, an implementation may work around such references by removing the scheme if it matches that of the base uri and the scheme is known to always use the "hier_part" syntax. the parser can then continue with the steps below for the remainder of the reference components. validating parsers should mark such a misformed relative reference as an
error. the decision was made against backwards compatibility. this means that urls like "http:page.html" or "http:/directory/page.html" are interpreted as absolute urls and "corrected" by the parser. also the handling of query segments is different from the examples given in rfc 2396: within an object with a well-defined base uri of http://a/b/c/d;p?q the relative uri would be resolved as fo...
Writing textual data - Archive of obsolete content
nsures 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 replacement characte...
...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 replacement character is not a supported character in the chosen character encoding, attempts to write unsupported characters will fail with ns_
error_loss_of_significant_data. versions before gecko 1.8 firefox 1.0.x, mozilla 1.7.x and older versions do not support nsiconverteroutputstream. alternative ways usable from javascript do not support character encodings that use embedded nulls (such as utf-16 and utf-32). they work by manually converting the string you want to write to a byte sequence using nsiscriptableunicodeconverter, and writi...
addFile - Archive of obsolete content
me relative to the localdirspec parameter. the file is installed in this location on the user's machine. you must always use forward slashes (/) in this pathname, regardless of the convention of the underlying operating system. if this parameter is blank or null, xpisourcepath is used. flags an optional field; reserved for future use. pass 0 as the default value. returns an integer
error code. for a list of possible values, see return codes. description the addfile method puts the file in a temporary location. to move this and all other files to their final location, call the performinstall method after you've successfully added all files. note: if you are installing binary files on a macintosh, be aware that the binary format for those files must be applesingle if the resource...
...be installed properly. ...
cancelInstall - Archive of obsolete content
summary aborts installation of the software; performs cleanup of temporary files. method of install object syntax void cancelinstall() void cancelinstall( int
errorcode ) parameters none. returns an integer
error code. the optional argument is an
error code that can be returned to the triggering page. for most purposes, it's recommended that one of the standard return codes be used. but a script can, in fact, return any valid integer. for a list of possible values, and any custom
errorcode created by install writer, see return codes. ...
...return codes be used. but a script can, in fact, return any valid integer. for a list of possible values, and any custom
errorcode created by install writer, see return codes. ...
execute - Archive of obsolete content
a parameter string that is passed to the executable. (ignored on mac os). see note below. blocking a boolean value that specifies whether the installation should wait for the execution of the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this method in versions of netscape before 6.1/mozilla 0.9.3. returns an integer
error code. for a list of possible values, see return codes. description the execute method extracts the named file from the xpi file to a temporary file name. your code must call the performinstall method to actually execute the file. you can use this method to launch an installshield installer or any install executable file stored in a xpi file. executing installed files note: if the file you wi...
...ect's execute method, on the other hand, deletes the executable from its temporary location once it has finished. the optional blocking argument, when set to true, specifies that the installation should wait for this executable to finish before processing the next queued install command. if you do not set this flag and launch an executable that is not a part of the installation, you will raise an
error when you restart the browser. passing arguments to the executable the args parameter, when present, passes a string to the executable as command-line parameters. the following line, for example, passes the "-c" command-line parameter to the executable: err = file.execute(myfile, "-c", true); when you want to pass more than one parameter to the executable itself, however, you must format the ar...
patch - Archive of obsolete content
string representing the directory to the getfolder method. relativelocalpath a pathname relative to the localdirspec parameter that identifies the subcomponent that is to be patched. you must always use forward slashes (/) in this pathname, regardless of the convention of the underlying operating system. if this parameter is blank or null, xpisourcepath is used. returns an integer
error code. for a list of possible values, see return codes. description the patch method to update an existing component by applying a set of differences between two known versions. the set of differences is in gdiff format and is created by the nsdiff utility. a patch can only be applied between two known versions. if the existing version of the file does not match the checksum stored in the gdif...
...ible values, see return codes. description the patch method to update an existing component by applying a set of differences between two known versions. the set of differences is in gdiff format and is created by the nsdiff utility. a patch can only be applied between two known versions. if the existing version of the file does not match the checksum stored in the gdiff file, patch returns an
error without applying the patch. after patch applies a patch, it compares a checksum.of the resulting file against a checksum stored in the gdiff file. if the checksums do not match, the original version of the file is preserved, the patched version of the file is discarded, and an
error code is returned. any single installation process can apply multiple patches to the same file. if performinstall ...
Methods - Archive of obsolete content
from the xpi file to a temporary location and schedules it for later execution. gestalt retrieves information about the operating environment. (mac os only) getcomponentfolder returns an object representing the directory in which a component is installed. getfolder returns an object representing a directory, for use with the addfile method. getlast
error returns the most recent non-zero
error code. getwinprofile constructs an object for working with a windows .ini file. getwinregistry constructs an object for working with the windows registry. initinstall initializes installation for the given software and version. loadresources returns an object whose properties are localized strings...
...fied property file. logcomment add a comment line to the install log. patch applies a set of differences between two versions. performinstall finalizes the installation of the software. refreshplugins refreshes the list of plug-ins registered for the browser. registerchrome registers chrome with the chrome registry. reset
error resets a saved
error code to zero. setpackagefolder sets the default package folder that is saved with the root node. ...
XPInstall API reference - Archive of obsolete content
the new packaging scheme with an install.rdf manifest. in particular plugin developers should see how to package a plugin as an extension. ...
...ry addfile alert cancelinstall confirm deleteregisteredfile execute gestalt getcomponentfolder getfolder getlast
error getwinprofile getwinregistry initinstall loadresources logcomment patch performinstall refreshplugins registerchrome reset
error setpackagefolder installtrigger no properties methods compareversion enabled getversion install installchrome startsoftwareupdate installversion properties methods compareto init tostring file no properties methods copy dircr...
Accessing Files - Archive of obsolete content
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. accessing files this section describes how to create a file reference. retrieving a file when working with files, usage is always done via a file object and not via string paths. this allows files to used in a portable way. because string paths are not used, references to files in a file object are made relative to some starting directory. a number of starting directories may be used, for ...
... ...
Getting File Information - Archive of obsolete content
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. the nsifile object 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 exi...
...file can be executed. nsifile.ishidden() - returns true if the file is hidden. in this example, an exeception will occur if the file cannot be written to. if (!file.iswritable()) throw "file cannot be modified"; if you aren't sure whether a file can be modified, for example, you may wish to check using nsifile.iswritable() first. otherwise, an attempt to write to the file will generate an
error. the four methods above are usually sufficient for most purposes. however, you can also use the permissions (nsifile.attributes) attribute to get the unix-style permission flags for a file. this attribute is also necessary if you need to modify the permissions. file.permissions = 0640; it is common to use an octal number (a number in base 8 beginning with 0) for permissions as it can make the...
IO - Archive of obsolete content
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. files and streams this section describes how to access and get information about files, read from files and create and write files. using files a xul application or extension may access files on disk, and either read or write to files. a file is accessed via a file object. to get a reference to a file object use nsiscriptableio.getfile(). the following example will retrieve a reference to ...
...inary files, see writing to files. copying and moving files files may be moved and copied on disk. for details, see copying a file and moving a file. deleting files to learn how to delete a file, see deleting a file. open and save dialogs you can show a dialog to the user to allow them to select a file to open or enter a filename for saving. for details about this, see open and save dialogs. file
errors see file
errors for a list of
errors that might occur while using files. working with directories directories may be accessed in a similar manner using nsiscriptableio.getfile(). for instance, in the following example, a subdirectory is retrieved. if the name 'subdirname' refers to a directory, then the returned object will refer to this directory. the returned value is still a nsifile object, ...
Custom toolbar button - Archive of obsolete content
w to find the profile directory, see: profile folder explanation: the profile directory contains information specific to a user, keeping it separate from the application. if the application is reinstalled or upgraded, information in the profile is not affected. 2. in the extensions directory, create a new directory with the following name. copy the name from here and paste it, to avoid typing
errors: custom-toolbar-button@example.com perform the following steps in this new directory, creating two files and a directory there. explanation: the name is a unique identifier for the extension. there is more information about identifiers in a later section of this tutorial. 3. create a plain text file named install.rdf. copy the following content, making sure that you scroll to get all of...
...ollowed all the steps exactly. if necessary, uninstall the button and start again, this time without making any changes to the files. after you get the button working, customize the files carefully. to see the effect of any change that you make, restart the application. advanced troubleshooting if you have some technical knowledge, then you can use the application's javascript console to see
error messages. however, you might see messages that are unhelpful or confusing, or that come from other parts of the application. to open the javascript console, choose tools – web developer- browser console, and enable js. or use short cut "ctrl + shift + j" messages in the javascript console can provide information about javascript, xul or css files. note: the preference setting javascript.opti...
Creating a Window - Archive of obsolete content
the findfile.xul example let's begin by creating the basic file for the find file dialog. create a file called findfile.xul and put it in the content directory specified in the findfile.manifest file (we've created in the previous section). add the xul template shown at...
...ame,flags); where the flags contains the flag "chrome" as in this example window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300"); if you are using firefox, try below: window.open("chrome://browser/content/places/places.xul", "bmarks", "chrome,width=600,height=300"); you can test lines of javascript like these in the
error console. choose tools –
error console, type a line of javascript, and press the evaluate button, or the return or enter key. the findfile.xul example let's begin by creating the basic file for the find file dialog. create a file called findfile.xul and put it in the content directory specified in the findfile.manifest file (we've created in the previous section). add the xul template shown at the top of this page to the fil...
Creating an Installer - Archive of obsolete content
donefn() which will be called when the install is complete. you can name the function whatever you like of course. this function has two arguments. the first is the name of the package that was just installed. this is important if you are installing multiple components. the second argument is a result code. if the result is 0, the installation completed successfully. if the result is non-zero, an
error occured and the value is an
error code. the function donefn() here just displays an alert box to the user. next, we create an array xpi which will hold the name (calendar) and url (calendar.xpi) of the installer. you can add an additional similar such line for each package you wish to have installed. finally, we call the install function. when this section of script is executed, the file calend...
...he name (calendar) and url (calendar.xpi) of the installer. you can add an additional similar such line for each package you wish to have installed. finally, we call the install function. when this section of script is executed, the file calendar.xpi will be installed. our find files example let's try this with the find files dialog. function donefn ( name , result ){ if (result) alert("an
error occured: " + result); } var xpi = new object(); xpi["find files"] = "findfile.xpi"; installtrigger.install(xpi,donefn); the xpi archive note: if you want to create a new xulrunner application, extension, or theme, see bundles. the installer xpi file is required to contain one file called install.js which is a javascript file which is executed during the installation. the remaining files are...
Using Visual Studio as your XUL IDE - Archive of obsolete content
isual assist x\ find the folder that represents your visual studio version ((vanet8, vanet9, etc.) and add your extensions to the corresponding registry entries extjs and extxml. make sure that visual studio is not running, when you do this. 5. problems that need to be solved there are still some problems for which i did not find a solution yet. 5.1 localization using dtd you will get validation
errors in visual studio, if you are localizing your xul files. that has to do with the way mozilla implemented localization: < !doctype window system "chrome://loomo/locale/main.dtd"> visual studio doesn't recognize the chrome uri prefix, what will give you an
error at the previous line ("the uri prefix is not recognized"). as vs doesn't know how the chrome protocol works it can't detect where the dtd...
...xul files. that has to do with the way mozilla implemented localization: < !doctype window system "chrome://loomo/locale/main.dtd"> visual studio doesn't recognize the chrome uri prefix, what will give you an
error at the previous line ("the uri prefix is not recognized"). as vs doesn't know how the chrome protocol works it can't detect where the dtd file is really located and thus will give you
errors wherever you use the entities that are declared in this file. 5.2 text preprocessor the mozilla build system includes a text preprocessor. as preprocessor directives are not valid xml, visual studio will mark them as
errors in your xul files. 5.3 javascript related you will get validation
errors for javascript code whenever using the keywords "const" and "let". these keywords are mozilla-specifi...
XUL accessibility tool - Archive of obsolete content
m the file menu to generate a xul report for that document. be aware that the report might take a little while to be ready depending on the complexity of the application being analyzed and the speed of your machine. ...
...ort might take a little while to be ready depending on the complexity of the application being analyzed and the speed of your machine. future work the following things have been suggested or are planned for a future version of the tool: new tests: (aaronlev) warning: hardcoded color and pixel sizings (aaronlev)
error: duplicate accesskey in a dialog (already have this for menus) (aaronlev)
error: form control without accesskey (aaronlev) warning: accesskey as lowercase letter with descender (underlined g,j,y,q,p are hard to read, not recommended) (aaronandy) list of things to check manually, such as a list oftrees in the document (make sure they have accessible column picker equivs) or a list of toolbarbuttons (make sure they have accessible alternatives). new features: (aaronlev) ...
XUL Coding Style Guidelines - Archive of obsolete content
coding style guidelines to ensure our objectives are achievable. the author has collected a set of guidelines from various sources listed in the references section. while some of the guidelines are recommended practices, the others are mandatory. xml, xul, html, and xhtml guidelines the following are considered good coding style for xml/xul documents. disobeying them might not cause any parsing
error for now, however, it might cause future maintenance headache: convert html files to xul files. use the xml declaration. use namespace. case sensitivity. use chrome urls. javascript code shall be moved out of xul. dtd declaration. predefined entities. other guidelines mentioned in xhtml 1.1 recommendation. see details here. making xul localizable -- mandatory in the past, ui (display) related ...
...ource descriptions are stored in *.rc (for windows client) or *.ad (for unix client) so that they can be localized for a specific language or culture. in the new world, mozilla 5.0, this is not true any more. most of the windows and dialogs in mozilla will be described using xul. to make xul stream/file localizable, several guidelines are to be adopted to make the translation work easier and less
error-prone. the issues are discussed in details here: what is localizable? widget resources content data style info layout geometry how to make them localizable? localization notes localization notes are the xul writers' notes to the localizers/translators. they are placed above the actual entity string in the format: <!-- localization note (entity.name): content --> where the <var>entity.name<...
image - Archive of obsolete content
src attribute can be used to specify the url of the image. more information is available in the xul tutorial. note: prior to gecko 8.0, images did not shrink down with the same ratio in both directions when specifying maximum sizes using maxheight or maxwidth. the new behavior aligns more with the html <img> element and shrinks both the width and height down proportionally. attributes on
error, onload, src, validate properties accessibletype, src style classes alert-icon,
error-icon, message-icon, question-icon examples <image src='firefoxlogo.png' width='135' height='130'/> attributes on
error type: script code this event is sent to an image element when an
error occurs loading the image. image.onload type: script code this event handler will be calle...
...e(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes alert-icon class that adds an alert icon. this typically looks like an exclamation mark. this and the other icon classes may be used by image elements or other elements which can have an image.
error-icon class that adds an
error icon. this will typically be a red "x" icon. message-icon class that adds a message box icon. question-icon class that adds a question icon, which usually looks like a question mark. related see also the image and icon attributes. interfaces nsiaccessibleprovider nsidomxulimageelement ...
Using LDAP XPCOM with XULRunner - Archive of obsolete content
[] = moz_dll_prefix "mozldap" moz_dll_suffix; nsresult nsgetmodule(nsicomponentmanager* acompmgr, nsifile* alocation, nsimodule* *aresult) { nsresult rv; nscomptr<nsifile> libraries; rv = alocation->getparent(getter_addrefs(libraries)); if (ns_failed(rv)) return rv; nscomptr<nsilocalfile> library(do_queryinterface(libraries)); if (!library) return ns_
error_unexpected; library->setnativeleafname(ns_literal_cstring("libraries")); library->appendnative(ns_literal_cstring("dummy")); // loop through and load dependent libraries for (char const *const *dependent = kdependentlibraries; *dependent; ++dependent) { library->setnativeleafname(nsdependentcstring(*dependent)); prlibrary *lib; library->load(&lib); // 1) we...
...'t care if this failed! // 2) we are going to leak this library. we don't care about that either. } library->setnativeleafname(ns_literal_cstring(krealcomponent)); prlibrary *lib; rv = library->load(&lib); if (ns_failed(rv)) return rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_
error_failure; return getmoduleproc(acompmgr, alocation, aresult); } then change your .mozconfig to add this line: ac_add_options --enable-extensions=ldapstub rebuild xulrunner. this will create a new file in the components subdirectory of the built package, mozldap_stub.dll (on windows) or libmozldap_stub.so (on linux). copy mozldap.xpt and mozldap_stub.dll into your components xul app subdirect...
XUL Explorer - Archive of obsolete content
xul explorer is a xulrunner application that provides an easy way to experiment with xul. it’s a simple editor that can preview xul inline or in a separate popup window. it has a list of code snippets (small fragments of xul or javascript) that can be quickly inserted into the editor. the xul can be loaded from and saved to files. a xul validator and the
error console are both available to help debug problems. ...
...rror console are both available to help debug problems. the help menu provides access to xul information on mdc. there is even simple “keyword” help lookup for xul elements. roadmap features: the preview pane can be toggled with the editor. previewing in a popup window is still available. option to automatically update the preview as the editor changes. indicator in the statusbar shows
errors. double-click to display
error console. option to specify the snippet used to load the editor on startup. option to include a user snippet file. the snippets are merged with the built-in snippets at startup. double-click or drag-and-drop to insert a snippet file > new allows user to pick any “template” snippet, as well as blank. simple xul checker can be used to ‘validate’ the xul s...
Archived Mozilla and build documentation - Archive of obsolete content
on solaris 10 and mac os x 10.5. embedding faq embedding mozilla in a java application using javaxpcom xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects. as you will see in this article, working with xpcom objects in java is not that much different than doing so in c++.
error console 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. ...
...orer xul explorer is a xulrunner application that provides an easy way to experiment with xul. it’s a simple editor that can preview xul inline or in a separate popup window. it has a list of code snippets (small fragments of xul or javascript) that can be quickly inserted into the editor. the xul can be loaded from and saved to files. a xul validator and the
error console are both available to help debug problems. the help menu provides access to xul information on mdc. there is even simple “keyword” help lookup for xul elements. xulrunner xulrunner is a mozilla runtime package that can be used to bootstrap xul+xpcom applications that are as rich as firefox and thunderbird. it provides mechanisms for installi...
NPN_GetAuthenticationInfo - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary the function is called by plugins to get http authentication information from the browser. ...
... password out parameter. the browser passes back the http password. if the function succeed, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the password may have internal null bytes and may not be null-terminated. plen out parameter. the length of the returned password buffer. returns if successful, the function returns nperr_no_
error. if unsuccessful, the function returns an
error code. for possible values, see
error codes. description plugin which implement their own http networking stack (such as the java plugin) may want to use the standard http auth prompts and password managed of the browser. this function allows the plugin to ask the browser for http authentication information for a domain. unless the plugin has specia...
NPN_GetURL - Archive of obsolete content
url pointer to the url of the request. can be of any type, such as http, ftp, news, or mailto. target name of the target window or frame, or one of the following special target names. ...
... instance's document is already at the top. use for breaking out of a deep frame nesting. if the target is null, the browser creates a new stream and delivers the data to the current instance regardless of the mime type of the url. in general, if a url works in the location box of the browser, it works here, except for the _self target. 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_geturl() is used to load a url into the current window or another target or stream. plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the network. this is especially useful for enabling an existing ...
NPN_GetURLNotify - Archive of obsolete content
url pointer to the url of the request. ...
... of the request. can be of any type, such as http, ftp, news, or mailto. target name of the target window or frame, or one of several special target names. for values, see npn_geturl(). notifydata plug-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_GetValueForURL - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary provides information to a plugin which is associated with a given url, for example the cookies or preferred proxy. syntax #include <npapi.h> typedef enum { npnurlvcookie = 501, npnurlvproxy } npnurlvariable; np
error npn_getvalueforurl(npp instance, npnurlvariable variable, const char *url, char **value, uint32_t *len); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable selects the type of information to be retrieved (npnurlvcookie or npnurlvproxy) url the url for which to fetch information. value out parameter. the browser passes back the reques...
...with npn_memalloc; the plugin is responsible for freeing the buffer. note: the value may have internal null bytes and may not be null-terminated. when multiple cookies are returned for a given url, the format of the return value is: cookie1=value1;cookie2=value2;cookie3=value3 len out parameter. the length of the returned value buffer. returns if successful, the function returns nperr_no_
error. if unsuccessful, the function returns an
error code. for possible values, see
error codes. description this entry point is designed to allow plugins which implement their own http stacks to form requests to the web server in the same way the browser does. see also npn_setvalueforurl, npn_getauthenticationinfo ...
NPN NewStream - Archive of obsolete content
summary requests the creation of a new data stream produced by the plug-in and consumed by the browser. syntax #include <npapi.h> np
error npn_newstream(npp instance, npmimetype type, const char* target, npstream** stream); parameters the function has the following parameters: instance pointer to current plug-in instance. type mime type of the stream. target name of the target window or frame, or one of several special target names. for values, see npn_geturl. stream stream to be created by the browser. 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_newst...
... see also npp_newstream, npp_write, npp_destroystream, npstream, npp ...
NPN_PostURL - Archive of obsolete content
url url of the request, specified by the plug-in. target display target, specified by the plug-in. if null, pass the new stream back to the current plug-in instance regardless of mime type. for values, see npn_geturl. ...
...ns the data to post. temporary file is deleted after use. data in buffer cannot be posted for a protocol that requires a header. file a boolean value that specifies whether to post a file. values: true: post the file whose path is specified in buf, then delete the file. false: post the raw data in buf. returns if successful, the function returns nperr_no_
error. if unsuccessful, the plug-in is not loaded and the function returns an
error code. for possible values, see
error codes. description npn_posturl works similarly to npn_geturl, but in reverse. npn_geturl reads data from the url and either displays it in the target window or delivers it to the plug-in. npn_posturl writes data from a file or buffer to the url and either displays the server'...
NPN_RequestRead - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary 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(). syntax #include <npapi.h> np
error npn_requestread(npstream* stream, npbyterange* rangelist); parameters the function has the following parameters: stream stream of type np_seek from which to read bytes. rangelist range of bytes in the form of a linked list of npbyterange objects, each of which specifies a request for a range of bytes. returns if successful, the function returns nperr_no_
error. if unsuccessful, the function returns an
error code. for possible values, see
error codes. description for a...
...s inherently seekable; npn_requestread() automatically changes the mode to np_seek. if the stream is not inherently seekable, the stream must have been put in np_seek mode initially (since the browser must cache all the stream data on disk in order to access it randomly). if npn_requestread() is called on a stream that is not inherently seekable and not initially in mode np_seek, it returns the
error code nperr_stream_not_seekable. typically, the only streams that are inherently seekable are those from in-memory or on-disk data, or from http servers that support byte-range requests. see also npp_newstream() npp_writeready() npp_write() npstream ...
NPN_SetValueForURL - Archive of obsolete content
plug-in api summary allows a plugin to change the stored information associated with a url, in particular its cookies. (while the api theoretically allows the preferred proxy for a given url to be changed, doing so does not have much meaning given how proxies are configured, and is not supported.) syntax #include <npapi.h> typedef enum { npnurlvcookie = 501, npnurlvproxy } npnurlvariable; np
error npn_setvalueforurl(npp instance, npnurlvariable variable, const char *url, const char *value, uint32_t len); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable selects the type of information to be changed. the only support...
... the current plug-in instance. variable selects the type of information to be changed. the only supported type is npnurlvcookie. url the url for which to change information. value the new associated information for the url. note: the value may have internal null bytes and may not be null-terminated. len the length of the value buffer. returns if successful, the function returns nperr_no_
error. if unsuccessful, the function returns an
error code. for possible values, see
error codes. description this entry point is designed to allow plugins to affect the cookies sent by the browser back to the server. see also npn_getvalueforurl, npn_getauthenticationinfo ...
NPN_Write - Archive of obsolete content
to a buffer of data to deliver to the stream. returns if successful, the function returns a positive integer representing the number of bytes written (consumed by the browser). this number depends on the size of the browser's memory buffers, the number of active streams, and other factors. if unsuccessful, the plug-in returns a negative integer. this indicates that the browser encountered an
error while processing the data, so the plug-in should terminate the stream by calling npn_destroystream(). description npn_write() delivers a buffer from the stream to the instance. a plug-in can call this function multiple times after creating a stream with npn_newstream(). the browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method returns, if desired. see ...
...mes after creating a stream with npn_newstream(). the browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method returns, if desired. see "example of sending a stream" for an example that includes npn_write(). example this example pushes a snippet of html over a newly created stream, then destroys the stream when it's done. note: you should actually handle
errors, which this example doesn't do. npstream* stream; char* mydata = "<html><b>this is a message from my plug-in!</b></html>"; int32 mylength = strlen(mydata) + 1; /* create the stream. */ err = npn_newstream(instance, "text/html", "_blank", &stream) /* push data into the stream. */ err = npn_write(instance, stream, mylength, mydata); /* delete the stream. */ err = npn_destroystre...
NPP_DestroyStream - Archive of obsolete content
stream pointer to current stream. reason reason the stream was destroyed. values: npres_done (most common): completed normally; all data was sent to the instance. ...
... all data was sent to the instance. npres_user_break: user canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. npres_network_err: stream failed due to problems with network, disk i/o, lack of memory, or other problems. returns if successful, the plug-in should return nperr_no_
error. if unsuccessful, the plug-in should return an
error code. for possible values, see
error codes. description the browser calls the npp_destroystream function when a data stream sent to the plug-in is finished, either because it has completed successfully or terminated abnormally. after this, the browser deletes the npstream object. you should delete any private data allocated in stream->pdat...
NPP_New - Archive of obsolete content
instance contains instance-specific private data for the plug-in and the browser. this data is stored in instance->pdata. mode display mode of plug-in. ...
... values passed to the plug-in from the embed tag. saved pointer to data saved by npp_destroy for a previous instance of this plug-in at the same url. if non-null, the browser passes ownership of the npsaveddata object back to the plug-in. the plug-in is responsible for freeing the memory for the npsaveddata and the buffer it contains. returns if successful, the function returns nperr_no_
error. if unsuccessful, the function returns an
error code. for possible values, see
error codes. description npp_new creates a new instance of a plug-in. it is called after np_initialize and is passed the mime type, embedded or full-screen display mode, and, for embedded plug-ins, information about html embed arguments. a new instance pointer (npp instance) is created by the plug-in, which is val...
NPP_NewStream - Archive of obsolete content
type pointer to mime type of the stream. stream pointer to new stream. seekable boolean indicating whether the stream is seekable: true: seekable. ...
...vered to the plug-in as it is saved to the file (as in mode np_normal). np_seek: stream data randomly accessible by the plug-in as needed, through calls to npn_requestread. implementation note: some plugins, notably silverlight, do not set this outparam, and rely on the outparam being initialized to a default np_normal value. returns if successful, the function should return nperr_no_
error. if unsuccessful, the function should return one of the np
error error codes. this will cause the browser to destroy the stream without calling npp_destroystream. description npp_newstream notifies the plug-in when a new stream is created. the npstream* pointer is valid until the stream is destroyed. the plug-in can store plug-in-private data associated with the stream in stream->pdata. the m...
NPP_StreamAsFile - Archive of obsolete content
cal file name for the data from a stream. syntax #include <npapi.h> void npp_streamasfile(npp instance, npstream* stream, const char* fname); parameters the function has the following parameters: instance pointer to current plug-in instance. stream pointer to current stream. fname pointer to full path to a local file. ...
...ath to a local file. if an
error occurs while retrieving the data or writing the file, fname may be null. description when the stream is complete, the browser calls npp_streamasfile to provide the instance with a full path name for a local file for the stream. npp_streamasfile is called for streams whose mode is set to np_asfileonly or np_asfile only in a previous call to npp_newstream. if an
error occurs while retrieving the data or writing the file, the file name (fname) is null. see also npp_newstream, npp_write, npp_writeready, npstream, npp ...
NP_GetValue - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary allows the browser to query the plug-in for information. syntax #include <npapi.h> np
error np_getvalue(void *instance, nppvariable variable, void *value); parameters the function has the following parameters: instance pointer to the current plug-in instance. instance parameter is null because no instance has been created. variable plug-in information the call gets. ...
...er to the current plug-in instance. instance parameter is null because no instance has been created. variable plug-in information the call gets. values: nppvpluginnamestring: gets the name of the plug-in nppvplugindescriptionstring: gets the description string of the plug-in value plug-in name, returned by the function. returns if successful, the function returns nperr_no_
error. if unsuccessful, the function returns an
error code. for possible values, see
error codes. description none. see also npp_setvalue ...
SAX - Archive of obsolete content
handlers receive a series of callbacks for the content of xml being parsed. the following handlers are available: interface purpose nsisaxcontenthandler receive notification of the logical content of a document (e.g. elements, attributes, whitespace, and processing instructions). nsisaxdtdhandler receive notification of basic dtd-related events. nsisax
errorhandler receive notification of
errors in the input stream. nsisaxlexicalhandler sax2 extension handler for lexical events (e.g. comment and cdata nodes, dtd declarations, and entities). an example implementation of the most commonly used content handler: function print(s) { dump(s + "\n"); } xmlreader.contenthandler = { // nsisaxcontenthandler startdocument: function...
...below is an example of parsing from a string: xmlreader.parsefromstring("<f:a xmlns:f='g' d='1'><bbq/></f:a>", "text/xml"); this call results in the following output (assuming the content handler from the example ...
.htaccess ( hypertext access ) - Archive of obsolete content
include statements in the file; you can have them automatically attached to all the files, whether at top or bottom, automatically through your .htaccess file. ...
... all the files, whether at top or bottom, automatically through your .htaccess file. php_value auto_prepend_file "/real/path/to/file/functions.php" # adds function.php at the top of requested document php_value auto_append_file "/real/path/to/file/footer.php" # adds footer.html at bottom of requested document customized
error responses : user can be directed to different pages depending on the
error they caused or by the webserver.
errordocument 404 /notfound.html # redirects traffic to notfound.html in case of a 404
error errordocument 500 /serverr.html # redirects traffic to serverr.html in case of a 500 internal server
error for further information see this external article: redirect your traffic for
error handling. cache control : .htaccess allows a server to control caching by web ...
Threats - Archive of obsolete content
lve intentional actors (e.g., attacker who wants to access information on a server) or unintentional actors (e.g., administrator who forgets to disable user accounts of a former employee.) threats can be local, such as a disgruntled employee, or remote, such as an attacker in another geographical area. a threat source is the cause of a threat, such as a hostile cyber or physical attack, a human
error of omission or commission, a failure of organization-controlled hardware or software, or other failure beyond the control of the organization. a threat event is an event or situation initiated or caused by a threat source that has the potential for causing adverse impact. many threats against data and resources are possible because of mistakes—either bugs in operating system and applications t...
...ganization-controlled hardware or software, or other failure beyond the control of the organization. a threat event is an event or situation initiated or caused by a threat source that has the potential for causing adverse impact. many threats against data and resources are possible because of mistakes—either bugs in operating system and applications that create exploitable vulnerabilities, or
errors made by end users and administrators. network traffic typically passes through intermediate computers, such as routers, or is carried over unsecured networks, such as wireless hotspots. because of this, it can be intercepted by a third party. threats against network traffic include the following: eavesdropping. information remains intact, but its privacy is compromised. for example, someon...
Common Firefox theme issues and solutions - Archive of obsolete content
ozilla's mission page. warning: if you copy over the firefox 11 or newer style rules and graphics from the media folder in omni.ja you need to make the following changes in videocontrols.css or the pause and mute buttons will break in firefox 10. change the style rules: .playbutton[paused] {...} .mutebutton[muted] {...} to: .playbutton[paused="true"] {...} .mutebutton[muted="true"] {...}
error console warnings unknown namespace for videocontrols.css the
error console is reporting the following issue: warning: unknown namespace prefix 'html'. ruleset ignored due to bad selector. source file: chrome://global/skin/media/videocontrols.css the solution to this issue is to add the following name space to the second line of the file right after, and in addition to, the existing @namespac...
...s reporting the following issue: warning: unknown namespace prefix 'html'. ruleset ignored due to bad selector. source file: chrome://global/skin/media/videocontrols.css the solution to this issue is to add the following name space to the second line of the file right after, and in addition to, the existing @namespace: @namespace html url("http://www.w3.org/1999/xhtml"); you can generate the
error console message by going to mozilla's mission page. if you are using the extension console² you can easily filter out content related messages to see just chrome issues. warning: unknown property (obsolete css rules) -moz-border-radius firefox no longer supports -moz-border-radius style properties. use css standard border-radius properties instead (supported by firefox since firefox 4). -moz...
Developing cross-browser and cross-platform pages - Archive of obsolete content
an important practice when doing cross-browser, cross-platform pages and dhtml development involves the ability to determine the capabilities of the browser which loads your web page. as a web author, you understandably want to avoid script
errors and page layout problems and you may want to ensure your scripts reach as wide an audience as possible. there are 2 known approaches for such goals: the browser identification approach (also known as useragent string detection and often referred as "browser sniffing") and the object/feature support detection approach. the browser identification approach is now known to be complicated, unreliable and difficult to maintain. browser identification approach (aka "browser sniffing"): not best, not reliable approach this approach, still commonly u...
...hod called getelementbyid on the document object, which is the one of the most basic levels of support for the dom in a browser. if there is, the code sees if document.getelementbyid(id_attribute_value) returns a reference to an existing element, which it then checks for a style object. if the style object exists on the element, then it sets that object's visibility property. the browser will not
error if you set this unimplemented property, so you do not need to check that the visiblity property itself exists. so, instead of needing to know which browsers and browser versions support a particular dom method (or dom attribute or dom feature), you can verify the support for that particular method in the visiting browser. with this approach, you ensure that all browsers -- including future relea...
Browser Feature Detection - Archive of obsolete content
cellspacing="0">'); for (i = 0; i < features.length; i++) { if (features[i].supported) document.write('<tr><td>' + features[i].name + '<\/td><td>' + features[i].supported + '<\/td><\/tr>'); else document.write('<tr><td>' + features[i].name + '<\/td><td style="background-color:red">' + features[i].supported + '<\/td><\/tr>'); } document.write('<\/table>'); } var oldon
error = window.on
error; // suppress
error messages... window.on
error = null; document.write('<p><b> your browser ' + navigator.useragent + '<\/b><\/p>'); generatereport(document, 'domcore1', 'document'); generatereport(document, 'domcore2', 'document'); generatereport(document, 'domhtml', 'document'); generatereport(document.body.style, 'domcss1', 'document.body.style'); generatereport(document...
...
error = null; document.write('<p><b> your browser ' + navigator.useragent + '<\/b><\/p>'); generatereport(document, 'domcore1', 'document'); generatereport(document, 'domcore2', 'document'); generatereport(document, 'domhtml', 'document'); generatereport(document.body.style, 'domcss1', 'document.body.style'); generatereport(document.body.style, 'domcss2', 'document.body.style'); window.on
error = oldon
error; see also browser detection and cross browser support comparison of layout engines web specifications supported in opera 9 what's new in internet explorer 7 (script) original document information author(s): (unknown) last updated date: updated march 16, 2003 copyright information: copyright © 2001-2003 netscape. note: this reprinted article was originally part of the...
E4X - Archive of obsolete content
ype "text/javascript;e4x=1" (i.e., have an attribute of the form type="text/javascript;e4x=1"). ...
...ich leads to a js syntax
error in html since html's <script> element produces an implicit cdata section, and therefore cannot contain explicit cdata sections). someone verify the above known bugs and limitations it is not currently possible to access a dom object through e4x (bug 270553). e4x doesn't support parsing xml declaration. <?xml version=...?>) (see bug 336551). you may get syntax
error "xml is a reserved identifier" (despite the xml being in a string). workaround: var response = xmlhttprequest.responsetext; // bug 270553 response = response.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, ""); // bug 336551 var e4x = new xml(response); resources e4x tutorial processing xml with e4x on mdc e4x for templating see the list of e4x-related pages on mdc ecma-357 s...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
if not specified, debug.ms_async_op_status_success is used. remarks call this function when the asynchronous operation completes. asyncoperationid must correspond to the operation id previously returned from debug.mstraceasyncoperationstarting. the possible values for status include: debug.ms_async_op_status_success debug.ms_async_op_status_canceled debug.ms_async_op_status_
error note: some debugging tools do not display the information sent to the debugger. example the following code provides an example of tracing an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, de...
... an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of async operation. }, function (
error) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_
error); debug.mstraceasynccallbackstarting(opid); }); debug.mstraceasynccallbackcompleted(); } function dosomethingasync() { return winjs.promise.as(true); } asyncwrapperfunction(); requirements supported in the internet explorer 11 standards document mode. also supported in store apps (window...
Debug - Archive of obsolete content
ion. 0 debug.ms_async_callback_status_join the synchronous work item satisfied part of a join asynchronous operation. 1 debug.ms_async_callback_status_chooseany the synchronous work item satisfied a choice asynchronous operation. 2 debug.ms_async_callback_status_cancel the synchronous work item was canceled. ...
...atus_join the synchronous work item satisfied part of a join asynchronous operation. 1 debug.ms_async_callback_status_chooseany the synchronous work item satisfied a choice asynchronous operation. 2 debug.ms_async_callback_status_cancel the synchronous work item was canceled. 3 debug.ms_async_callback_status_
error the synchronous work item caused an
error in an asynchronous operation. 4 async operation status codes contant description value debug.ms_async_op_status_success the asynchronous operation was successful. 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 ...
GetObject - Archive of obsolete content
when this code is executed, the application associated with the specified pathname is started, and the object in the specified file is activated. if pathname is a zero-length string (""), getobject returns a new object instance of the specified type. if the pathnameargument is omitted, getobject returns a currently active object of the specified type. if no object of the specified type exists, an
error occurs. some applications allow you to activate part of a file. to do so, add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. for information on how to create this string, see the documentation for the application that created the object. for example, in a drawing application you might have multiple laye...
...ance, and you don't want the object started with a file loaded, use the activexobject object. if an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times activexobject is executed. with a single-instance object, getobject always returns the same instance when called with the zero-length string ("") syntax, and it causes an
error if the pathname argument is omitted. requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, and internet explorer 8 standards. ...
Object.prototype.watch() - Archive of obsolete content
d 200. ...
...atch('name', this._isvalidassignment.bind(this)); this.name = name; this.age = age; } tostring() { return this.name + ', ' + this.age; } _isvalidassignment(id, oldval, newval) { if (id === 'name' && (!newval || newval.length > 30)) { throw new range
error('invalid name for ' + this); } if (id === 'age' && (newval < 0 || newval > 200)) { throw new range
error('invalid age for ' + this); } return newval; } } const will = new person('will', 29); console.log(will); // will, 29 try { will.name = ''; } catch (e) { console.log(e); } try { will.age = -4; } catch (e) { console.log(e); } this script displays the following: will, 29 range
error: invalid name for will, 29 range
error: invalid age for will, 29 specifications not part of...
handler.enumerate() - Archive of obsolete content
is is bound to the handler. target the target object. return value an iterator object. description the handler.enumerate method is a trap for for...in statements. interceptions this trap can intercept these operations: property enumeration / for...in: for (var name in proxy) {...} reflect.enumerate() invariants if the following invariants are violated, the proxy will throw a type
error: the enumerate method must return an object. examples the following code traps for...in statements. var p = new proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" the following code violates the invariant. var p = ...
...r...in statements. var p = new proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" the following code violates the invariant. var p = new proxy({}, { enumerate(target) { return 1; } }); for (var x in p) {} // type
error is thrown note: both examples make use of the shorthand syntax for method definitions. specifications not part of any standard. ...
JSException - Archive of obsolete content
extends runtimeexception java.lang.object | +----java.lang.throwable | +----java.lang.exception | +----java.lang.runtimeexception | +----netscape.javascript.jsexception description jsexception is an exception which is thrown when javascript code returns an
error. constructor summary the netscape.javascript.jsexception class has the following constructors: jsexception deprecated constructors optionally let you specify a detail message and other information. method summary the netscape.javascript.jsexception class has the following methods: getwrappedexception instance method getwrappedexception. getwrappedexceptiontype instance method...
...as not available. jsexception constructors, deprecated in javascript 1.4, constructs a jsexception object with an optional detail message. declaration 1. public jsexception() 2. public jsexception(string s) 3. public jsexception(string s, string filename, int lineno, string source, int tokenindex) arguments s the detail message. filename the url of the file where the
error occurred, if possible. lineno the line number of the file, if possible. source the string containing the javascript code being evaluated. tokenindex the index into the source string where the
error occurred. getwrappedexception instance method getwrappedexception. declaration public object getwrappedexception() description getwrappedexception() returns an object that rep...
Examples - Archive of obsolete content
ing of the code). ideally, upload the file to a web server and you're done. please note that the examples 4, 5 and 6 require a file named style.css to exist in the same directory as the example. you can get the contents of style.css at the bottom of this page. examples for "problems with inline style and script" problem 1 <!-- this file should have a .xhtml extension and will generate an
error when parsed. --> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us"> <head> <title>problem 1 - < in xhtml</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /> <script type="text/javascript"> var i = 0; while (...
...--> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us"> <head> <title>problem 3 - comments in xml</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /> <script type="text/javascript"> var i; var sum = ...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
by making the content of each card 45% the width of the containing element, and adding 2% margin to both the left and right sides, each card's element box is 49% as wide as the parent. two of them side by side will take up 98% the width of the parent element. this leaves out 2% as "wasted space," so to speak. ...
...the layout wasn't bad if the fish weren't laid out next to each other, so i moved on. floating fish with the cards set up to float, the next step was to place the images appropriately. this involved floating the image inside the floated div. it just seemed like a fish cam page should have a lot of floating for some reason. ...
UDP (User Datagram Protocol) - MDN Web Docs Glossary: Definitions of Web-related terms
ctionless communication model with a minimum of protocol mechanism. udp provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram. it has no handshaking dialogues, and thus exposes the user's program to any unreliability of the underlying network; there is no guarantee of delivery, ordering, or duplicate protection. ...
...poses the user's program to any unreliability of the underlying network; there is no guarantee of delivery, ordering, or duplicate protection. if
error-correction facilities are needed at the network interface level, an application may use the transmission control protocol (tcp) or stream control transmission protocol (sctp) which are designed for this purpose. udp is suitable for purposes where
error checking and correction are either not necessary or are performed in the application; udp avoids the overhead of such processing in the protocol stack. time-sensitive applications often use udp because dropping packets is preferable to waiting for packets delayed due to retransmission, which may not be an option in a real-time system. general knowledge user datagram protocol on wikipedia te...
What is accessibility? - Learn web development
notes designing with cognitive accessibility will lead to good design practices. they will benefit everyone. many people with cognitive impairments also have physical disabilities. websites must conform with the w3c’s web content accessibility guidelines, including cognitive accessibility guidelines. the w3c’s cognitive and learning disabilities acce...
...ssary content or advertisements; consistent webpage layout and navigation; familiar elements, such as underlined links blue when not visited and purple when visited; dividing processes into logical, essential steps with progress indicators; website authentication as easy as possible without compromising security; and making forms easy to complete, such as with clear
error messages and simple
error recovery. notes designing with cognitive accessibility will lead to good design practices. they will benefit everyone. many people with cognitive impairments also have physical disabilities. websites must conform with the w3c’s web content accessibility guidelines, including cognitive accessibility guidelines. the w3c’s cognitive and learning disabilities accessibility task force produ...
Debugging CSS - Learn web development
this lesson see the how to guides. debugging problems in css devtools can be a great help when solving css problems, so when you find yourself in a situation where css isn't behaving as you expect, how should you go about solving it? the following steps should help. take a step back from the problem any coding problem can be frustrating, especially css problems because you often don't get an
error message to search for online to help with finding a solution. if you are becoming frustrated, take a step away from the issue for a while — go for a walk, grab a drink, chat to a co-worker, or work on some other thing for a while. sometimes the solution magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier. do you ...
... or work on some other thing for a while. sometimes the solution magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier. do you have valid html and css? browsers expect your css and html to be correctly written, however browsers are also very forgiving and will try their best to display your webpages even if you have
errors in the markup or stylesheet. if you have mistakes in your code the browser needs to make a guess at what you meant, and it might make a different decision to what you had in mind. in addition, two different browsers might cope with the problem in two different ways. a good first step therefore is to run your html and css through a validator, to pick up and fix any
errors. css validator html ...
How CSS works - Learn web development
at browsers can recognise, you might wonder what happens if a browser encounters a css selector or declaration it doesn't recognise. the answer is that it does nothing, and just moves on to the next bit of css! if a browser is parsing your rules, and encounters a property or value that it doesn't understand, it ignores it and moves on to the next declaration. it will do this if you have made an
error and misspelled a property or value, or if the property or value is just too new and the browser doesn't yet support it. similarly, if a browser encounters a selector that it doesn't understand, it will just ignore the whole rule and move on to the next one. in the example below i have used the british english spelling for color, which makes that property invalid as it is not recognised. so my p...
...nised. so my paragraph has not been colored blue. all of the other css have been applied however; only the invalid line is ignored. <p> i want this text to be large, bold and blue.</p> p { font-weight: bold; colour: blue; /* incorrect spelling of the color property */ font-size: 200%; } this behavior is very useful. it means that you can use new css as an enhancement, knowing that no
error will occur if it is not understood — the browser will either get the new feature or not. coupled with the way that the cascade works, and the fact that browsers will use the last css they come across in a stylesheet when you have two rules with the same specificity you can also offer alternatives for browsers that don't support new css. this works particularly well when you want to use a value...
Test your skills: Form validation - Learn web development
e browser apply some more specific validation suitable for the data being asked for. give the "user name" field a required length of between 5 and 20 characters, the "phone number" field a maximum length of 15 characters, and the "comment" field a maximum length of 200 characters. try submitting your form — it should refuse to submit until the above constaints are followed, and give suitable
error messages. to help, you might want to consider adding some simple css to show when a form field is valid or invalid. download the starting point for this task to work in your own editor or in an online editor. form validation 2 now we want you to take the same form you saw in the previous task (use your previous answer if you want to), and add some more specific pattern validation to the firs...
...valid. download the starting point for this task to work in your own editor or in an online editor. form validation 3 in our final task for this set, we are providing you with a similar example to what you saw in the accompanying article — a simple email address entry input. we would like you to use the constraint validation api, plus some form validation attributes, to program some custom
error messages. make the input mandatory to fill in, and give it a minimum length of 10 characters. add an event listener that checks whether the inputted value is an email address, and whether it is long enough. if it doesn't look like an email address or is too short, provide the user with appropriate custom
error messages. download the starting point for this task to work in your own editor o...
HTML basics - Learn web development
ening and closing angle brackets. this states where the element begins or starts to take effect — in this case where the paragraph begins. the closing tag: this is the same as the opening tag, except that it includes a forward slash before the element name. this states where the element ends — in this case where the paragraph ends. failing to add a closing tag is one of the standard beginner
errors and can lead to strange results. the content: this is the content of the element, which in this case, is just text. the element: the opening tag, the closing tag and the content together comprise the element. elements can also have attributes that look like the following: attributes contain extra information about the element that you don't want to appear in the actual content. here, clas...
...e</title> </head> <body> <img src="images/firefox-icon.png" alt="my test image"> </body> </html> here, we have the following: <!doctype html> — the doctype. it is required preamble. in the mists of time, when html was young (around 1991/92), doctypes were meant to act as links to a set of rules that the html page had to follow to be considered good html, which could mean automatic
error checking and other useful things. however these days, they don't do much, and are basically just needed to make sure your document behaves correctly. that's all you need to know for now. <html></html> — the <html> element. this element wraps all the content on the entire page and is sometimes known as the root element. <head></head> — the <head> element. this element acts as a container for...
Tips for authoring fast-loading HTML pages - Learn web development
rather than the older approaches based on document.write(). use modern css and valid markup use of modern css reduces the amount of markup, can reduce the need for (spacer) images, in terms of layout, and can very often replace images of stylized text -- that "cost" much more than the equivalent text-and-css. using valid markup has other advantages. first, browsers will have no need to perform
error-correction when parsing the html (this is aside from the philosophical issue of whether to allow format variation in user input and then programmatically "correct" or normalize it; or whether, instead, to enforce a strict, no-tolerance input format). moreover, valid markup allows for the free use of other tools which can pre-process your web pages. for example, html tidy can remove whitespace an...
...her to allow format variation in user input and then programmatically "correct" or normalize it; or whether, instead, to enforce a strict, no-tolerance input format). moreover, valid markup allows for the free use of other tools which can pre-process your web pages. for example, html tidy can remove whitespace and optional ending tags; however, it will refuse to run on a page with serious markup
errors. chunk your content tables for layouts are a legacy method that should not be used anymore. layouts utilizing floats, positioning, flexbox, or grids should be used instead. tables are still considered valid markup but should be used for displaying tabular data. to help the browser render your page quicker, you should avoid nesting your tables. rather than deeply nesting tables as in: <table...
Getting started with HTML - Learn web development
nt begins or starts to take effect. in this example, it precedes the start of the paragraph text. the content: this is the content of the element. in this example, it is the paragraph text. the closing tag: this is the same as the opening tag, except that it includes a forward slash before the element name. this marks where the element ends. failing to include a closing tag is a common beginner
error that can produce peculiar results. the element is the opening tag, followed by content, followed by the closing tag. active learning: creating your first html element edit the line below in the input area by wrapping it with the tags <em> and </em>. to open the element, put the opening tag <em> at the start of the line. to close the element, put the closing tag </em> at the end of the line. d...
..., as soon as we add the title attribute in this way, there are problems: <a href=https://www.mozilla.org/ title=the mozilla homepage>favorite website</a> as written above, the browser misinterprets the markup, mistaking the title attribute for three attributes: a title attribute with the value the, and two boolean attributes, mozilla and homepage. obviously, this is not intended! it will cause
errors or unexpected behavior, as you can see in the live example below. try hovering over the link to view the title text! always include the attribute quotes. it avoids such problems, and results in more readable code. single or double quotes? in this article you will also notice that the attributes are wrapped in double quotes. however, you might see single quotes in some html code. this is a m...
Choosing the right approach - Learn web development
(blob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); } loadasset('coffee.jpg', 'blob', displayimage); pitfalls nested callbacks can be cumbersome and hard to read (i.e. "callback hell"). failure callbacks need to be called once for each level of nesting, whereas with promises you can just use a single .catch() block to handle the
errors for the entire chain. async callbacks just aren't very graceful. promise callbacks are always called in the strict order they are placed in the event queue; async callbacks aren't. async callbacks lose full control of how the function will be executed when passed to a third-party library. browser compatibility really good general support, although the exact support for callbacks in apis de...
...t to run in. let's say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds. when your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive settimeout() — this will keep the time interval constant between executions regardless of how long the code takes to execute, and you won't get
errors. browser compatibility desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetsettimeoutchrome full support 30edge full support 12firefox full support 1 ...
General asynchronous programming concepts - Learn web development
when a function relies on the results of multiple previous processes to function. consider the following thread diagrams: main thread: task a --> task b in this case, let's say task a is doing something like fetching an image from the server and task b then does something to the image like applying a filter to it. if you start task a running and then immediately try to run task b, you'll get an
error, because the image won't be available yet. main thread: task a --> task b --> |task d| worker thread: task c -----------> | | in this case, let's say task d makes use of the results of both task b and task c. if we can guarantee that these results will both be available at the same time, then we might be ok, but this is unlikely. if task d tries to run when one of its inputs is not yet a...
...e available yet. main thread: task a --> task b --> |task d| worker thread: task c -----------> | | in this case, let's say task d makes use of the results of both task b and task c. if we can guarantee that these results will both be available at the same time, then we might be ok, but this is unlikely. if task d tries to run when one of its inputs is not yet available, it will throw an
error. to fix such problems, browsers allow us to run certain operations asynchronously. features like promises allow you to set an operation running (e.g. the fetching of an image from the server), and then wait until the result has returned before running another operation: main thread: task a task b promise: |__async operation__| since the operation is happening somewhe...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); just like settimeout(), setinterval() returns an identifying value you can use later when you need to clear the interval. clearing intervals setinterval() keeps running a task forever, unless you do something about it. you'll probably want a way to stop such tasks, otherwise you may end up getting
errors when the browser can't complete any further versions of the task, or if the animation being handled by the task has finished. you can do this the same way you stop timeouts — by passing the identifier returned by the setinterval() call to the clearinterval() function: const myinterval = setinterval(myfunction, 2000); clearinterval(myinterval); active learning: creating your own stopwatch! ...
...ords, the value of the second parameter can specify a different time in milliseconds to wait before running the code again. when your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive settimeout() — this will keep the time interval constant between executions regardless of how long the code takes to execute, and you won't get
errors. immediate timeouts using 0 as the value for settimeout() schedules the execution of the specified callback function as soon as possible but only after the main code thread has been run. for instance, the code below (see it live) outputs an alert containing "hello", then an alert containing "world" as soon as you click ok on the first alert. settimeout(function() { alert('world'); }, 0); ...
Function return values - Learn web development
an onchange event handler. it runs whenever the change event fires on the text input — that is, when a new value is entered into the text input, and submitted (e.g., enter a value, then unfocus the input by pressing tab or return). when this anonymous function runs, the value in the input is stored in the num constant. next, we do a conditional test. if the entered value is not a number, an
error message is printed to the paragraph. the test looks at whether the expression isnan(num) returns true. the isnan() function to test whether the num value is not a number — if so, it returns true, and if not, it returns false. if the test returns false, the num value is a number. therefore, a sentence is printed out inside the paragraph element that states the square, cube, and factorial valu...
...he finished version on github (see it running live also), or ask us for help. now it's your turn! at this point, we'd like you to have a go at writing out a couple of functions of your own and adding them to the library. how about the square or cube root of the number? or the circumference of a circle with a given radius? some extra function related tips: look at another example of writing
error handling into functions. it is generally a good idea to check that any necessary parameters are validated, and that any optional parameters have some kind of default value provided. this way, your program will be less likely to throw
errors. think about the idea of creating a function library. as you go further into your programming career, you'll start doing the same kinds of things over and ov...
Test your skills: Conditionals - Learn web development
in your code — conditionals article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). conditionals 1 in this task you are provided with two variables: season — contains a string that says what the current season is. response — begins uninitialized, but is later used to store a ...
...variable if it isn't, telling the user to switch the machine on. inside the first, you need to nest an if...else if...else that puts appropriate messages into the response variable depending on what the value of score is — if the machine is turned on. the different conditional tests (and resulting responses) are as follows: score of less than 0 or more than 100 — "this is not possible, an
error has occurred." score of 0 to 19 — "that was a terrible score — total fail!" score of 20 to 39 — "you know some things, but it's a pretty bad score. needs improvement." score of 40 to 69 — "you did a passable job, not bad!" score of 70 to 89 — "that\'s a great score, you really know your stuff." score of 90 to 100 — "what an amazing score! did you cheat? are you for real?" try u...
Third-party APIs - Learn web development
; j++) { ... } ) to loop through all the keywords associated with each article, and insert each one inside its own <span>, inside a <p>. this was done to make it easy to style each one. we used an if() block (if(current.multimedia.length > 0) { ... }) to check whether each article has any images associated with it (some stories don't.) we display the first image only if it exists (otherwise an
error would be thrown). we gave our <div> element a class of "clearfix", so we can easily apply clearing to it. wiring up the pagination buttons to make the pagination buttons work, we will increment (or decrement) the value of the pagenumber variable, and then re-rerun the fetch request with the new value included in the page url parameter. this works because the nytimes api only returns 10...
...t function is simple — we increment the pagenumber variable, then run the fetchresults() function again to display the next page's results. the second function works nearly exactly the same way in reverse, but we also have to take the extra step of checking that pagenumber is not already zero before decrementing it — if the fetch request runs with a minus page url parameter, it could cause
errors. if the pagenumber is already 0, we simply return out of the function, to avoid wasting processing power (if we are already at the first page, we don't need to load the same results again). note: you can find our finished nytimes api example code on github (also see it running live here). youtube example we also built another example for you to study and learn from — see our youtube vi...
Basic math in JavaScript — numbers and operators - Learn web development
check it out live, and look at the source code to see if you can spot the incrementors! we'll look at loops in detail later on in the course. let's try playing with these in your console. for a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. the following will return an
error: 3++; so, you can only increment an existing variable. try this: let num1 = 4; num1++; okay, strangeness number 2! when you do this, you'll see a value of 4 returned — this is because the browser returns the current value, then increments the variable. you can see that it's been incremented if you return the variable value again: num1; the same is true of -- : try the following let num2 ...
...te: you may see some people using == and != in their tests for equality and non-equality. these are valid operators in javascript, but they differ from ===/!==. the former versions test whether the values are the same but not whether the values' datatypes are the same. the latter, strict versions test the equality of both the values and their datatypes. the strict versions tend to result in fewer
errors, so we recommend you use them. if you try entering some of these values in a console, you'll see that they all return true/false values — those booleans we mentioned in the last article. these are very useful, as they allow us to make decisions in our code, and they are used every time we want to make a choice of some kind. for example, booleans can be used to: display the correct text la...
Test your skills: Strings - Learn web development
pt and useful string methods articles. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). strings 1 in our first strings task, we start off small. you already have half of a famous quote inside a variable called quotestart; we would like you to: look up the other half of the quote, and ...
...sk, we start off small. you already have half of a famous quote inside a variable called quotestart; we would like you to: look up the other half of the quote, and add it to the example inside a variable called quoteend. concatenate the two strings together to make a single string containing the complete quote. save the result inside a variable called finalquote. you'll find that you get an
error at this point. can you fix the problem with quotestart, so that the full quote displays correctly? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. strings 2 in this task you are provided with two variables, quote and substring, which contain two strings. we would like you to: ...
Test your skills: variables - Learn web development
ormation you need — variables article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). variables 1 in this task we want you to: declare a variable called myname. initialize myname with a suitable value, on a separate line (you can use your actual name, or something else). declare a...
...es 2 in this task you need to add a new line to correct the value stored in the existing myname variable to your own name. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. variables 3 the final task for now — in this case you are provided with some existing code, which has two
errors present in it. the results panel should be outputting the name chris, and a statement about how old chris will be in 20 years' time. how can you fix the problem and correct the output? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice t...
Inheritance in JavaScript - Learn web development
rson { constructor(subject, grade) { this.subject = subject; this.grade = grade; } } but there's a little catch. unlike old-school constructor functions where the new operator does the initialization of this to a newly-allocated object, this isn't automatically initialized for a class defined by the extends keyword, i.e the sub-classes. therefore running the above code will give an
error: uncaught reference
error: must call super constructor in derived class before accessing 'this' or returning from derived constructor for sub-classes, the this intialization to a newly allocated object is always dependant on the parent class constructor, i.e the constructor function of the class from which you're extending. here we are extending the person class — the teacher sub-class is an ...
...and grade are specific to teacher this._subject = subject; this.grade = grade; } get subject() { return this._subject; } set subject(newsubject) { this._subject = newsubject; } } in our class above we have a getter and setter for the subject property. we use _ to create a separate value in which to store our name property. without using this convention, we would get
errors every time we called get or set. at this point: to show the current value of the _subject property of the snape object we can use the snape.subject getter method. to assign a new value to the _subject property we can use the snape.subject="new value" setter method. the example below shows the two features in action: // check the default value console.log(snape.subject) // returns "dark ar...
Working with Svelte stores - Learn web development
t is unmounted. it will also generate the alert.set(...) statements whenever we assign a value to $alert. the end result of this nifty trick is that you can access global stores just as easily as using reactive local variables. this is a perfect example of how svelte puts the compiler in charge of better developer ergonomics, not only saving us from typing boiler plate, but also generating less
error-prone code. writing to our store writing to our store is just a matter of importing it and executing $store = 'new value'. let's use it in our todos component. add the following import statement below the existing ones: import { alert } from '../stores.js' update your addtodo() function like so: function addtodo(name) { todos = [...todos, { id: newtodoid, name, completed: fa...
...our modification methods into a central place. we'll just leave them as they are, and instead concentrate on persisting our todos. note: if you are following this guide working from the svelte repl you won't be able to complete this step. for security reasons the svelte repl works in a sandboxed environment which will not let you access web torage, and you will get a "the operation is insecure"
error. in order to follow this section you'll have to clone the repo and go to the mdn-svelte-tutorial/06-stores folder or you can directly download the folder's content with npx degit opensas/mdn-svelte-tutorial/06-stores. so, to implement a custom store that saves its content to web storage, we will need a writable store that: initially reads the value from web storage, and if it's not present i...
Accessibility API cross-reference
n/a expandable expandable implied by the presence of the aria-expanded attribu...
... folded tree branches or accordions collapsed collapsed collapsed aria-expanded=false different from xul's collapsed="true" attribute which indicates something is hidden this is the default button or menu item default n/a n/a identifies the element that provides an
error message for the object. n/a n/a aria-
errormessage an item that has been expanded, such as a tree item or accordion expanded expanded expanded aria-expanded=true indicates this object allows progressive disclosure of its children. n/a expandable expandable implied by the presence of the aria-expanded attribute, regardless of value can extend sele...
Command line options
(composer) for the given url (where url is optional). seamonkey only. seamonkey -edit www.mozilla.org -inspector url start with the dom inspector, if installed, and inspect the given url (where url is optional). -jsdebugger start application with browser toolbox (formerly browser debugger). that is different to venkman debugger (see option -venkman). -jsconsole start application with the
error console, or, in firefox, the browser console. -purgecaches gecko (layout engine) has a javascript cache, which is not reset on startup, this clears it. -start-debugger-server port firefox only. start the debugger server on port. this will enable another instance of firefox to connect the firefox developer tools to this firefox instance. see the article on remotely debugging firefox desktop. ...
...d by the application. --display=display set the x display to use. --g-fatal-warnings make all warnings fatal. --sync make x calls synchronous. ...
Creating a Language Pack
source. every time you want to create a langpack, you need to be in the directory obj-firefox-build/browser/locales. it is likely that you will continue to generate language packs as your progress just to test your work. while in that directory, issue the following command: $ make merge-x-testing locale_mergedir=$(pwd)/mergedir x-testing: browser chrome browser aboutcert
error.dtd // add and localize this file ... // lots of notifications about missing entities ... x-testing: changed: 6 missinginfiles: 6124 missing: 5 0% of entries changed this step is not necessary anymore to create the language pack, because it is included in the next command. it is only useful if you want to preview the contents of the mergedir. you'll see that...
...x-testing locale with the en-us files from the original source. issue the following command: $ make merge-x-testing locale_mergedir=$(pwd)/mergedir rm -f -rf mergedir macosx_deployment_target= compare-locales -m mergedir /users/your_id/mozilla/vc/mozilla-aurora/browser/locales/l10n.ini /users/your_id/mozilla/vc/l10n-central x-testing x-testing: browser chrome browser aboutcert
error.dtd // add and localize this file ... // lots of notifications about missing entities ... x-testing: changed: 6 missinginfiles: 6124 missing: 5 0% of entries changed if you now preview the contents of the mergedir, you'll see that it contains the files which in your localization were missing some entities. all other files will be taken from en-us directly. i...
Debugging OpenGL
xt isn't current, the call aborts. every time an opengl call completes, glfinish() gets run automatically. this flushes out each call, essentially turning opengl into a synchronous api. this makes debugging crashes caused by an opengl call much easier, since the stack you see will match where the call was issued, rather than some time in the future when it happens to run and crash. if an opengl
error occurred when executing the call, an
error message is output. note: you can download debug builds from mozilla taskcluster — click an appropriate platform's debug build on the left, e.g. linux64-debug, then find the build link on the right hand side (this would be target.tar.bz2 for linux, target.dmg for macos, and target.zip for windows). if you need more verbose debug output, you can ena...
...d target.zip for windows). if you need more verbose debug output, you can enable the verbose debug mode by defining the environment variable moz_gl_debug_verbose. with this enabled, messages are printed before and after every opengl call. this can help make it much easier to debug crashes and hangs that make the computer unusable (thereby stymieing attempts to debug). the moz_gl_debug_abort_on_
error environment variable, if set, causes firefox to abort as soon as an opengl
error occurs. this is generally only useful in cases where you know that no
error should occur, since there are cases where perfectly valid webgl code may generate opengl
errors. you don't have to define more than one of these; for example, if you set moz_gl_debug_abort_on_
error, the moz_gl_debug setting is assumed. ...
Configuring Build Options
eople developing patches (especially in c++) should generally use this option. ac_add_options --disable-optimize disables compiler optimization. this makes it much easier to step through code in a debugger. ac_add_options --enable-debug-js-modules enable only javascript assertions. this is useful when working locally on javascript-powered components like the devtools. this will help catch any
errors introduced into the js code, with less of a performance impact compared to the --enable-debug option. you can make an optimized build with debugging symbols. see building firefox with debug symbols. extensions ac_add_options --enable-extensions=default|all|ext1,ext2,-skipext3 there are many optional pieces of code that live in extensions/. many of these extensions are now considered an in...
... enables the machinery that allows firefox to write out a minidump files when crashing as well as the tools to process and submit crash reports to mozilla. after enabling the crash reporter in your local build, you will need to run mach with the --enable-crash-reporter (note the extra dash) to enable it at runtime, like so: `./mach run --enable-crash-reporter` ac_add_options --enable-warnings-as-
errors this makes compiler warnings into
errors which fail the build. this can be useful since certain warnings coincide with reviewbot lints which must be fixed before merging. ac_add_options --with-ccache=/path/to/.mozbuild/sccache/sccache this enables sccache to speed up builds. this saves a considerable amount of time directly after a clobber build, so pulling in new updates and rebasing is less...
Simple Instantbird build
use "documents and settings"). you can pick any other location, such as a new directory c:\instantbird-src. note: parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). on linux, this can manifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of os access denied
errors, where access is denied not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it close to the root of your machine and re-building.
... replace the url to the repository in the hg clone instruction). checked to make sure that the path in which you placed the source code has no spaces, and is not too long? have you searched the bug database for issues relating to your problem (e.g., platform-specific issues)? try asking in mozilla.dev.chat - don't forget to include details of what is in your mozconfig, and what the actual
error is. references general build documentation comm-central simple thunderbird build ...
Commenting IDL for better documentation
cription please only use this to provide a brief description of the interface, keep it short and to the point. do not include more than one brief per interface. @param parameter description every parameter of a method should be documented, only use the parameter name, leave out things like [in]/[out]. @returns description if the method returns something then this should be included. @throws
error description the
error should be the actual name of the
error constant, in all caps. @note description used to include a note styled paragraph. @remarks remark a remark paragraph to be included in the remarks section of the documentation. note: this is not yet supported by our documentation tool. using it will make it easier for documenters. @see description either an interface or a html l...
...icookie 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 astring language); }; in conclu...
Limitations of chrome scripts
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 in multiprocess firefox, if you register the nsiconten...
...and document-element-inserted in a frame script. observers for these topics get content objects as the asubject argument to observe(), so notifications are not sent to the chrome process. there is a shim that will forward these two topics to the chrome process, sending cpows as the asubject argument. http requests you can't observe http requests in the content process. if you do, you'll get an
error. if you do so in the chrome process, it will mostly work. the subject for the observer notification will be an nsihttpchannel as you would expect. a common pattern here is to use the notificationcallbacks property of the nsihttpchannel to get the dom window that initiated the load, like this: observe: function (subject, topic, data) { if (topic == "http-on-modify-request") { var httpch...
Storage access policy: Block cookies from trackers
rs across 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 security
error exception. prior to firefox 70: window.localstorage is null. thus, attempts to read and write using this object will throw a type
error exception. sessionstorage: read and write attempts are permitted. indexeddb: attempting to access the indexeddb factory object throws a security
error exception. messaging and workers: broadcast channel: attempts to create a new broadcastchannel will throw ...
.... prior to firefox 70: window.localstorage is null. thus, attempts to read and write using this object will throw a type
error exception. sessionstorage: read and write attempts are permitted. indexeddb: attempting to access the indexeddb factory object throws a security
error exception. messaging and workers: broadcast channel: attempts to create a new broadcastchannel will throw a security
error exception. shared worker: attempts to create a new sharedworker will throw a security
error exception. service worker: attempts to create a new serviceworker will throw a security
error exception. dom cache: calls to cachestorage will always reject with a security
error. browser caches: the http cache, the image cache, and the alternative services (alt-svc) cache are all partitioned for ...
HTMLIFrameElement.download()
warning: removed in firefox 65. the download() method of the htmliframeelement interface downloads a specified url, storing it at /sdcard/download. syntax var instanceofdomrequest = instanceofhtmliframeelement.download(url, options); returns a domrequest for handling the download request. its request.onsuccess handler handles the success case, and its request.on
error handler handles the failure case. parameters url the url of the file to be downloaded. options optional an options object allowing optional settings to be specified for the download. the available options are: filename: the filename to save the downloaded file as. if this is not specified, the filename used will be the original filename, as specified in the url. referrer: specifies a referrer for the downloaded...
...fied, the filename used will be the original filename, as specified in the url. referrer: specifies a referrer for the downloaded file. if this is not specified there will be no referrer. examples var browser = document.queryselector('iframe'); var request = browser.download(foourl, { filename: 'foo.bin' }); request.onsuccess = function() { console.log("file downladed"); } request.on
error = function() { console.log("download
error"); } specification not part of any specification. ...
HTMLIFrameElement.getContentDimensions()
lement interface retrieves the x and y dimensions of the content window. note: the values returned are equivalent to document.body.scrollwidth and document.body.scrollheight. syntax var instanceofdomrequest = instanceofhtmliframeelement.getcontentdimensions(); returns a domrequest for handling the dimensions request. its request.onsuccess handler handles the success case, and its request.on
error handler handles the failure case. the x and y dimensions are available in the request.result.x and request.result.y properties, respectively. parameters none. examples var browser = document.queryselector('iframe'); var request = browser.getcontentdimensions(); request.onsuccess = function() { console.log("page size:", request.result.width + "x" + request.result.height); } ...
...ndles the failure case. the x and y dimensions are available in the request.result.x and request.result.y properties, respectively. parameters none. examples var browser = document.queryselector('iframe'); var request = browser.getcontentdimensions(); request.onsuccess = function() { console.log("page size:", request.result.width + "x" + request.result.height); } request.on
error = function() { console.log("download
error"); } specification not part of any specification. ...
mozbrowseractivitydone
user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowseractivitydone event is fired when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. if the activity has a returnvalue set to true, then the activity is consumed when postresult or post
error is invoked on the activity by the receiving app. note: for activities where the receiving app's activity definition in its manifest does not include returnvalue or returnvalue is false, no mozbrowseractivitydone event will be generated as of the landing of bug 1194525 in firefox os 2.5. postresult and post
error calls made on such an activity will be ignored and have no effect. general info ...
...mpleted successfully (true) or not (false). ...
HTMLIFrameElement.purgeHistory()
ete cookies for a firefox os app, you could call clearbrowserdata() on the actual app itself. syntax there is a domrequest version and a promise version: var mydomrequest = instanceofhtmliframeelement.purgehistory(); instanceofhtmliframeelement.purgehistory().then(function() { ... ...
...ject that returns an onsuccess handler if the history is deleted, or an on
error handler if not. a promise that resolves, with no parameters, if the history is deleted, or rejects if not. parameters none. examples domrequest: var browser = document.queryselector('iframe'); var request = browser.purgehistory(); request.onsuccess = function() { console.log('history deleted!'); } request.on
error = function() { console.
error(this.
error.name); } promise: var browser = document.queryselector('iframe'); browser.purgehistory().then(function() { console.log('history deleted!'); }, function(
error) { console.
error(this.
error.name); }); specification not part of any specification. ...
IPDL Best Practices
while this can be worked around with actordestroy, being explicit about deleting the protocol with send__delete__ is easier to maintain, with symmetric alloc/deallocpprotoc...
...nt(); } bool deallocpprotocol() { return true; } }; nsautoptr<pprotocolparent> parent = manager->sendpprotocolconstructor(); while this may look appealing as the ipdl logic is stuffed away in a sensible place, it breaks under
error conditions. specifically, because allocpprotocol and deallocpprotocol are asymmetric, if ipdl ends up shutting down the protocol tree due to an
error, the auto pointer will attempt to trigger protocol deletion a second time. while this can be worked around with actordestroy, being explicit about deleting the protocol with send__delete__ is easier to maintain, with symmetric alloc/deallocpprotocol functions also being easier to reason about. minimize overall use of messages reducing ipc traffic is a righteous goal. consider the following prot...
Implementing Download Resuming
g the nsiresumablechannel 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). th...
...ink (this needs to be done before calling asyncopen). note: in versions of firefox prior to 3.0 alpha 7, nsiwebbrowserpersist cannot append to existing files (as opposed to overwriting them), and is therefore not usable for this task (see bug 129921). detecting when a file changed if the file changed (that is, the entity id does not match), then necko will notify the stream listener with an ns_
error_entity_changed
error code. the front-end may want to offer the user to get the new file from scratch in such a case. resuming not supported in some cases, it's not possible to detect whether the server supports resuming until the user actually tries to resume. in such a case, the stream listener will get an ns_
error_not_resumable status. here, too, the front-end may want to offer downloading th...
JavaScript-DOM Prototypes in Mozilla
ment examples above, those examples let you define new properties on all image elements. by modifying the node top-level object, you can do similar things to all objects that implement node. this means you can add a property to every node in a dom tree by doing something like this: node.prototype.foo = bar; again, modifying host objects is an unsafe practice. it is not guaranteed to work or be
error-free in any implementation. it is not standard and cannot be expected to have any result. here is an attempt to modify a host object: (function(){ try { image.prototype.src = 1; } catch(ex){ alert(ex); } })(); this demonstrates that the image constructor, a host object supported in nearly all browsers for mac and windows, has a prototype property, and tha...
...ed to have any result. here is an attempt to modify a host object: (function(){ try { image.prototype.src = 1; } catch(ex){ alert(ex); } })(); this demonstrates that the image constructor, a host object supported in nearly all browsers for mac and windows, has a prototype property, and that an attempt to modify the prototype's src - property results in an
error. another example would be modifying the pagex property of a mouseevent instance. the pagex property actually needs a patch because it doesn't get set correctly in initmouseevent bug 411031. here is a diagram that shows the prototype layout of a htmldivelement in mozilla: htmldivelement.prototype | |.__proto__ | htmlelement.prototype | ...
Addon
required methods iscompatiblewith() tests whether this add-on is known to be compatible with a particular application and platform vers...
...t read only integer reviewurl read only string totaldownloads read only integer weeklydownloads read only integer dailyusers read only integer repositorystatus read only integer callbacks datadirectorycallback() a callback which is passed a directory path, and, when an
error has occured, an
error object. void datadirectorycallback( in string path, in
error error ) parameters path a string representation of the addon's data directory.
error if an
error has occured, an
error object relevant to the
error, othereise null. required methods iscompatiblewith() tests whether this add-on is known to be compatible with a particular application and platform version. void iscompatibl...
UpdateListener
s found. onupdatefinished() to signal that the update check has completed. method overview void oncompatibilityupdateavailable(in addon addon) void onnocompatibilityupdateavailable(in addon addon) void onupdateavailable(in addon addon, in addoninstall install) void onnoupdateavailable(in addon addon) void onupdatefinished(in addon addon, in integer
error) methods oncompatibilityupdateavailable() called when the update check found compatibility information for the application and platform version that the update check was being performed for. void oncompatibilityupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onnocompatibilityupdateavailable() called when the update check found n...
...eing checked for updates install an addoninstall for the updated version onnoupdateavailable() called when no new version of an add-on has been found for install. void onnoupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onupdatefinished() called when the update check is complete. void onupdatefinished( in addon addon, in integer
error ) parameters addon the addon that was being checked for updates
error any
error from the update checkaddon ...
AsyncShutdown.jsm
d addblocker(string name, function|promise condition, optional function info) boolean removeblocker(function|promise condition) methods addblocker () register a blocker for the completion of a phase. void addblocker( in string name, in function|promise|* condition, optional in function info ) arguments name the human-readable name of the blocker. used for debugging/
error reporting. please make sure that the name respects the following model: "some service: some action in progress" - for instance "os.file: flushing all pending i/o". condition a condition blocking the completion of the phase. generally, this is a function returning a promise. this function is evaluated during the phase and the phase is guaranteed to not terminate until the resulting promise is ei...
...this function is evaluated during the phase and the phase is guaranteed to not terminate until the resulting promise is either resolved or rejected. if condition is not a function but another value v, it behaves as if it were a function returning v. info optionally, a function returning information about the current state of the blocker as an object. used for providing more details when logging
errors or crashing. removeblocker () remove the blocker for a condition. if several blockers have been registered for the same condition, remove all these blockers. if no blocker has been registered for this condition, this is a noop. boolean removeblocker( in function|promise|* condition ) arguments condition a condition blocking the completion of the phase. this must be the same condition...
DeferredTask.jsm
en if the delay specified on construction is zero. multiple "arm" calls within the same tick of the event loop are guaranteed to result in a single execution of the task. by design, this method doesn't provide a way for the caller to detect when the next execution terminates, or collect a result. in fact, doing that would often result in duplicate processing or logging. if a special operation or
error logging is needed on completion, it can be better handled from within the task itself, for example using a try/catch/finally clause in the task. the "finalize" method can be used in the common case of waiting for completion on shutdown. void arm(); disarm cancel any request for a delayed execution of the task, though the task itself cannot be canceled in case it is already running. this me...
... instead, if you are going to delete the saved data from disk anyways, you might as well prevent any pending write from starting, while still ensuring that any write that is currently in progress terminates, so that the file is not in use any more: savedeferredtask.disarm(); savedeferredtask.finalize().then(() => os.file.remove(...)) .then(null, components.utils.report
error); ...
Download
number of bytes currently transferred. this value starts at zero, and may be updated regardless of the value of hasprogress. note: you shouldn't rely on this property being equal to totalbytes to determine whether the download is completed. you should use the individual state properties instead, since this value may not be updated after the last piece of data is transferred.
error read only download
error when the download fails, this is set to a download
error instance indicating the cause of the failure. if the download has been completed successfully or has been canceled, this property is null. this property is reset to null when a failed download is restarted. haspartialdata read only boolean indicates whether, at this time, there is any parti...
...mediately. note: if you need to start a new download from the same source, rather than restarting a failed or canceled one, you should create a separate download object with the same source as the current one. promise start(); parameters none. promise resolves to undefined when the download has finished successfully and you can access the target file. promise can be rejected with download
error if the download failed. launch() opens or executes the target file after download has completed. if the launcherpath property is null, the file will be opened with the default application for the mime type specified in the contenttype property. if the content type is not available, an attempt will be made to obtain it from the extension of the target file. if the launcherpath property is set,...
Interfacing with the Add-on Repository
ne, passing in as parameters a prompt including the name of the returned add-on, a label for the button to show in the notification ("install"), and the addoninstall object that can be used with the add-on manager api to install the add-on. ...
... ); } the code here starts by stashing the passed-in addoninstall object for later use, then creates and displays the pop-up notification box with the text and button label passed into the method. the pop-up callback function that gets called when the user clicks the button looks to see if there's a non-null addoninstall object reference; if it's null, then the pop-up is displaying an
error notification, so clicking the button simply dismisses the pop-up. otherwise, the addoninstall object's install() method is called to install the add-on. this doesn't display any ui showing that the install is taking place; however, if you go to the add-on manager panel, you'll see the pending install listed among your add-ons. ...
Following the Android Toasts Tutorial from a JNI Perspective
object called sig and populate it with our types. let sig = { context: 'landroid/content/context;', charsequence; 'ljava/lang/charsequence;', int: 'i', toast: 'landroid/widget/toast;', void: 'v', }; get java environment before we go on to declare the other important features, we need to load our environment variable. we want to wrap this in a try-catch statement so if any
errors occur we make sure to unload the classes and the java environment, this is good for performance. this is the template that will follow our object of signatures: var my_jenv = null; try { my_jenv = jni.getforthread(); // do the jni work here } finally { if (my_jenv) { jni.unloadclasses(my_jenv); } } the reason we choose my_jenv for a variable name, and not jenv, is be...
...thods, fields, and static_fields go here }); the variable name of toast was used, but it does not matter, you can use whatever you want. the first argument to loadclass is the java environment variable, my_jenv. the second argument is the class sig without the surrounding l and ;. because we don't want to keep typing string signatures everywhere, we can end up with typos and hard to trace back
errors, we use the sig object. we see sig.toast.substr(1, sig.toast.length - 2) was written, this can be replaced with 'android/widget/toast'. the third argument is an object of our declares. declare constructors in our toast example, we do not have any constructors. determine static-ness of methods declare them there are two types of methods, chainable and static. if it is static, this means that...
OSFile.jsm
executed on a worker thread. for this reason, api clients can also spawn their own worker threads and make use of os.file directly from these threads. ...
...reason, api clients can also spawn their own worker threads and make use of os.file directly from these threads. ...
Promise.jsm
t may not be available yet. internally, a promise can be in one of three states: pending, when the final value is not available yet. this is the only state that may transition to one of the other two states. fulfilled, 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 th...
...ed with the value, i.e. 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. ...
Webapps.jsm
path) _getappdir: function(aid) _writefile: function(apath, adata) dogetlist: function() doexport: function(amsg, amm) doimport: function(amsg, amm) doextractmanifest: function(amsg, amm) dolaunch: function (adata, amm) launch: function launch(amanifesturl, astartpoint, atimestamp, aonsuccess, aonfailure) close: function close(aapp) canceldownload: function canceldownload(amanifesturl, a
error) startofflinecachedownload: function(amanifest, aapp, aprofiledir, aisupdate) computemanifesthash: function(amanifest) updateapphandlers: function(aoldmanifest, anewmanifest, aapp) checkforupdate: function(adata, amm) doinstall: function doinstall(adata, amm) doinstallpackage: function doinstallpackage(adata, amm) pushcontentaction: function(windowid) popcontentaction: function(windowid) ...
...(aapp, aissigned, aislocalfileinstall) _saveetag: function(aisupdate, aoldapp, arequestchannel, ahash, amanifest) _checkorigin: function(aissigned, aoldapp, amanifest, aisupdate) _getids: function(aissigned, azipreader, aconverter, anewapp, aoldapp,) _checkforstoreidmatch: function(aisupdate, anewapp, astoreid, astoreversion) revertdownloadpackage: function(aid, aoldapp, anewapp, aisupdate, a
error) uninstall: function(amanifesturl) _promptforuninstall: function(adata) confirmuninstall: function(adata) denyuninstall: function(adata, areason = "
error_unknown_failure") getself: function(adata, amm) checkinstalled: function(adata, amm) getinstalled: function(adata, amm) getnotinstalled: function(adata, amm) geticon: function(adata, amm) getall: function(acallback) isreceipt: functio...
What every Mozilla translator should know
this way you will receive mail for bugs affecting many or even all locales. when you create a bug, if you want the person in charge 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 t...
...so, change the state of the bug to verified and write verified1.8.xxx in the keyword field tinderbox in tinderbox you can see the result of the build process. once you have made some changes in mercurial, as soon as the next build is done you can check the tinderbox and see if something was wrong. l10n tinderbox when the color is green, it means that the build process has finished with no
errors. in this case the resultant installable file will be available in the mozilla ftp servers: firefox nightly builds thunderbird nightly builds qa (quality assurance) in order to assure the quality of a build we should make some tests using http://litmus.mozilla.org ...
MathML3Testsuite
the pages below contain our current results 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 ...
...t is welcome on the tracking bug for the mathml testsuite. characters blocks symbols variants entitynames numericrefs utf8 general clipboard genattribs math presentation css dynamicexpressions generallayout scriptsandlimits tablesandmatrices tokenelements topics accents bidi elementarymathexamples embellishedop largeop linebreak nesting stretchychars whitespace torturetests
errorhandling original document information author(s): frédéric wang other contributors: last updated date: may 26, 2010 copyright information: portions of this content are © 2010 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Mozilla Port Blocking
tocol's handler can override this blocking for itself in order to enable the required access for that protocol. potential problems caused by port blocking port blocking can cause problems if a site or web application requires access to one of the ports which is blocked in mozilla. ...
...s if a site or web application requires access to one of the ports which is blocked in mozilla. if a user attempts to access a uri on a blocked port, mozilla shows one of the following alerts to the user or in the
error console. "access to the port number given has been disabled for security reasons." "establishing a connection to an unsafe or otherwise banned port was prohibited" "0x804b0013 (ns_
error_port_access_not_allowed)" if your product or web site uses a port which is blocked by mozilla's default port blocking rules, you can either change the port of your service to a unblocked value (recommended if possible) or ask your mozilla users to enable the port. for details on which ports are blocked and how to override the blocking see below. modifying mozilla's port blocking at run time users...
Memory reporting
ided into the two following kinds. traversal-based reporters traverse one or more data structures and measure the size of all the allocated blocks in the data structure. counter-based reporters maintain a counter that is incremented on each relevant allocation and decremented on each relevant deallocation. traversal-based reporters are preferable, for the following reasons. they are less
error-prone. we've had multiple bugs in the past with counter-based reporters. the cost of reporting isn't incurred unless the memory reporter is queried. they provide more information to dmd, which is a tool that helps keep about:memory's "heap-unclassified" number low. see below for more details. sometimes counter-based reporters are unavoidable, particularly when writing memory reporters for thi...
...e, including "slop" bytes caused by the heap allocator rounding up request sizes (a.k.a. internal fragmentation). if slop bytes aren't measured they'll end up in about:memory's heap-unclassified entry, which is bad. the size is not computed analytically. for example, sizeof doesn't appear anywhere. this is a good thing, because computing sizes analytically doesn't count slop, and it is much more
error-prone than using moz_malloc_usable_size. they are flexible and integrate well with dmd. the amallocsizeof parameter allows mozilla::mallocsizeof functions with dmd-specific hooks to be passed in when they are used by memory reporters, but functions without such hooks (such as moz_malloc_size_of) can also be passed in when they are used in other circumstances. some other things to note. plea...
TraceMalloc
tk 476 2197708 341 2366564 -135 168856 9.32 nsmemcacherecord 843 45767 2328 124767 1485 79000 4.36 nstextnode 209 11704 1614 90384 1405 78680 4.34 htmlattributesimpl 482 14288 2824 88400 2342 74112 4.09 nsscanner 58 76824 94 146300 36 69476 3.83 nsscript
error 253 25070 842 91548 589 66478 3.67 nshtmldocument.mreferrer 177 21550 691 85460 514 63910 3.53 nshtmlvalue 139 7846 1215 68734 1076 60888 3.36 htmlcontentsink 6 4816 12 57782 6 52966 2.92 uncategorized.pl, which lists all the void* allocations (the ones that couldn't be catego...
... all the void* allocations (the ones that couldn't be categorized by type), sorted by size. also, your javascript can call the following dom window methods: tracemallocdisable() - turn off tracing, first flushing any buffered log events for all log files. tracemallocenable() - turn on tracing. tracemallocopenlogfile(filename) - open a new log file and return its log file descriptor (or -1 on
error). tracemallocchangelogfd(logfd) - change the current log file to the one identified by logfd, returning the previous fd (so you can maintain a number of open files; keep their fds in a js array!). tracemalloccloselogfd(logfd) - close the log file identified by logfd, flushing its buffer of any events first. if logfd identifies the current log file, change the current log file to the default log...
Optimizing Applications For NSPR
s 3.1 applications for cross platform consistency, but do not expect to see real 64 bit file offset behavior. on windows 3.1, when nspr detects a value in a 64 bit file offset greater than 32bit significance, it terminates with an assert. the general rules of 16 bit large model memory restrictions apply to applications using nspr on windows 3.1. the nspr process creation api functions return an
error when invoked on windows 3.1. functions called in an application by a shared library require an additional function prolog. the prolog is presented in the macro <tt>pr_callback</tt>. for any function made available to any shared library (most likely passed in as a function pointer), that function must have the <tt>pr_callback</tt> qualifier. nspr functions are normally declared <tt>__cdecl</tt>.
...ems, depending on the needs of your application. the mode (blocking or nonblocking) of a socket cannot be changed at will once the socket has been used. also, the new socket created by an <tt>pr_accept()</tt> call on a listening socket inherits the mode of the listening socket, and cannot be changed. a file descriptor is not usable after an io operation on it fails with either <tt>pr_io_timeout_
error</tt> or <tt>pr_io_interrupt_
error</tt>. the only thing you can do is to close the file descriptor. see the faq article for more info. there is no current workaround. you must write your program with this restriction in mind. pr_interrupt is implemented except for <tt>pr_connect()</tt>. irix the irix (classic) implementation has a known race condition in creating new threads. if the spawned t...
Introduction to NSPR
ropriate for each host os. it's usually not necessary to create a global thread explicitly unless you are planning to port your code only to platforms that provide threading services with which you are familiar or unless the thread will be executing code that might directly call blocking os functions. threads can also have "per-thread-data" attached to them. each thread has a built-in per-thread
error number and
error string that are updated when nspr operations fail. it's also possible for nspr clients to define their own per-thread-data. for details, see controlling per-thread private data. thread scheduling nspr threads are scheduled by priority and can be preempted or interrupted. the sections that follow briefly introduce the nspr approach to these three aspects of thread scheduling. ...
... are to turn off preemption (a runtime decision) or to preempt global threads only. interrupting threads nspr threads are interruptable, with some constraints and inconsistencies. to interrupt a thread, the caller of pr_interrupt must have the nspr reference to the target thread (prthread*). when the target is interrupted, it is rescheduled from the point at which it was blocked, with a status
error indicating that it was interrupted. nspr recognizes only two areas where a thread may be interrupted: waiting on a condition variable and waiting on i/o. in the latter case, interruption does cancel the i/o operation. in neither case does being interrupted imply the demise of the thread. nspr thread synchronization thread synchronization has two aspects: locking and notification. locking preven...
PR_Accept
the connecting entity. timeout a value of type printervaltime specifying the time limit for completion of the accept operation. returns the function returns one of the following values: upon successful acceptance of a connection, a pointer to a new prfiledesc structure representing the newly accepted connection. if unsuccessful, null. further information can be obtained by calling pr_get
error. description the socket fd is a rendezvous socket that has been bound to an address with pr_bind and is listening for connections after a call to pr_listen. pr_accept accepts the first connection from the queue of pending connections and creates a new socket for the newly accepted connection. the rendezvous socket can still be used to accept more connections. if the addr parameter is not null...
...n from the queue of pending connections and creates a new socket for the newly accepted connection. the rendezvous socket can still be used to accept more connections. if the addr parameter is not null, pr_accept stores the address of the connecting entity in the prnetaddr object pointed to by addr. pr_accept blocks the calling thread until either a new connection is successfully accepted or an
error occurs. if the timeout parameter is not pr_interval_no_timeout and no pending connection can be accepted before the time limit, pr_accept returns null with the
error code pr_io_timeout_
error. ...
PR_ConnectContinue
rfiledesc *fd, print16 out_flags); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. out_flags the out_flags field of the poll descriptor returned by pr_poll(). returns if the nonblocking connect has successfully completed, pr_connectcontinue returns pr_success. if pr_connectcontinue() returns pr_failure, call pr_get
error(): - pr_in_progress_
error: the nonblocking connect is still in progress and has not completed yet. the caller should poll the file descriptor for the in_flags pr_poll_write|pr_poll_except and retry pr_connectcontinue later when pr_poll() returns. - other
errors: the nonblocking connect has failed with this
error code. description continue a nonblocking connect. after a nonblockin...
...gress and has not completed yet. the caller should poll the file descriptor for the in_flags pr_poll_write|pr_poll_except and retry pr_connectcontinue later when pr_poll() returns. - other
errors: the nonblocking connect has failed with this
error code. description continue a nonblocking connect. after a nonblocking connect is initiated with pr_connect() (which fails with pr_in_progress_
error), one should call pr_poll() on the socket, with the in_flags pr_poll_write | pr_poll_except. when pr_poll() returns, one calls pr_connectcontinue() on the socket to determine whether the nonblocking connect has completed or is still in progress. repeat the pr_poll(), pr_connectcontinue() sequence until the nonblocking connect has completed. ...
PR_GetSpecialFD
gets the file descriptor that represents the standard input, output, or
error stream. syntax #include <prio.h> prfiledesc* pr_getspecialfd(prspecialfd id); parameter the function has the following parameter: id a pointer to an enumerator of type prspecialfd, indicating the type of i/o stream desired: pr_standardinput, pr_standardoutput, or pr_standard
error. returns if the id parameter is valid, pr_getspecialfd returns a file descriptor that represents the corresponding standard i/o stream. otherwise, pr_getspecialfd returns null and sets the
error to pr_invalid_argument_
error. ...
...andardoutput, or pr_standard
error. returns if the id parameter is valid, pr_getspecialfd returns a file descriptor that represents the corresponding standard i/o stream. otherwise, pr_getspecialfd returns null and sets the
error to pr_invalid_argument_
error. description type prspecialfd is defined as follows: typedef enum prspecialfd{ pr_standardinput, pr_standardoutput, pr_standard
error } prspecialfd; #define pr_stdin pr_getspecialfd(pr_standardinput) #define pr_stdout pr_getspecialfd(pr_standardoutput) #define pr_stderr pr_getspecialfd(pr_standard
error) file descriptors returned by pr_getspecialfd are owned by the runtime and should not be closed by the caller. ...
PR_Interrupt
arranged between the thread doing the interrupting and the thread being interrupted. when the interrupted thread reaches the prearranged point, it can communicate with its peer to discover the real reason behind the change in plans. the interrupt request remains in the thread's state until it is delivered exactly once or explicitly canceled. the interrupted thread returns pr_failure (-1) with an
error code (see pr_get
error) for blocking operations that return a prstatus (such as i/o operations, monitor waits, or waiting on a condition). to check whether the thread was interrupted, compare the result of pr_get
error with pr_pending_interrupt_
error. pr_interrupt may itself fail if the target thread is invalid. bugs pr_interrupt has the following limitations and known bugs: there can be a de...
...wing limitations and known bugs: there can be a delay for a thread to be interrupted from a blocking i/o function. in all nspr implementations, the maximum delay is at most five seconds. in the pthreads-based implementation on unix, the maximum delay is 0.1 seconds. file i/o is considered instantaneous, so file i/o functions cannot be interrupted. unfortunately the standard input, output, and
error streams are treated as files by nspr, so a pr_read call on pr_stdin cannot be interrupted even though it may block indefinitely. in the nt implementation, pr_connect cannot be interrupted. in the nt implementation, a file descriptor is not usable and must be closed after an i/o function on the file descriptor is interrupted. see the memo using io timeout and interrupt on nt for details. ...
PR_Poll
ime expires without any i/o becoming ready, pr_poll returns zero. returns the function returns one of these values: if successful, the function returns a positive number indicating the number of prpolldesc structures in pds that have events. the value 0 indicates the function timed out. the value -1 indicates the function failed. the reason for the failure can be obtained by calling pr_get
error. 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 s...
...ting 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. ...
PR_Seek64
pr_seek_end. sets the file pointer to the size of the file plus the value of the offset parameter. returns the function returns one of the following values: if the function completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file. if the function fails, the file pointer remains unchanged and the function returns -1. ...
... size of the file plus the value of the offset parameter. returns the function returns one of the following values: if the function completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file. if the function fails, the file pointer remains unchanged and the function returns -1. the
error code can then be retrieved with pr_get
error. description this is the idiom for obtaining the current location (expressed as a 64-bit integer) of the file pointer for the file descriptor fd: pr_seek64(fd, 0, pr_seek_cur) if the operating system can handle only a 32-bit file offset, pr_seek64 may fail with the
error code pr_file_too_big_
error if the offset parameter is out of the range of a 32-bit integer. see also pr_seek ...
PR_StringToNetAddr
prstatus pr_stringtonetaddr( const char *string, prnetaddr *addr); parameters the function has the following parameters: string the string to be converted. addr on output, the equivalent network address. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_get
error. description for ipv4 addresses, the input string represents numbers in the internet standard "." notation. ipv6 addresses are indicated as strings using ":" characters separating octets, with numerous caveats for shortcutting (see rfc #1884). if the nspr library and the host are configured to support ipv6, both formats are supported. otherwise, use of anything other than ipv4 dotted notation ...
... ...
PR_Writev
meout); #define pr_max_iovector_size 16 parameters the function has the following parameters: fd a pointer to a prfiledesc object for a socket. iov an array of priovec structures that describe the buffers to write from. size number of priovec structures in the iov array. the value of this parameter must not be greater than pr_max_iovector_size. if it is, the function will fail and the
error will be set to pr_buffer_overflow_
error. timeout a value of type printervaltime describing the time limit for completion of the entire write operation. returns one of the following values: a positive number indicates the number of bytes successfully written. the value -1 indicates that the operation failed. the reason for the failure can be obtained by calling pr_get
error. description ...
...t the operation failed. the reason for the failure can be obtained by calling pr_get
error. description the thread calling pr_writev blocks until all the data is written or the write operation fails. therefore, the return value is equal to either the sum of all the buffer lengths (on success) or -1 (on failure). note that if pr_writev returns -1, part of the data may have been written before an
error occurred. if the timeout parameter is not pr_interval_no_timeout and all the data cannot be written in the specified interval, pr_writev returns -1 with the
error code pr_io_timeout_
error. this is the type definition for priovec: typedef struct priovec { char *iov_base; int iov_len; } priovec; the priovec structure has the following fields: iov_base a pointer to the beginning of the b...
NSS 3.46 release notes
hanges to the default tls configuration in nss 3.47, which will be released in october: tls 1.3 will be the default maximum tls version. see bug 1573118 for details. tls extended master secret will be enabled by default, where possible. see bug 1575411 for details. ...
...74220 - improve controls after
errors in tstcln, selfserv and vfyserv cmds bug 1550636 - upgrade sqlite in nss to a 2019 version bug 1572593 - reset advertised extensions in ssl_constructextensions bug 1415118 - nss build with ./build.sh --enable-libpkix fails bug 1539788 - add length checks for cryptographic primitives (cve-2019-17006) bug 1542077 - mp_set_ulong and mp_set_int should return
errors on bad values bug 1572791 - read out-of-bounds in der_decodetimechoice_util from sslexp_delegatecredential bug 1560593 - cleanup.sh script does not set
error exit code for tests that "failed with core" bug 1566601 - add wycheproof test vectors for aes-kw bug 1571316 - curve25519_32.c:280: undefined reference to `pr_assert' when building nss 3.45 on armhf-linux bug 1516593 - client to genera...
NSS 3.51 release notes
pdated dtls 1.3 implementation to draft-34. see bug 1608892 for details. bugs fixed in nss 3.51 bug 1608892 - update dtls 1.3 implementation to draft-34. bug 1611209 - correct swapped pkcs11 values of ckm_aes_cmac and ckm_aes_cmac_general bug 1612259 - complete integration of wycheproof ecdh test cases bug 1614183 - check if ppc __has_include(<sys/auxv.h>) bug 1614786 - fix a compilation
error for ‘getfipsenv’ "defined but not used" bug 1615208 - send dtls version numbers in dtls 1.3 supported_versions extension to avoid an incompatibility. bug 1538980 - secu_readderfromfile calls strstr on a string that isn't guaranteed to be null-terminated bug 1561337 - correct a warning for comparison of integers of different signs: 'int' and 'unsigned long' in security/nss/lib/freebl/ecl/ec...
...ent signs: 'int' and 'unsigned long' in security/nss/lib/freebl/ecl/ecp_25519.c:88 bug 1609751 - add test for mp_int clamping bug 1582169 - don't attempt to read the fips_enabled flag on the machine unless nss was built with fips enabled bug 1431940 - fix a null pointer dereference in blake2b_update bug 1617387 - fix compiler warning in secsign.c bug 1618400 - fix a openbsd/arm64 compilation
error: unused variable 'getauxval' bug 1610687 - fix a crash on unaligned cmaccontext.aes.keyschedule when using aes-ni intrinsics this bugzilla query returns all the bugs fixed in nss 3.51: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.51 compatibility nss 3.51 shared libraries are backward compatible w...
NSS 3.52 release notes
ed to a value corresponding to ulivlen. alternatively, defining nss_pkcs11_2_0_compat will yield the old definition. see the bug for more information. bug 1623374 - support new pkcs #11 v3.0 message interface for aes-gcm and chachapoly. bug 1612493 - integrate avx2 chacha20, poly1305, and chacha20poly1305 from hacl*. bugs fixed in nss 3.52 bug 1633498 - fix unused variable 'getauxval'
error on ios compilation. bug 1630721 - add softoken functions for fips. bug 1630458 - fix problem of gyp msvc builds not producing debug symbol files. bug 1629663 - add ikev1 quick mode kdf. bug 1629661 - mpconfig calls in ssl initialize policy before nss is initialized. bug 1629655 - support temporary session objects in ckfw. bug 1629105 - add pkcs11 v3.0 functions to module debug logger. bug ...
...ation. bug 1630721 - add softoken functions for fips. bug 1630458 - fix problem of gyp msvc builds not producing debug symbol files. bug 1629663 - add ikev1 quick mode kdf. bug 1629661 - mpconfig calls in ssl initialize policy before nss is initialized. bug 1629655 - support temporary session objects in ckfw. bug 1629105 - add pkcs11 v3.0 functions to module debug logger. bug 1626751 - fix
error in generation of fuzz32 docker image after updates. bug 1625133 - fix implicit declaration of function 'getopt'
error. bug 1624864 - allow building of gcm-arm32-neon on non-armv7 architectures. bug 1624402 - fix compilation
error in firefox android. bug 1624130 - require ck_function_list structs to be packed. bug 1624377 - fix clang warning for unknown argument '-msse4'. bug 1623374 - suppo...
NSS Sample Code Sample1
m_dupitem(data); if (!*res) { rv = 1; goto done; } done: return rv; } // initialize the nss library. normally this // would be done as part of each server's startup. // however, this example uses the same databases // to store keys for server in the "cluster" so // it is done once. ...
...the encryption and mac keys from the "files" rv = server1->start(); if (rv) { cout << "cannot start server 1" << endl; goto done; } // create a second server in the cluster. ...
NSS Sample Code Sample_2_Initialization of NSS
= null; char *p1 = null; secupwdata *pwdata = (secupwdata *) arg; if (pwdata->source == pw_fromfile) { return filepasswd(slot, retry, pwdata->data); } if (pwdata->source == pw_plaintext) { return pl_strdup(pwdata->data); } /* open terminal */ input = fopen("/dev/tty", "r"); if (input == null) { pr_fprintf(pr_stderr, "
error opening input terminal for read\n"); return null; } /* we have no password, so initialize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (o...
...turn null; } /* we have no password, so initialize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (output == null) { pr_fprintf(pr_stderr, "
error opening output terminal for write\n"); return null; } for (;;) { if (p0) port_free(p0); p0 = getpassword(input, output, "enter new password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", c...
NSS Sample Code Utilities_1
lename, &stbuf); return stbuf.st_size; } /* * readderfromfile */ secstatus readderfromfile(secitem *der, const char *infilename, prbool ascii) { secstatus rv = secsuccess; prfiledesc *infile = null; infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "failed to open file \"%s\" (%ld, %ld).\n", infilename, pr_get
error(), pr_getos
error()); rv = secfailure; goto cleanup; } if (ascii) { /* first convert ascii to binary */ secitem filedata; char *asc, *body; /* read in ascii data */ rv = filetoitem(&filedata, infile); asc = (char *)filedata.data; if (!asc) { pr_fprintf(pr_stderr, "unable to read data from input file\n"); ...
... } else { pr_fprintf(pr_stderr, "input has header but no trailer\n"); port_free(filedata.data); rv = secfailure; goto cleanup; } } else { body = asc; } /* convert to binary */ rv = atob_convertasciitoitem(der, body); if (rv) { pr_fprintf(pr_stderr, "
error converting ascii to binary %s\n", port_get
error()); port_free(filedata.data); rv = secfailure; goto cleanup; } port_free(filedata.data); } else { /* read in binary der */ rv = filetoitem(der, infile); if (rv) { pr_fprintf(pr_stderr, "
error converting der \n"); rv = secfa...
Initialize NSS database - sample 2
= null; char *p1 = null; secupwdata *pwdata = (secupwdata *) arg; if (pwdata->source == pw_fromfile) { return filepasswd(slot, retry, pwdata->data); } if (pwdata->source == pw_plaintext) { return pl_strdup(pwdata->data); } /* open terminal */ input = fopen("/dev/tty", "r"); if (input == null) { pr_fprintf(pr_stderr, "
error opening input terminal for read\n"); return null; } /* we have no password, so initialize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (o...
...turn null; } /* we have no password, so initialize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (output == null) { pr_fprintf(pr_stderr, "
error opening output terminal for write\n"); return null; } for (;;) { if (p0) port_free(p0); p0 = getpassword(input, output, "enter new password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", c...
NSS reference
nss environment variables nss cryptographic module nss tech notes nss tech notes nss memory allocation tools based on nss tools documentation. based on nss tools man pages : work in progress ...
... nss environment variables nss cryptographic module nss tech notes nss tech notes nss memory allocation tools based on nss tools documentation. based on nss tools man pages : work in progress ...
JS::Compile
chars const char16_t * string containing the script to compile. bytes const char * string containing the script to compile. length size_t the length of chars or bytes, in characters. file file * file handle containing the function. filename const char * name of file or url containing the function. used to report filename or url in
error messages. script js::mutablehandlescript out parameter. on success, script receives the result script. description js::compile compiles a script, srcbuf, chars, bytes, or file, for execution. the script is associated with a js object. srcbuf, chars, bytes is the string containing the text of the script. length indicates the size of the text version of the script in charact...
...script, srcbuf, chars, bytes, or file, for execution. the script is associated with a js object. srcbuf, chars, bytes is the string containing the text of the script. length indicates the size of the text version of the script in characters. file is the filehandle containing the text of the script. filename is the name of the file (or url) containing the script. this information is included in
error messages if an
error occurs during compilation.. on success, js::compile stores an object representing the newly compiled script into script, and returns true. otherwise, it returns false and the value left in script is undefined. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js::compile js::evaluate js::compileoffthread js::compilefunction...
JS::Evaluate
he script to compile and execute. chars const char16_t * string containing the script to compile and execute. bytes const char * string containing the script to compile and execute. length size_t the length of chars or bytes, in characters. filename const char * name of file or url containing the script. used to report filename or url in
error messages. rval js::mutablehandlevalue out parameter. on success, if rval is not null, *rval receives the result value. description js::evaluate compiles and executes a script in the specified scope, obj or scopechain. srcbuf, chars and bytes are the string containing the text of the script. length indicates the size of the text version of the script in characters. filenam...
... *rval receives the result value. description js::evaluate compiles and executes a script in the specified scope, obj or scopechain. srcbuf, chars and bytes are the string containing the text of the script. length indicates the size of the text version of the script in characters. filename is the name of the file (or url) containing the script. this information is used in messages if an
error occurs during compilation. rval is an optional out parameter. if it is non-null, then on success, the result value is stored in *rval. this value is determined the same way as for the standard eval function. in the common case where the script is just an expression, the result value is simply the value of that expression. more generally, the result value is the value of the last-executed express...
JS::SetOutOfMemoryCallback
syntax void js::setoutofmemorycallback(jsruntime *rt, js::outofmemorycallback cb, void *data); name type description rt jsruntime * the jsruntime for which to set the gc callback. cb js::outofmemorycallback pointer to the new callback function to use. data void * data parameter which will be passed to js::outofmemorycallback. ...
...ck function to use. data void * 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 c...
JSFastNative
e the following macros to access the fields of vp: macro name description js_callee(cx, vp) returns the function object that was called, as a jsval. native methods must not call js_callee after calling js_set_rval. (the return value and the callee are stored in the same stack slot.) js_this(cx, vp) returns the this argument as a jsval, or jsval_null on
error. native methods must not call js_this after calling js_set_rval. (js_this may call js_callee.) js_this_object(cx, vp) returns the this argument as a jsobject *, or null on
error. native methods must not call js_this_object after calling js_set_rval. (js_this_object may call js_callee.) js_argv(cx, vp) returns the argv pointer. this points to element 0 of an...
...s currently in the return-value slot. js_set_rval(cx, vp, value) sets the return value of the native function. it is safe to call this multiple times within a single call to a jsfastnative. if the jsfastnative returns js_true, the last value passed to this macro will be returned to the caller. on success, the callback must call js_set_rval (at least once) and return js_true. on
error or exception, it must return js_false. to create a jsfunctionspec that points to a jsfastnative, use js_fn. when a jsfastnative is called, no jsstackframe is generated. this is what makes a fast native fast. however, it causes 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 imple...
JSNative
in spidermonkey 17. (this structure is now provided in "js/callargs.h" added in spidermonkey 24 as well as through "jsapi.h".) this structure encapsulates access to the callee function, this, the function call's arguments, and the eventual return value. on success, the callback must set js::callargs::rval() or call js_set_rval (at least once) and return true. otherwise it should either report an
error (using e.g. js_report
error or js_reportoutofmemory) or raise an exception (using js_setpendingexception), and the callback must return false. (returning false without reporting an
error or raising an exception terminates the script with an uncatchable
error. this has limited use cases; it's used to implement firefox's "slow script" dialog, for example.) when a jsnative is called, no jsstackfram...
...s generated. ...
JSProtoKey
oto_json json mxr search for jsproto_json jsproto_date date mxr search for jsproto_date jsproto_math math mxr search for jsproto_math jsproto_number number mxr search for jsproto_number jsproto_string string mxr search for jsproto_string jsproto_regexp regexp mxr search for jsproto_regexp jsproto_
error error mxr search for jsproto_
error jsproto_internal
error internal
error mxr search for jsproto_internal
error jsproto_eval
error eval
error mxr search for jsproto_eval
error jsproto_range
error range
error mxr search for jsproto_range
error jsproto_reference
error reference
error mxr search for jsproto_reference
error jspro...
... mxr search for jsproto_
error jsproto_internal
error internal
error mxr search for jsproto_internal
error jsproto_eval
error eval
error mxr search for jsproto_eval
error jsproto_range
error range
error mxr search for jsproto_range
error jsproto_reference
error reference
error mxr search for jsproto_reference
error jsproto_syntax
error syntax
error mxr search for jsproto_syntax
error jsproto_type
error type
error mxr search for jsproto_type
error jsproto_uri
error uri
error mxr search for jsproto_uri
error jsproto_iterator iterator mxr search for jsproto_iterator jsproto_stopiteration stopiteration mxr search for jsproto_stopiteration jsproto_arraybuff...
JS_AlreadyHasOwnProperty
namelen size_t (in js_alreadyhasownucproperty only) the length of name, in characters; or the special value (size_t) -1 to indicate that name is null-terminated. index uint32_t (in js_alreadyhasownelement only) the index of the element to search for. foundp bool * out parameter. *foundp receives true if the property is found or false if it is not found. if an
error occurs, the value left in *foundp is undefined. description these functions attempt to determine whether a property already exists on a specific jsobject without modifying the object. by design, this search may not find a property that other property lookup functions, such as js_lookupproperty, would find. for native objects—objects whose properties are stored in the default data structur...
... this calls the jsobjectops.lookupproperty hook. *foundp is set to true only if lookupproperty reports that the property was found on obj itself and not on some other object (even the corresponding outer object, if any). if the property is found on obj, this sets *foundp to true and returns true. if the property is not found on obj, this sets *foundp to false and returns true (to indicate that no
error occurred). if the search fails with an
error or exception, this 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_CompileFunctionForPrincipals
function. argnames const char ** names to assign to the arguments passed to the function. body const char * or const jschar * string containing the source code of the function to compile. length size_t the length, in characters, of body. filename const char * name of file or url containing the function. used to report filename or url in
error messages. lineno unsigned int line number. used to report the offending line in the file or url if an
error occurs. description js_compilefunctionforprincipals compiles a security-enabled function from a text string, bytes, and associates it with a js object, obj. js_compileucfunctionforprincipals is the unicode version of the function. principals is a pointer to the jspri...
...gnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. body is the string containing the source code of the function. length is the length of the string in characters. filename 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 f...
JS_CompileScriptForPrincipals
s associated. principals jsprincipals * pointer to the structure holding the security information for this script. src const char * or const jschar * string containing the script to compile. length size_t the length of src, in characters. filename const char * name of file or url containing the function. used to report filename or url in
error messages. lineno unsigned int line number. used to report the offending line in the file or url if an
error occurs. version jsversion javascript version for the script. description js_compilescriptforprincipals compiles a security-enabled script, src, for execution. js_compileucscriptforprincipals is the unicode version of the function. the script is associat...
...sion of the function. the script is associated with a js object. principals is a pointer to the jsprincipals structure that contains the security information to associate with this script. src is the string containing the text of the script. length indicates the length of the script, in characters. filename is the name of the file (or url) containing the script. this information is included in
error messages if an
error occurs during compilation. 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 scrip...
JS_CompileUTF8FileHandle
ls); name type description cx jscontext * the context in which to compile the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object with which the script is associated. filename const char * filename to associate with the compiled script. this filename is used for
error messages. it should be the name of the file that contains the script, if available. file file * the file handle containing the script to compile. principals jsprincipals * (only in js_compileutf8filehandleforprincipals) the security principals to associate with the new script, or null. description js_compileutf8filehandle reads a script from a stdio file hand...
...ame is the name of the file containing the script to compile. file is the file handle. js_compileutf8filehandle does not close the file handle. if principals is non-null, it points to a jsprincipals object that is associated with the new script and any functions it creates. on success, js_compileutf8filehandle reads file to eof and returns an object representing the newly compiled script. if an
error occurs during compilation, js_compileutf8filehandle stops reading from the file and returns null. js_compileutf8filehandle and js_compileutf8filehandleforprincipals are deprecated, use file, use js::compile instead. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compileutf8filehandle js::compile js_decompilescript js::evaluate js_execute...
JS_ConvertValue
perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handlevalue the value to convert. type jstype the type to which the value is to be converted. type must be one of jstype_void, jstype_object, jstype_function, jstype_string, jstype_number, or jstype_boolean. otherwise js_convertvalue reports an
error. vp js::mutablehandlevalue out parameter. on success, *vp receives the converted value. description js_convertvalue converts a javascript value, v, to the specified type. on success, the converted value is stored in *vp. typically users of this function set vp to point to v, so that if conversion is successful, v now contains the converted value. js_convertvalue calls othe...
...is a function object that has not been stripped of its lexical scope. it is safe to call the result (e.g. using js_callfunctionvalue). converting to jstype_string works like js::tostring. converting to jstype_number works exactly like js::tonumber. converting to jstype_boolean works exactly like js::toboolean. on success, js_convertvalue stores the converted value in *vp and returns true. on
error or exception, it returns false, and the value left in *vp is undefined. see also mxr id search for js_convertvalue js_convertarguments js_gettypename js_typeofvalue bug 1125784 ...
JS_EncodeCharacters
h encoded characters; or null. the caller is responsible for allocating and freeing this buffer. dstlenp size_t * in/out parameter. on entry, if dst is non-null, *dstlenp must be the length of the destination string in 16-bit units. on success, *dstlenp receives the length of the converted string, in bytes. on failure, *dstlenp receives the number of bytes written to dst before the
error occurred. description js_encodecharacters copies the characters of a jschar array into a char array, converting the 16-bit values to 8-bit values. if spidermonkey was built with js_c_strings_are_utf8 defined or js_setcstringsareutf8 was called, the string is converted to utf-8. otherwise each character is simply truncated to 8 bits. if utf-8 is turned on, the length of the encoded string m...
...t == null) return js_false; /* convert characters to bytes. */ js_encodecharacters(cx, src, srclen, dst, &dstlen); /* use the converted bytes for something. */ ... /* remember to free the bytes afterwards. */ js_free(cx, dst); return js_true; on success, js_encodecharacters sets *dstlenp to the real result length and returns js_true. otherwise it reports an
error and returns js_false. this happens if the destination is too small for the resulting string or if the source buffer isn't proper utf-16 because it contains unpaired surrogate values. the user is responsible for allocating and freeing the memory of the destination string. js_encodecharacters never adds a trailing null character. to obtain a null-terminated string, allocate an extra byte for the n...
JS_EvaluateScript
object * the scope in which to execute the script. this parameter is documented in detail at js_executescript. src const char * or const jschar * string containing the script to compile and execute. length unsigned int the length of src, in characters. filename const char * name of file or url containing the script. used to report filename or url in
error messages. lineno unsigned int line number. used to report the offending line in the file or url if an
error occurs. rval jsval * out parameter. on success, if rval is not null, *rval receives the result value. description js_evaluatescript compiles and executes a script in the specified scope, obj. js_evaluateucscript is the unicode version of the function. ...
...ue. description js_evaluatescript compiles and executes a script in the specified scope, obj. js_evaluateucscript is the unicode version of the function. src is the string containing the text of the script. length indicates the size of the text version of the script in characters. filename is the name of the file (or url) containing the script. this information is used in messages if an
error occurs during compilation. similarly, lineno is used to report the line number of the script or file where an
error occurred during compilation. rval is an optional out parameter. if it is non-null, then on success, the result value is stored in *rval. this value is determined the same way as for the standard eval function. in the common case where the script is just an expression, the result va...
JS_EvaluateScriptForPrincipals
als jsprincipals * pointer to the structure holding the security information for this script. src / bytes / chars const char * or const jschar string containing the script to compile and execute. length unsigned int the length of src, in characters. filename const char * name of file or url containing the script. used to report filename or url in
error messages. lineno unsigned int line number. used to report the offending line in the file or url if an
error occurs. rval jsval * out parameter. on success, *rval receives the value from the last-executed expression statement in the script. version jsversion javascript version for the script. description js_evaluatescriptforprincipals compiles a...
...cscriptforprincipals is the unicode version of the function. principals is a pointer to the jsprincipals structure that contains the security information to associate with this script. src is the string containing the text of the script. length is the length of the script, in characters. filename is the name of the file (or url) containing the script. this information is used in messages if an
error occurs during compilation. similarly, lineno is used to report the line number of the script or file where an
error occurred during compilation. if the script compiles and executes successfully, *rval receives the value from the last-executed expression statement processed in the script, and js_evaluatescriptforprincipals or js_evaluateucscriptforprincipals returns js_true. otherwise it returns ...
JS_GetProperty
operty is the unicode version of the function. js_getpropertybyid is the same but takes a js::handleid for the property name. in the simplest case, js_getproperty stores the value of the property in *vp and returns true. however, several different hooks can affect property gets. the full algorithm is described below. details first, a property lookup is performed. if the lookup proceeds without
error, exactly one of the following cases applies: if the property is not found, then *vp is set to undefined. then the jsclass.getproperty hook of obj's class is called with the arguments (cx, obj, id, vp). for many objects, including objects of standard classes such as object and array, this hook does nothing and returns true, so the property get succeeds and undefined is left in *vp. if the prop...
...ies, the getter does nothing and returns true, so the property get succeeds and the property's stored value is left in *vp. internally, property retrieval, including all the behavior described above, is implemented by obj's jsobjectops.getproperty callback. on success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and return true. on an
error or exception, these functions return 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_InstanceOf
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. obj js::handle<jsobject*> object to test. clasp jsclass * class against which to test the object. args js::callargs * optional pointer to arguments. if non-null, report an
error if obj is not of type clasp. added in spidermonkey 38 argv jsval * optional argument vector. if non-null, report an
error if obj is not of type clasp. argv must be the argv argument passed from the engine to a jsnative callback, js_argv(cx, rv) in a jsfastnative callback, or null. obsolete since jsapi 32 description js_instanceof can be used to check whether an object obj i...
...(obj) == clasp. js_instanceof can also be used in native functions to check the class of an argument when a particular class is required. to use it this way, pass the arguments provided by the engine for args with js::callargsfromvp(argc, vp). when args is non-null, js_instanceof behaves as follows. if obj is of the given class, it returns true. otherwise, it returns false; it also reports a type
error containing the function's name. note that js_instanceof is not the equivalent of the javascript instanceof keyword, which examines constructor properties along the prototype chain. js_hasinstance is similar to instanceof. see also mxr id search for js_instanceof js_hasinstance js_getclass bug 959787 ...
JS_LookupProperty
given name. these functions all have similar behavior: the search starts with obj and proceeds along the prototype chain. if the property is found, *vp receives the property's stored value, or true if the property has no stored value; and the return value is true. if neither obj nor any of its prototypes have such a property, *vp receives undefined and the return value is true (to indicate no
error occurred). on
error or exception (such as running out of memory during the search), the return value is false, and the value left in *vp is undefined. there is no way to tell the difference 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_l...
...ame) ..." or "obj.name ? ... : ...". objects may pretend that the property does not exist when this flag is set. for example, mozilla's document.all property is hidden in this way. jsresolve_declaring behave as though the name were being declared in a var, const, or function declaration. jsresolve_classname search for the initial value of a standard class such as object, array, or
error. do not automatically infer and enable other flags by looking at the currently executing bytecode. notes js_lookupproperty does not distinguish between a property with a value of undefined and a property that does not exist. use js_getpropertyattributes to distinguish these cases. js_lookupproperty differs from js_getproperty in that js_lookupproperty does not invoke the get handler for the prop...
JS_ReportPendingException
forward the current pending exception in a given jscontext to the current js
errorreporter callback. syntax bool js_reportpendingexception(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_reportpendingexception converts the exception to a string and reports it to the current
error reporter. on success, it clears the exception as though by calling js_clearpendingexception and returns true. if no exception is pending, or if a second
error occurs while trying to report the first one, it returns false. this function can be used to catch exceptions thrown fr...
...ortpendingexception converts the exception to a string and reports it to the current
error reporter. on success, it clears the exception as though by calling js_clearpendingexception and returns true. if no exception is pending, or if a second
error occurs while trying to report the first one, it returns false. this function can be used to catch exceptions thrown from scripts and send them to the
error reporter to be logged or ignored. note that certain jsapi functions automatically do this for uncaught exceptions; see "automatic handling of uncaught exceptions" in the jsapi user guide. see also mxr id search for js_reportpendingexception ...
JS_SetOptions
gs); // turn off those extra warnings js_setoptions(cx, js_getoptions(cx) & ~jsoption_extra_warnings); the options parameter and the return value are the logical or of zero or more constants from the following table: option description jsoption_extra_warnings warn on dubious practice. mxr id search for jsoption_extra_warnings jsoption_w
error convert warnings to
errors. mxr id search for jsoption_w
error jsoption_varobjfix make js_evaluatescript() use the last object on its obj param's scope chain (that is, the global object) as the ecma "variables object". this flag is recommended. without it, the two scripts "x = 1" and "var x = 1", where no variable x is in scope, do two different t...
... 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 function () {} in statement con...
JS_ValueToFunction
o any global or enclosing scope, and therefore must not be treated like a real function. instead, use jsval_is_object and js_objectisfunction() to check whether a value is already a function, or use js_convertvalue() to convert a value to jstype_function safely. if v is a function object, this returns the associated jsfunction. ...
...pe
error is 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
ip int32 * out parameter. on success, *ip receives the converted integer value. description js_valuetoint32 converts a specified js value, v, to a 32-bit signed integer (-2147483648 to 2147483647). first it converts v to a floating-point number as if by calling js::tonumber. if the result is nan, an infinity, or a number outside the 32-bit range, js_valuetoint32 reports an
error and conversion fails. otherwise, the floating-point number is rounded to the nearest integer value. on success, js_valuetoint32 stores the converted value in *ip and returns js_true. on
error or exception, it returns js_false, and the value left in *ip is undefined. js_valuetoint32 is pre-ecma-262 edition 1, and rounds differently than js_valuetoecmaint32 and js::toint32. this routine was added...
...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, while this routine rounds by adding 0.5 to the converted float-point number and truncating the result at the decimal point. js::toint32 will also convert nan (and anything that converts to nan, such as an array of strings) to 0, whereas this routine would report an
error. see also js_convertarguments js::toint32 bug 933946 ...
JS_ValueToNumber
, or true, conversion succeeds, and the result is nan, 0, 0, or 1 respectively. if v is a string, conversion proceeds as specified in ecma 262-3 §9.3.1. js_valuetonumber always succeeds in this case, returning js_true. if the string is not a numeric string, *dp is set to nan. otherwise v is an object. js_valuetonumber carries out the following steps to convert it to a number. if at any step an
error or 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,...
...ch simply calls v.valueof() if present. if the convert callback produces a primitive value, the value is converted to a number as described above and conversion succeeds. otherwise, the resulting object's tostring method, if any, is called. if that produces a primitive value, the value is converted to a number as described above and conversion succeeds. otherwise conversion fails with a type
error. 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
ngly. if v is a number, conversion succeeds, and the result is a string representation of that number as specified in ecma 262-3 §9.8.1. this might be "nan", "infinity", or "-infinity". otherwise the result is a decimal representation of the number, possibly using 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 js...
...onverted to a string as described above and conversion succeeds. otherwise, the resulting 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 type
error. 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 ...
JS_malloc
nd free memory that is not managed by the garbage collector. syntax void * js_malloc(jscontext *cx, size_t nbytes); void * js_realloc(jscontext *cx, void *p, size_t oldbytes, size_t newbytes); char * js_strdup(jscontext *cx, const char *s); void js_free(jscontext *cx, void *p); name type description cx jscontext * pointer to a js context. if allocation fails, an
error is reported in this context. p void * (js_realloc and js_free only) pointer to a previously allocated region of memory to resize or deallocate. nbytes size_t (js_malloc and js_realloc only) amount of space, in bytes, to allocate. s const char * (js_strdup only) pointer to a null-terminated string. s must not be null. description js_malloc allocat...
...ewly allocated space is uninitialized. js_realloc(cx, null, nbytes) behaves exactly like js_malloc(cx, nbytes). when p is not null, js_realloc(cx, p, 0) behaves like js_free(cx, p) and returns null. js_strdup allocates a copy of the null-terminated string s. on success, it returns a pointer to the copy. if any of these three functions fails to allocate the required amount of memory, it reports an
error as though by calling js_reportoutofmemory(cx) and returns null. js_free deallocates a region of memory allocated a previous call to js_malloc, js_realloc, or js_strdup. if p is null, js_free does nothing. once the region of memory is freed, the application must not use it again. for js_realloc and js_free, if p is non-null, cx must be associated with the same runtime as the context used to alloca...
Property attributes
js_fs, and js_fn flag description jsprop_enumerate the property is visible to javascript for...in and for each ... in loops, as well as to js_enumerate. this is the inverse of the ecma standard dontenum attribute. mxr id search for jsprop_enumerate jsprop_readonly the property's value cannot be set. ...
...in javascript 1.3 and higher, as in ecmascript, such attempts are ignored. this is the ecma standard dontdelete attribute. the javascript language does not provide any way for a script to delete a permanent property. ...
SpiderMonkey 1.8.5
t are easier to use correctly. js_newdouble, js_newdoublevalue, and js_newnumbervalue are gone. instead use double_to_jsval, int_to_jsval, and uint_to_jsval, which are faster and can't fail. js_getstringbytes and js_getstringchars are gone. there is no longer an infallible way to examine string characters. applications must use js_getstringcharsandlength or js_encodestring/js_free and check for
errors. these and other changes are explained in detail below. new javascript language features javascript 1.8.5 adds support for ecmascript edition 5, including es5 strict mode. for details, see new in javascript 1.8.5. note that there are a very small number of incompatibilities between es5 and and es3, the version of ecmascript supported by spidermonkey versions 1.5 through 1.8. these are discusse...
...ases the need to explicitly root gc things or use the "root as you go" approach popular with earlier spidermonkey releases. since this is a conservative collector, it will often find "garbage" addresses which can trigger warnings from certain code analysis tools. if you are running valgrind on your embedding, be sure to build spidermonkey with the --enable-valgrind option to suppress superflous
error messages triggered by the garbage collector. this also means that objects will be finalized in a non-deterministic order in spidermonkey 1.8.5. this is not a bug, and, any embedding which depends upon deterministic finalization is fatally flawed. typed rooting api the rooting api has been changed from an
error-prone void ** interface to an interface which accepts pointers to specific types. js_...
SpiderMonkey 1.8
pplications that share objects among threads in such a way that two threads could access an array, iterator, or generator object at the same time should not use spidermonkey 1.8. there is a minor known bug in the new javascript 1.8 functionality. when javascript 1.8 support is enabled, the parser accepts some incorrect programs by inserting a semicolon where it should instead throw a syntax
error (bug 384758). this bug will be fixed in 1.8.1. migrating to spidermonkey 1.8 spidermonkey 1.8 is not binary-compatible with previous releases. it is source-compatible with spidermonkey 1.7 though, which means you can probably just recompile and relink your application. a handful of changes are not backwards-compatible: the result of assigning to a property with a setter has changed (bug 312...
...plementation 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 appear, such as in the argument to eval(). functions that were js_threadsafe-only in spidermonkey 1.7 (js_beginrequest, for example) are now present, but do nothing, in non-js_threadsafe builds. this is to help applications share and reuse code regardless of whether they use threads. there a...
TPS Tests
t_modify list are present; i.e., all the changes performed in profile2 have successfully been synced to profile1. lastly, firefox closes and the tests ends. (implementation detail) two final cleanup phases are run to wipe the server state and unregister devices. troubleshooting and debugging tips for writing and running tps tests tps evaluates the whole file in every phase, so any syntax
error(s) in the file will get reported in phase 1, even though the
error may not be in phase 1 itself. inspect tps.log. when a tps test fails, the log is dumped to tps.log in the virtualenv. inspect about:sync-log. every sync should have a log and every item synced should have a record. run runtps with --debug. this will enable much more verbose logging in all engines. check the tps.log file writte...
...tate manually. using this technique in conjunction with aboutsync is helpful. (note that the python testrunner will generally still kill firefox after a tps test runs for 5 or so minutes, so it's often helpful to kill the python testrunner outright, and then use aboutsync in a different instance of the browser). a tps failure may not point directly to the problem. for example, most
errors involving bookmarks look like "places item not found in expected index", which could mean a number of issues. the other engines are similarly unhelpful, and will likely fail if there's any problem, without really indicating what the problem is. it's common for the phase after the problem to be the one reporting
errors (e.g. if one phase doesn't upload what it should, we won't notice until the...
Secure Development Guidelines
-designed api when using integers as array indexes, use caution format string bugs example: int main(int argc, char *argv[]) { if (argc > 1) printf(argv[1]); } format string bugs: prevention easy to fix: always use a format string specifier: int main(int argc, char *argv[]) { if (argc > 1) printf("%s", argv[1]); } double free example: void* ptr = malloc(1024); if (
error) { free(ptr); } free(ptr); double free: prevention set a pointer to null when it’s freed valgrind or malloc debugging can help detect those bugs use after free accessing data after a free() or delete can lead to undefined behavior some debug tools might be able catch some cases un-initialized data example: int main() { char *uninitialized_ptr; printf("0x%08x\r...
...havior some debug tools might be able catch some cases un-initialized data example: int main() { char *uninitialized_ptr; printf("0x%08x\r\n", uninitialized_ptr); return 0; } $ ./test 0x8fe0103 un-initialized data: prevention initialize your variables! ...
Places Developer Guide
e is the time at which the visit occurred, in microseconds. }, onitemmoved: function(id, oldparent, oldindex, newparent, newindex) { // oldparent and newparent are the ids of the old and new parent folders of the moved item. }, queryinterface: function(iid) { if (iid.equals(ci.nsinavbookmarkobserver) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_
error_no_interface; }, }; // register the observer with the bookmarks service var bmsvc = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); bmsvc.addobserver(observer, false); // un-register the observer when done. bmsvc.removeobserver(observer); html import/export the nsiplacesimportexportservice service is used for import and export of bookma...
...the service is uri-centric, meaning that consumers can tag uris directly, without first creating a bookmark. the unique identifier is the uri, and all apis require uris as nsiuri objects. // get the tagging service var tagssvc = cc["@mozilla.org/browser/tagging-se...
Aggregating the In-Memory Datasource
aggregation to the rescue! here are the gory details on how. when it won't work although this magic is terribly convenient to use, it won't work in the case that you want to "override" some of the in-memory datasource's methods. for example, while writing the bookmarks datasource, i wanted to be able to trap assert() to enforce the ...
... it willforward the query interface to its "outer" (which is "us"). this preserves the symmetrical property of queryinterface(). ...
How to build an XPCOM component in JavaScript
rder to be registered and used within mozilla applications. the compilation can be done using the gecko sdk. you can learn how to get mac, linux, and windows versions of the gecko sdk by reading the article gecko sdk. for code outside the tree note: on windows if you download the gecko sdk without the whole build tree, you will be missing some required dlls for xpidl.exe and it will run with no
errors but not do anything. to fix this download the mozilla build tools for windows and copy the dlls from windows\bin\x86 within the zip into the bin directory of the gecko sdk. note: the mac version of the sdk provided for download is powerpc-only. if you need an intel version, you'll need to compile it yourself as described on that page. execute this command to compile the typelib. here, {sdk_dir...
...the class constructor, and you removed the "[components.interfaces.nsihelloworld]" argument for the call to xpcomutils.generateqi() in queryinterface, then you can access your component like this: try { var mycomponent = components.classes['@dietrich.ganx4.com/helloworld;1'] .getservice().wrappedjsobject; alert(mycomponent.hello()); } catch (an
error) { dump("
error: " + an
error); } for more information about wrappedjsobject, see here. using xpcom instantiation try { var mycomponent = components.classes['@dietrich.ganx4.com/helloworld;1'] .createinstance(components.interfaces.nsihelloworld); alert(mycomponent.hello()); } catch (an
error) { dump("
error: " + an
error); } ot...
Component Internals
tion a last chance to clean up any leftovers before they are released. in order to support something like an "are you sure you want to quit" dialog, the application needs to provide a higher-level event (e.g., startshutdown()) which allows for cancellation. note also that xpcom services may deny you access once you have received the shutdown notification. it is possible that xpcom will return an
error if you access the nsiservicemanager at that point, for example, so you may have to keep a reference-counted pointer to the service you are interested in using during this notification. component loaders components can be written in many languages. so far this book has been focusing on "native components," shared libraries exporting a nsgetmodule symbol. but if there is a component loader for j...
...crash along with a version change. the glue library in general, you should avoid any interfaces, symbols in xpcom, or other part of gecko libraries that aren't frozen. however, there are some unfrozen tools in xpcom that are used so often they are practically required parts of component programming. the smart pointer class, nscomptr, for example, which makes reference counting less tedious and
error-prone, is not actually frozen, and neither is nsdebug, a class for aiding in tracking down bugs, nor is nsmemory, a class to ensure that everyone uses the same heap, generic factory, and module. instead of asking every developer to find and copy these various files into their own application, xpcom provides a single library of "not-ready-to-freeze-but-really-helpful" classes that you can link int...
Finishing the Component
signature. however, when this same component is used in a gecko installation where this interface has changed, the method testa does not exist in the nsifoo interface; the first entry in the v-table is in fact isprime(). when this method call is made, the code execution treats the isprime method as testa. needless to say, this is a bad thing. furthermore, there is no way easy way to realize this
error at runtime. gecko developers could change the interface's iid, and some do. this can prevent many
errors like this. but unfrozen interfaces are not supported in any formal way, and relying upon a different iid for any change in the interface is not a good idea either. when using frozen interfaces, you are guaranteed compatibility with future versions of gecko. the only trouble occurs when the...
...intro to the html 4 specification for more information about relative urls. here is the complete implementation of the shouldload() method: ns_imethodimp weblock::shouldload(print32 contenttype, nsiuri *contentlocation, nsisupports *ctxt, nsidomwindow *window, prbool *_retval) { if (!contentlocation) return ns_
error_failure; nsembedcstring scheme; contentlocation->getscheme(scheme); if (strcmp("http", scheme.get()) != 0 && strcmp("https", scheme.get()) != 0 && strcmp("ftp", scheme.get()) != 0) { // this isn't a type of uri that we deal with *_retval = pr_true; return ns_ok; } nsembedcstring hosttoload; contentlocation->gethost(hosttoload); // assume failure. d...
Introduction to XPCOM for the DOM
this document is an introduction to the use of xpcom in the context of the dom code. the use of xpcom and nscomptr's described in this document covers about 80% of what you need to know to read the dom code, and even write some. for more advanced topics, please see the xpcom page. the tracking bug for this document is bug 99592. target audience: people who would like a quick introduction to the use of c++ and xpcom in the dom code. the understanding of the content of this document is a requirement to read the rest of the dom hacking guide. ...
...nctions. the first one is the most straightforward. the functions we have to implement are nshtmldocument::fabian() and nshtmldocument::getneat(). so let's just code them. ns_imethodimp nshtmldocument::fabian(void) { printf("hello from the nsidomfabian interface\n"); // whatever you want... return ns_ok; } ns_imethodimp nshtmldocument::getneat(prbool *aneat) { if(!aneat) { return ns_
error_null_pointer; } nsresult rv = fabian(); if( rv == ns_ok ) { *aneat = pr_true; } else { *aneat = pr_false; } return ns_ok; } this code is of course written in nshtmldocument.cpp. the functions are very simple, but it is only a proof-of-concept. a second possibility is to use the "interface forwarding macro". this macro is also auto-generated by the xpidl compiler. below is t...
Components.isSuccessCode
. an xpcom return code indicates 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 ...
... onstoprequest: function(request, context, statuscode) { copyinprogress = false; // did the copy fail? ...
Components.results
components.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at table of
errors), with the value of each corresponding to that constant's value. introduction components.results is an object whose properties are the names of well-known xpcom result codes, with each value being that of the corresponding result code. elements in this array can be used to test against unknown nsresult variables or they can be 'thrown' to indicate failure... if(something_unexpected_happened) throw components.results.ns_
error_unexpected; the elements of the components.results object can be enumerated using a for-in loop. usage implementing nsisupports the standard nsisupports is usually implemented in java...
...by using components.results to get a failure return value if does not implement the given interface. note the common use of an abbreviation for components.results, cr: const ci = components.interfaces, cr = components.results; function class() { /* ... */ } class.prototype = { /* ... */ queryinterface: function(id) { if (id.equals(ci.imyinterface)) return this; throw cr.ns_
error_no_interface; } }; ...
Components.utils.cloneInto
add-on script can define an object, clone it, and pass it into this function: // add-on script var addonscriptobject = {"message" : "hello from add-on"}; contentwindow.foo(cloneinto(addonscriptobject, contentwindow)); // "they said: hello from add-on" cloning objects that have functions if the object to be cloned contains functions, you must pass the {clonefunctions:true} flag or you'll get an
error. if you do pass this flag, then functions in the object are cloned using the same mechanism as that used in components.utils.exportfunction: // add-on script var addonscriptobject = { greetme: function() { alert("hello from add-on"); } }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, ...
... {clonefunctions: true}); // page script var test = document.getelementbyid("test"); test.addeventlistener("click", function() { window.addonscriptobject.greetme(); }, false); cloning objects that contain dom elements by default, if the object you clone contains objects that are reflected from c++, such as dom elements, the cloning operation will fail with an
error. if you pass the {wrapreflectors:true} flag, then the object you clone is allowed to contain these objects: // add-on script var addonscriptobject = { body: contentwindow.document.body }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, {wrapreflectors: true}); // page script va...
Components.utils.import
ilerplate in your component files. see using javascript code modules for more details. note: prior to gecko 2.0, javascript code modules could only be loaded using file: or resource: urls. gecko 2.0 adds support for loading modules from chrome: urls, even those inside jar archives. syntax components.utils.import(url [, scope]); // or, if you use a tool such as jslint which reports compiler
errors for the above, components.utils["import"](url [, scope]); parameters url a string of the url of the script to be loaded. the url must point to a file on the disk, possibly in a jar. scope an optional object to import onto; if omitted, the global object is used. under boot2gecko, the scope is not optional. if your code is meant to work on all platforms, you should always provide a scop...
... under boot2gecko, the scope is not optional. if your code is meant to work on all platforms, you should always provide a scope. in case of doubt, this is generally a good scope. return value the module's global object. use of the return value is discouraged since it grants access to the module's internal properties which are not part of its public api. import throws if it encounters an
error (like a syntax
error) in the file it reads. example components.utils.import("resource://gre/modules/xpcomutils.jsm", this); difference from mozijssubscriptloader the differences from mozijssubscriptloader: the behavior when importing/loading the same code from different locations: the subscript loader evaluates the specified code each time it is invoked, with the caller's global object. ...
Components object
provides access to the value of the methodjit property in the javascript environment. utils.methodjit_always obsolete since gecko 24.0 provides access to the value of the methodjit_always property in the javascript environment. utils.relimit provides access to the value of the relimit property in the javascript environment. utils.report
error reports a javascript
error object to the
error console. utils.scheduleprecisegc requests that garbage collection occur sometime in the future when no javascript code is running; accepts a callback function to receive notification once collection is complete. utils.setgczeal() sets the gc zeal level for the context. utils.strict prov...
... requests that garbage collection occur sometime in the future when no javascript code is running; accepts a callback function to receive notification once collection is complete. utils.setgczeal() sets the gc zeal level for the context. utils.strict provides access to the value of the strict property in the javascript environment. utils.w
error provides access to the value of the w
error property in the javascript environment. utils.sandbox creates sandbox objects for use with evalinsandbox. utils.xml provides access to the value of the xml property in the javascript environment. ...
NS_NewLocalFile
ance of nsilocalfile that provides a platform independent representation of a file path. #include "nsxpcom.h" #include "nsilocalfile.h" nsresult ns_newlocalfile( const nsastring& apath, prbool afollowlinks, nsilocalfile** aresult ); parameters apath [in] a utf-16 string object that specifies an absolute filesystem path. this path does not need to reference an existing file. it is an
error to pass a relative filesystem path. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly c...
...cally resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly created nsilocalfile instance. return values the ns_newlocalfile function returns ns_ok if successful. otherwise, it returns an
error code. ns_
error_file_unrecognized_path indicates that the specified path is invalid. this
error is returned if a relative file path is passed to ns_newlocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newlocalfile(nse...
NS_NewNativeLocalFile
ude "nsilocalfile.h" nsresult ns_newnativelocalfile( const nsacstring& apath, prbool afollowlinks, nsilocalfile** aresult ); parameters apath [in] a string object that specifies an absolute filesystem path. this string should be encoded using ascii or the multibyte character coding corresponding to the native filesystem. this path does not need to reference an existing file. it is an
error to pass a relative filesystem path. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly c...
...resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly created nsilocalfile instance. return values the ns_newnativelocalfile function returns ns_ok if successful. otherwise, it returns an
error code. ns_
error_file_unrecognized_path indicates that the specified path is invalid. this
error is returned if a relative file path is passed to ns_newnativelocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. if you use this function on windows 2000 or later, you would not be able to handle file names containing characters outside th...
NS ConvertASCIItoUTF16 external
he string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
NS ConvertUTF16toUTF8 external
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
NS ConvertUTF8toUTF16 external
he string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
PromiseFlatCString (External)
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
PromiseFlatString (External)
he string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsACString (External)
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsAString (External)
ce of a character in a string. @return the offset of the character from the beginning of the string, or -1 if not found. ...
...ring, or -1 if not found. parameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
nsAutoString (External)
he string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsCAutoString (External)
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsCStringContainer (External)
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsCString external
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsDependentCString external
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsDependentCSubstring external
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsDependentString external
he string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsDependentSubstring external
he string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsLiteralCString (External)
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsLiteralString (External)
of the string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsStringContainer (External)
he string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
nsString external
he string, or -1 if not found. ...
... void appendint(int, print32) - source append a string representation of a number. ...
mozIAsyncFavicons
iven page, if any. void getfaviconurlforpage( in nsiuri apageuri, in nsifavicondatacallback acallback ); parameters apageuri uri of the page whose favicon uri and data we're looking up. acallback this callback is always invoked to notify the result of the lookup. the auri parameter will be the favicon uri, or null when no favicon is associated with the page or an
error occurred while fetching it. if auri is not null, the other parameters may contain the favicon data. however, if no favicon data is currently associated with the favicon uri, adatalen will be 0, adata will be an empty array, and amimetype will be an empty string. setandfetchfaviconforpage() declares that a given page uses a favicon with the given uri and attempts to fetch and save the icon data b...
...the icon unless aforcereload is true. similarly, if the icon is in the failed favicon cache we will not do anything unless aforcereload is true, in which case we'll try to reload the favicon. this function will only save favicons for "good" uris, as defined by what gets added to history or is a bookmark. for "bad" uris, this function will succeed but do nothing. this function will also ignore the
error page favicon uri (see favicon_
errorpage_url in nsifaviconservice.idl). icons that fail to load will automatically be added to the failed favicon cache, and this function will not save favicons for non-bookmarked uris when history is disabled. note: this function is identical to nsifaviconservice.setandloadfaviconforpage() void setandfetchfaviconforpage( in nsiuri apageuri, in nsiuri afavic...
mozIStorageStatement
ns a new mozistoragebindingparamsarray object that can be used to bind multiple values to parameters in preparation for calling executeasync(). mozistoragebindingparamsarray newbindingparamsarray(); parameters none. bindparameters() binds all the parameters in the specified array to the statement in preparation for calling executeasync(). note: starting in gecko 2.0, this method returns ns_
error_unexpected if the specified mozistoragebindingparamsarray is empty. void bindparameters( in mozistoragebindingparamsarray aparameters ); parameters aparameters the mozistoragebindingparamsarray object containing one or more mozistoragebindingparams objects with the parameters to be bound to the statement prior to execution. bindutf8stringparameter() binds a utf8string to the specified...
...eters. the optional callback routine receives notifications about the progress of the query. for sample code and more details, see the overview document. note: the statement does not have to be reset before being reused. mozistoragependingstatement executeasync( [optional] mozistoragestatementcallback acallback ); parameters acallback a callback object that will be notified of progress,
errors, and query completion. this parameter is optional. return value a mozistoragependingstatement object that can be used to cancel the execution of the statement. executestep() executes a query with the currently bound parameters, and steps through the results one row at a time. for sample code and more details, see the overview document. note: the statement must be reset before being reused.
mozIVisitInfoCallback
toolkit/components/places/public/moziasynchistory.idlscriptable this interface provides callback handling functionality for moziasynchistory.updateplaces() 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) method overview void handle
error(in nsresult aresultcode, in moziplaceinfo aplaceinfo); void handleresult(in moziplaceinfo aplaceinfo); void oncomplete(in nsresult aresultcode, in moziplaceinfo aplaceinfo);obsolete since gecko 8.0 methods handle
error() called when a moziplaceinfo couldn't be processed. void handle
error( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult indicating the reason wh...
..., title change, or guid change when passed to moziasynchistory.updateplaces(). void oncomplete( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult of the change indicating success or failure reason. aplaceinfo the information that was being entered into the database. notes this method was replaced by the separate handleresult() and handle
error() methods in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). see also mozivisitinfo moziasynchistory ...
GetAccessibleRelated
is 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). ...
...essible getaccessiblerelated( in unsigned long arelationtype ); parameters arelationtype[in] the relation type between the accessible (see constants listed in relations documentation). return value returns an accessible which is related to the one provided by the given relation type. ...
nsIAccessibleHyperText
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 index, otherwise -1.
...he 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 nsiaccessiblehyperlink ...
nsIAccessibleImage
ame 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. ...
...n. 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
onstant 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 if the current chil...
...); 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. ...
nsIAlertsService
latforms. 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.showalertnotification...
...", "alerts service test", "click me", true, "cookie", listener, ""); } catch (e) { // this can fail on mac os x } example 2 this example shows how to use all the available observer topics: var as = cc['@mozilla.org/alerts-service;1'].getservice(ci.nsialertsservice); var notiflistener = { observe: function(asubject, atopic, adata) { console.
error('incoming notification observer:', asubject, atopic, adata); if (atopic == 'alertclickcallback') { console.
error('user clicked trying to throw click'); services.prompt.alert(services.wm.getmostrecentwindow('navigator:firefox'), 'focus firefox', 'will now focus fireox and then focus the tab'); } else if (atopic == 'alertshow') { console.log('j...
nsIAsyncInputStream
methods asyncwait() asynchronously wait for the stream to be readable or closed. the notification is one-shot, meaning that each asyncwait call will result in exactly one notification callback. after the oninputstreamready event is dispatched, the stream releases its reference to the nsiinputstreamcallback object. it is safe to call asyncwait again from the notificat...
... the stream is closed, the stream's status cannot be changed. any successful status code passed to this method is treated as ns_base_stream_closed, which has an effect equivalent to nsiinputstream.close(). note: this method exists in part to support pipes, which have both an input end and an output end. if the input end of a pipe is closed, then writes to the output end of the pipe will fail. the
error code returned when an attempt is made to write to a "broken" pipe corresponds to the status code passed in when the input end of the pipe was closed, which greatly simplifies working with pipes in some cases. void closewithstatus( in nsresult astatus ); parameters astatus the
error that will be reported if this stream is accessed after it has been closed. ...
nsIAsyncOutputStream
methods asyncwait() asynchronously wait for the stream to be writable or closed. the notification is one-shot, meaning that each asyncwait call will result in exactly one notification callback. after the nsioutputstreamcallback.onoutputstreamready() event is dispatched, the stream releases its reference to the nsioutputstreamcallback object. it is safe to call asyncw...
...the stream is closed, the stream's status cannot be changed. any successful status code passed to this method is treated as ns_base_stream_closed, which has an effect equivalent to nsiinputstream.close(). note: this method exists in part to support pipes, which have both an input end and an output end. if the output end of a pipe is closed, then reads from the input end of the pipe will fail. the
error code returned when an attempt is made to read to a "closed" pipe corresponds to the status code passed in when the output end of the pipe was closed, which greatly simplifies working with pipes in some cases. void closewithstatus( in nsresult reason ); parameters reason the
error that will be reported if this stream is accessed after it has been closed. ...
nsIAuthModule
p( [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 unsigned long aintokenlen...
...th ); 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. ...
nsIBrowserSearchService
firmation 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 method, in astring url ); parameters ...
...omplete, 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 to remove. restoredefau...
nsICategoryManager
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. deletecategoryentry() delete an ...
...ntry() 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<nsicategorymanager> c...
nsIChannel
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 implement this method.
...tions 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
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. boolean handlefla...
...ovearguments() 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 included. aend the in...
nsIDictionary
dictionary. void getkeys( out pruint32 count, [retval, array, size_is(count)] out string keys ); return value array of all keys, unsorted. getvalue() find the value indicated by the key. nsisupports getvalue( in string key ); parameters key the lookup key indicating the value. return value the value associated with the specified key. if the key doesn't exist, ns_
error_failure is returned. setvalue() add the key-value pair to the dictionary. if the key is already present, the new value replaces the old one. void setvalue( in string key, in nsisupports value ); parameters key the key by which the value can be accessed. value the value to store. deletevalue() find the value indicated by the key. nsisupports deletevalue( i...
... setvalue( in string key, in nsisupports value ); parameters key the key by which the value can be accessed. value the value to store. deletevalue() find the value indicated by the key. nsisupports deletevalue( in string key ); parameters key the key indicating the pair to be removed. return value the removed value. if the key doesn't exist, ns_
error_failure will be returned. clear() delete all key-value pairs from the dictionary. void clear(); parameters none. ...
nsIException
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. null indicates "no data" read only. inner nsiexception an inner exception that triggered this, if available. read only. linenumber pruint32 valid li...
...ption 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 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. ...
nsIFeedProgressListener
cess. 1.0 66 introduced gecko 1.8 inherits from: nsifeedresultlistener last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void handleentry(in nsifeedentry entry, in nsifeedresult result); void handlefeedatfirstentry(in nsifeedresult result); void handlestartfeed(in nsifeedresult result); void report
error(in astring
errortext, in long linenumber, in boolean bozo); methods handleentry() called after each entry or item is processed. if the document is a standalone item or entry, the handlefeedatfirstentry() method will not already have been called, and the received nsifeedentry will have a null parent value. void handleentry( in nsifeedentry entry, in nsifeedresult result ); paramete...
... found, but before processing it. handlestartfeed() called as soon as a reasonable start to a feed is detected; this lets your code know that the feed does appear to be an actual feed rather than some other sort of document. void handlestartfeed( in nsifeedresult result ); parameters result an nsifeedresult describing the current state of the feed at the moment parsing begins. report
error() called by the feed processor when a fatal xml parsing
error occurs, or if the document isn't a feed. void report
error( in astring
errortext, in long linenumber, in boolean bozo ); parameters
errortext a short description of the
error. linenumber the line on which the
error occurred. bozo the bozo bit will be set if the
error was due to a fatal
error. see also nsifeedresul...
nsIFeedResult
doc nsifeedcontainer the parsed feed or entry. null if a non-feed was processed. headers nsiproperties the http response headers that accompanied the feed. stylesheet nsiuri an xslt stylesheet available to transform the source of the feed. some ...
... doc nsifeedcontainer the parsed feed or entry. ...
nsIGlobalHistory3
ion is responsible for sending ns_link_visited_event_topic to observers for redirect pages. this notification must be sent for history consumers for all non-redirect pages. the other params to this function are the same as those for nsichanneleventsink.onchannelredirect(). implementors who wish to implement this interface but rely on nsiglobalhistory2.adduri() for redirect processing may throw ns_
error_not_implemented from this method. if they do so, then callers must call nsiglobalhistory2.adduri() upon getting the ns_
error_not_implemented result. void adddocumentredirect( in nsichannel aoldchannel, in nsichannel anewchannel, in print32 aflags, in boolean atoplevel ); parameters aoldchannel anewchannel aflags flags to add. these are defin...
... aflags flags to add. these are defined by the history that is implementing this interface. atoplevel whether the uri is loaded in a top-level window. if false, the load is in a subframe. geturigeckoflags() get the gecko flags for this uri. these flags are used by gecko as hints to optimize page loading. not all histories have them; this need not be supported (just return ns_
error_not_implemented. these flags are opaque and should not be interpreted by the history engine. unsigned long geturigeckoflags( in nsiuri auri ); parameters auri the nsiuri to get flags for. flags are defined by the history that is implementing this interface. return value the gecko flags for the uri. seturigeckoflags() set the gecko flags for this uri. may fail if the history ent...
nsIMicrosummaryObserver
. 1.0 66 introduced gecko 1.8 obsolete gecko 6.0 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) method overview void oncontentloaded(in nsimicrosummary microsummary); void onelementappended(in nsimicrosummary microsummary); void on
error(in nsimicrosummary microsummary); methods oncontentloaded() called when an observed microsummary updates its content. since an observer might watch multiple microsummaries at the same time, the microsummary whose content has been updated gets passed to this handler. void oncontentloaded( in nsimicrosummary microsummary ); parameters microsummary the microsummary whose content has just bee...
...dated gets passed to this handler. void oncontentloaded( in nsimicrosummary microsummary ); parameters microsummary the microsummary whose content has just been updated. onelementappended() called when an element is appended to a microsummary set. void onelementappended( in nsimicrosummary microsummary ); parameters microsummary the microsummary that has just been appended to the set. on
error() called when an observed microsummary encounters an
error during an update. void on
error( in nsimicrosummary microsummary ); parameters microsummary the microsumary which could not be updated. see also microsummary topics creating a microsummary ...
nsIMsgHeaderParser
e in utf-8. addr the address of the sender. this should be in utf-8. return value a string of the form name <address>. exceptions thrown missing exception missing description native code only!parseheaderaddresses given a string which contains a list of header addresses, parses it into their component names and mailboxes. the returned value is the number of addresses, or a negative
error code; the names and addresses are returned into the provided pointers as consecutive null-terminated strings. it is up to the caller to free them. note that some of the strings may be zero-length. the caller may pass nsnull for charset and it will be interpreted as "us-ascii". either of the provided pointers may be null if the caller is not interested in those components. void parseheader...
...e. the names are separated by null-terminators. this param may be null if the caller does not want this part of the result. addresses a string of the addresses in the header line. the addresses are separated by null-terminators. this param may be null if the caller does not want this part of the result. numaddresses the number of addresses in the header. if this is negative, there has been an
error parsing the header. exceptions thrown missing exception missing description parseheaderswitharray() void parseheaderswitharray( in wstring aline, [array, size_is(count)] out wstring aemailaddresses, [array, size_is(count)] out wstring anames, [array, size_is(count)] out wstring afullnames, [retval] out unsigned long count ); parameters aline the header line to parse. aem...
nsIPrincipal
ans 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: prior to gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), this was not available to scripts. if the load is allowed this function does nothing. if the load is not allowed the function throws ns_
error_dom_bad_uri. note: other policies might override this, such as the access-control specification. note: the 'domain' attribute has no effect on the behaviour of this function. void checkmayload( in nsiuri uri, in boolean report ); parameters uri missing description report if true, will report a warning to the console service if the load is not allowed. exceptions thrown ...
..._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 capability missing...
nsIRequest
t's load flags are merged with the load flags of the load group. loadgroup nsiloadgroup the load group of this request. while pending, the request is a member of the load group. it is the responsibility of the request to implement this policy. name autf8string the name of the request. often this is the uri of the request. read only. status nsresult the
error status associated with the request. read only. constants various load flags which may be or'd together. constant value description load_normal 0 no special load flags. load_background 1 << 0 do not deliver status notifications to the nsiprogresseventsink, or keep this load from completing the nsiloadgroup it may belong to. the following...
...en opened. this means that things like authorization tokens or cookie headers should not be added. note: this will prevent proxy authentications from working, so use this flag with caution. methods cancel() cancels the current request. this will close any open input or output streams and terminate any async requests. users should normally pass ns_binding_aborted, although other
errors may also be passed. the
error passed in will become the value of the status attribute. implementations must not send any notifications (for example via nsirequestobserver) synchronously from this function. similarly, removal from the load group (if any) must also happen asynchronously. requests that use nsistreamlistener must not call ondataavailable anymore after cancel has been called. note...
nsIResumableChannel
od 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 ctxt, in unsigned...
...ffset, in bytes, to use to download. entityid information about the file, to match before obtaining the file. pass an empty string to use anything. resumeat() prepare this channel for resuming. the request will not start until asyncopen or open is called. calling resumeat after open or asyncopen has been called has undefined behaviour. during onstartrequest, this channel will have a status of ns_
error_not_resumable if the file cannot be resumed, for example because the server doesn't support this. this
error may occur even if startpos is 0, so that the front end can warn the user. similarly, the status of this channel during onstartrequest may be ns_
error_entity_changed, which indicates that the entity has changed, as indicated by a changed entityid. in both of these cases, no ondataavailable ...
nsISHistory
dle 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 page loads and so on. void purgehistory( in long numentries ); parameters...
...e 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 object must implement nsish...
nsIScriptableInputStream
ay 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 the stream, including...
...nate amount of time. this exception may only be thrown if nsiinputstream.isnonblocking() returns true. readbytes() read data from the stream, including null bytes. acstring readbytes( in unsigned long acount ); parameters acount the maximum number of bytes to read. return value the data from the stream, which will be an empty string if eof has been reached. exceptions thrown ns_
error_failure if there are not enough bytes available to read acount amount of data. ns_base_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. however, it does not address the problem of reading arbitrary binary data from a stream. for b...
nsIScriptableUnescapeHTML
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 src ); parameters ...
...g 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 ...
nsISocketTransport
host for the underlying socket connection. read only. port long get the port for the underlying socket connection. read only. securitycallbacks nsiinterfacerequestor security notification callbacks passed to the secure socket provider via nsisslsocketcontrol at socket creation time. this object supports nsibadcertlistener2 and nsissl
errorlistener for ssl connections, and possibly other interfaces. note: this attribute cannot be changed once a stream has been opened. securityinfo nsisupports security info object returned from the secure socket provider. this object supports nsisslsocketcontrol, nsitransportsecurityinfo, and possibly other interfaces. this attribute is only availa...
...onstants timeout type this constants are used by gettransport() and settransport() to specify socket timeouts constant value description timeout_connect 0 connecting timeout. timeout_read_write 1 read and write timeouts. nsitransporteventsink status codes note: although these constants look like xpcom
error codes and are passed in an nsresult variable, they are not
error codes. they do overlap with existing
error codes in necko, these status codes are confined within a very limited context where no
error codes may appear, so there is no ambiguity. the values of these status codes must never change. the status codes appear in near-chronological order (not in numeric order). status_resolving may be sk...
nsITaskbarProgress
nsigned long long currentvalue optional, in unsigned long long maxvalue optional); constants constant value description state_no_progress 0 stop displaying progress on the taskbar button. this should be used when the operation is complete or canceled. state_indeterminate 1 display a cycling, indeterminate progress bar. state_normal 2 display a determinate, normal progress bar. state_
error 3 display a determinate,
error progress bar. state_paused 4 display a determinate progress bar indicating that the operation has paused. methods setprogressstate() sets the taskbar progress state and value for this window. the currentvalue and maxvalue parameters are optional and should be supplied when state is one of state_normal, state_
error or state_paused. void setprogressstate( in ns...
...s 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 ...
nsIUTF8ConverterService
ing 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-escaped if your spec is no...
...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
r); 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 will be stored. ex...
...annot 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. ...
nsIUpdateCheckListener
toolkit/mozapps/update/nsiupdateservice.idlscriptable an interface describing an object that listens to the progress of an update check operation. this object is notified as the check continues, finishes and if it has an
error. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void oncheckcomplete(in nsixmlhttprequest request, [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount); void on
error(in nsixmlhttprequest request, in nsiupdate update); void onprogress(in nsixmlhttprequest request, in unsigned long position, in unsigned long totalsize); methods oncheckcomplete() called when the update check is completed. void oncheckcomple...
...lete() called when the update check is completed. void oncheckcomplete( in nsixmlhttprequest request, [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount ); parameters request the nsixmlhttprequest object handling the update check. updates an array of nsiupdate objects describing the available updates. updatecount the number of updates in the updates array. on
error() called when an
error occurs while loading the remote update service file. void on
error( in nsixmlhttprequest request, in nsiupdate update ); parameters request the nsixmlhttprequest object handling the update check. update an nsiupdate object containing details about the
error in its statustext attribute. onprogress() called every time there is a progress notification loading the update ...
nsIWebBrowser
esslistener or nsishistorylistener notifications in which case the the iid is that of the interface. void addwebbrowserlistener( in nsiweakreference alistener, in nsiidref aiid ); parameters alistener the listener to be added. aiid the iid of the interface that will be called on the listener as appropriate. return value ns_ok listener was successfully added. ns_
error_invalid_arg one of the arguments was invalid or the object did not implement the interface specified by the iid. removewebbrowserlistener() removes a previously registered listener. void removewebbrowserlistener( in nsiweakreference alistener, in nsiidref aiid ); parameters alistener the listener to be removed. aiid the iid of the interface on the listener that will no ...
...nterface specified by the iid. removewebbrowserlistener() removes a previously registered listener. void removewebbrowserlistener( in nsiweakreference alistener, in nsiidref aiid ); parameters alistener the listener to be removed. aiid the iid of the interface on the listener that will no longer be called. return value ns_ok listener was successfully added. ns_
error_invalid_arg one of the arguments was invalid or the object did not implement the interface specified by the iid. see also nsibasewindow nsicontextmenulistener nsidomwindow nsiembeddingsitewindow nsiinterfacerequestor nsishistorylistener nsitooltiplistener nsiuricontentlistener nsiweakreference nsiwebbrowserchrome nsiwebbrowserchromefocus nsiwebprogresslistener ...
nsIWebBrowserPersist
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 incompatible way. save the s...
...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. 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 ...
nsIWebSocketChannel
ription 0-999 reserved and not used. 1000 close_normal normal closure; the connection successfully completed whatever purpose for which it was created. 1001 close_going_away the endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection. 1002 close_protocol_
error the endpoint is terminating the connection due to a protocol
error. 1003 close_unsupported the connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data). 1004 close_too_large the endpoint is terminating the connection because a data frame was received that is too large. ...
...onously opens the websocket connection. received messages are fed to the socket listener as they arrive. the socket listener's methods are called on the thread that calls asyncopen() and are not called until after asyncopen() returns. if asyncopen() returns successfully, the protocol implementation promises to call at least onstart and onstop of the listener. note: implementations should throw ns_
error_already_opened if the websocket connection is reopened. void asyncopen( in nsiuri auri, in acstring aorigin, in nsiwebsocketlistener alistener, in nsisupports acontext ); parameters auri the uri of the websocket protocol; this may be redirected. aorigin the uri of the originating resource. alistener the nsiwebsocketlistener implementation. acontext an opa...
nsIWebSocketListener
ers acontext user defined context. amsg the message data. onmessageavailable() called when a text message has been received. void onmessageavailable( in nsisupports acontext, in autf8string amsg ); parameters acontext user defined context. amsg the message data, as a utf-8 string. onserverclose() called when the server sends a close message. in the case of
errors, onstop() may be called without this method ever getting called. no additional messages through onmessageavailable(), onbinarymessageavailable()() or onacknowledge()() will be delievered to the listener after onserverclose() is called, but outgoing messages can still be sent through the nsiwebsocketchannel connection. void onserverclose( in nsisupports acontext, in unsigned short acode, in...
...of the message stream. any listener that receives onstart() will also receive onstop(). void onstart( in nsisupports acontext ); parameters acontext user defined context. onstop() called to signify the completion of the message stream. this is the final notification the listener will receive; once it's been received, the websocket connection is complete. this event can be received in
error cases even if nsiwebsocketchannel.close() has not been called. void onstop( in nsisupports acontext, in nsresult astatuscode ); parameters acontext user defined context. astatuscode reason for stopping (ns_ok if completed successfully). see also websockets nsiwebsocketchannel ...
nsIXMLHttpRequestEventTarget
t listeners used when uploading data using the xmlhttprequest object. 1.0 66 introduced gecko 1.9.1 inherits from: nsidomeventtarget last changed in gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2) attributes attribute type description onabort nsidomeventlistener a javascript function object that gets invoked if the operation is canceled by the user. on
error nsidomeventlistener a javascript function object that gets invoked if the operation fails to complete due to an
error. onload nsidomeventlistener a javascript function object that gets invoked when the operation is successfully completed. onloadend nsidomeventlistener a javascript function object that gets invoked when the operation is completed for any reason; it will always follow a an abo...
...domeventlistener a javascript function object that gets invoked if the operation fails to complete due to an
error. onload nsidomeventlistener a javascript function object that gets invoked when the operation is successfully completed. onloadend nsidomeventlistener a javascript function object that gets invoked when the operation is completed for any reason; it will always follow a an abort,
error, or load event. onloadstart nsidomeventlistener a javascript function object that gets invoked exactly once when the operation begins. onprogress nsidomeventlistener a javascript function object that gets invoked zero or more times, after the loadstart event, but before any abort,
error, or load events occur. handling the events when the handler functions for these events are called, they ...
nsIXULRuntime
s running. read only. browsertabsremoteautostart boolean if true, browser tabs may be opened by default in a different process from the main browser ui. read only. insafemode boolean whether the application was launched in safe mode. read only. is64bit boolean indicates whether the current firefox build is 64-bit. read only. logconsole
errors boolean whether to write console
errors to a log file. if a component encounters startup
errors that might prevent the app from showing proper ui, it should set this flag to true. os autf8string a string tag identifying the current operating system. this is taken from the os_target configure variable. it will always be available. read only. processid unsigned lon...
...fying the binary abi of the current processor and compiler vtable. this is taken from the target_xpcom_abi configure variable. it may not be available on all platforms, especially unusual processor or compiler combinations. the result takes the form <processor>-<compilerabi>, for example: x86-msvc ppc-gcc3. this value should almost always be used in combination with os. may throw ns_
error_not_available. read only. constants process type constants constant value description process_type_default 0 the default (chrome) process. process_type_plugin 1 a plugin subprocess. process_type_content 2 a content subprocess. process_type_ipdlunittest 3 ipdl unit testing subprocess. methods invalidate...
NS_ASSERTION
summary macro throws an assertion failure if the first macro argument does not evaluate to true. in a debug build the failure text is written to console (stderr), into the nspr debug log, and on windows a dialog box is opened. the behavior of an assertion failure can be controlled using the xpcom_debug_break environment variable. an assertion failure should be thrown on critical program
errors only. ...
...rrors only. a triggered assertion failure is equivalent to crashing in tinderbox tests. note on terminology: "assertion" is the condition to test. ...
Setting HTTP request headers
.getservice(components.interfaces.nsiobserverservice); os.addobserver(this, "http-on-modify-request", false); return; } }, queryinterface: function (iid) { if (iid.equals(components.interfaces.nsiobserver) || iid.equals(components.interfaces.nsisupports)) return this; components.returncode = components.results.ns_
error_no_interface; return null; }, }; var mymodule = { registerself: function (compmgr, filespec, location, type) { var compmgr = compmgr.queryinterface(components.interfaces.nsicomponentregistrar); compmgr.registerfactorylocation(this.mycid, this.myname, this.myprogid, ...
...actory; }, mycid: components.id("{9cf5f3df-2505-42dd-9094-c1631bd1be1c}"), myprogid: "@dougt/myhttplistener;1", myname: "simple http listener", myfactory: { queryinterface: function (aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsifactory)) throw components.results.ns_
error_no_interface; return this; }, createinstance: function (outer, iid) { log("----------------------------> createinstance"); return new myhttplistener(); } }, canunload: function(compmgr) { return true; } }; function nsgetmodule(compmgr, filespec) { return mymodule; } privacy and security good practice a use case ...
Frequently Asked Questions
aq usually just refers back directly to the appropriate answer, there. if you're looking here just to learn about nscomptrs, you'll get a better introduction in the getting started guide. the faq is divided into sections to help you find what you're looking for faster. in most cases, the answer will just refer back into the reference manual, above. no need to explain things twice :-). buildtime
errors the build just broke. it's not in your code, or it's not on your platform, but there's an nscomptr on the line where the
error is and you're suspicious. you're looking in the right place. comparing an nscomptr to a raw xpcom interface pointer declaring an nscomptr to a forward-declared class not linking to xpcom not including nscomptr.h different settings of nscap_feature_debug_ptr_types ...
...uild just broke. it's not in your code, or it's not on your platform, but there's an nscomptr on the line where the
error is and you're suspicious. you're looking in the right place. comparing an nscomptr to a raw xpcom interface pointer declaring an nscomptr to a forward-declared class not linking to xpcom not including nscomptr.h different settings of nscap_feature_debug_ptr_types runtime
errors ns_assertion "queryinterface needed" may be caused by a class that derives from a given interface, when you forgetting to also specify the interface name in the ns_impl_isupports / ns_impl_threadsafe_isupports macro. for example, the assertion occurs when you convert the pointer to the object to a raw pointer to that interface, then assign the raw pointer to another nscomptr for that interfac...
Reference Manual
omptr with operator->()" a similar precondition intervenes on behalf of operator*. reference-counting safeguards all of the operations that extract the underlying raw pointer out of an nscomptr use a c trick to implement another safety feature. the pointer returned cannot be addrefed, released, or deleted. nscomptr<nsifoo> foo = ...; foo->addref(); //
error: |addref| is private delete foo.get(); //
error: |operator delete| is private ns_release(foo); //
error: |release| is private of course, the most important safety feature provided by nscomptr is that it addrefs and releases automatically at the appropriate times. casting never use old-style c/c++ casts on an nscomptr. an old-style cast is guaranteed to compile, even if it can'...
...nsresult rv; nscomptr<nsifoo> foo( do_queryinterface(abarptr, &rv) ); // or foo = do_queryinterface(abarptr, &rv); nscomptr<t> = dont_addref( t* ), nscomptr<t> = getter_addrefs( t* ) sometimes, you happen to have a pointer lying around that's already addrefed, but you want to put it into an nscomptr. this often happens with getters that return the addrefed pointer as ...
Using nsCOMPtr
er it, there probably isn't a document that answers it. you'll have to turn to the xpcom newsgroup or another experienced nscomptr user, or find the answer by experimentation. if you've never used nscomptr before, you're starting in the right place. just keep reading. you'll know when to stop. after you've been using nscomptrs for a while, and you reach unfamiliar territory, or run into compiler
errors; you may want to return to this document to get help from the reference manual or the faq. contents status, recent changes, and plans recent changes to nscomptr getting started guide introduction using nscomptr summary reference manual the basics initialization and assignment using an nscomptr<t> as a t* efficiency and correctness compiler ann...
...om the reference manual or the faq. contents status, recent changes, and plans recent changes to nscomptr getting started guide introduction using nscomptr summary reference manual the basics initialization and assignment using an nscomptr<t> as a t* efficiency and correctness compiler annoyances frequently asked questions buildtime
errors runtime
errors how do i... general bibliography original document information author(s): scott collins last updated date: december 11, 2001 copyright information: copyright © 1999, 2000 by the mozilla organization; use is subject to the mpl. portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons lic...
Working with Multiple Versions of Interfaces
{ return self; } rv = accdocnode->getwindowhandle(&wh); if(ns_succeeded(rv)){ self = static_cast<hwnd>(wh); } return self; } this approach worked, as is, for versions as early as firefox 1.5. the problem arises when one tries to run an extension built with the latest sdk in an older version of firefox, say firefox 2. what happens is that the call to do_createinstance fails with nsresult ns_
error_no_interface. this is because the call to do_createinstance(acid, aouter,
error); will eventually evolve into a request for an object supporting the interface with iid ns_get_iid(nsiaccessibleretrieval). unfortunately we compiled this in the latest sdk, and so this magic number happens to be: "244e4c67-a1d3-44f2-9cab-cdaa31b68046" whereas, inside firefox 2, the iid it happens to know about is...
...fortunately there is a plan of action that we can follow to rectify this. we build construct our xpcom component so that first tries to get the interface by it's new iid, then if that fails, attempts plan b. plan b is simply trying to get the interface by it's older iid. ...
XPCOM ABI
gcc2 - gnu c++ compiler 2.x gcc3 - gnu c++ compiler 3.x or 4.x sunc - sun c++ compiler ibmc - ibm c++ compiler for example: firefox built with the gnu c++ compiler 4.0.0 for the intel pentium processor would have xpcom abi of x86-gcc3 the xpcom abi string can be retrieved programmatically by using the nsixulruntime interface. ...
...++ compiler 3.x or 4.x sunc - sun c++ compiler ibmc - ibm c++ compiler for example: firefox built with the gnu c++ compiler 4.0.0 for the intel pentium processor would have xpcom abi of x86-gcc3 the xpcom abi string can be retrieved programmatically by using the nsixulruntime interface. to retrieve the abi of your firefox or thunderbird, open the
error console (accessible through tools |
error console) and evaluate the following javascript code: components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulruntime) .xpcomabi if either the cpu architecture or the c++ compiler are unknown, the application wouldn't have an xpcom abi string and attempts to get it will result in
error ns_
error_not_available. it would still be a distinct abi...
wrappedJSObject
suppose we register the component below with the @myself.com/my-component;1 contract. // constructor function helloworld() { }; helloworld.prototype = { hello: function() { return "hello world!"; }, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsihelloworld)) throw components.results.ns_
error_no_interface; return this; } }; xpconnect wrapping now let's get a reference to our component. in this example we use getservice, but as long as we get the reference from xpcom, our component gets wrapped by xpconnect in the same way: var comp = components.classes["@myself.com/my-component;1"].getservice(); if we try to call the hello() method we defined in our component implementatio...
... } }; xpconnect wrapping now let's get a reference to our component. in this example we use getservice, but as long as we get the reference from xpcom, our component gets wrapped by xpconnect in the same way: var comp = components.classes["@myself.com/my-component;1"].getservice(); if we try to call the hello() method we defined in our component implementation, we get: > comp.hello(); type
error on line 1: comp.hello is not a function this happens because, as we mentioned earlier, comp is not the helloworld js object itself, but an xpconnect wrapper around it: > dump(comp); [xpconnect wrapped nsisupports] the idea of these wrappers is to make the javascript-implemented xpcom components look just like any other xpcom component to the user. this also makes the public interface of the ...
XPIDL
and attributes interfaces declare a series of attributes and methods. attributes in idl are akin to javascript properties, in that they are a getter and (optionally) a setter pair. in javascript contexts, attributes are exposed as a regular property access, while native code sees attributes as a get and possibly a set method. attributes can be declared readonly, in which case setting causes an
error to 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 ...
...nnot. the must_use property is useful if the result of a method call or an attribute get/set should always (or usually) be checked, which is frequently the case. (e.g. a method that opens a file should almost certainly have its result checked.) this property will cause moz_must_use to be added to the generated function declarations, which means certain compilers (e.g. clang and gcc) will reports
errors if these results are not used. source and binary compatibility some consumers of idl interfaces create binary plugins that expect the interfaces to be stored in a specific way in memory. in other words, some changes made to idl interfaces require the author to modify the unique identifier (iid) in order to make it clear to plugins that utilize these interfaces that they have changed, and thus ...
Add to iPhoto
strcf = corefoundation.cfstringcreatewithcharacters(null, appstr, appstr.length); var appurl = corefoundation.cfurlcreatewithstring(null, appstrcf, null); corefoundation.cfrelease(appstrcf); var b = corefoundation.cfurlgetfsref(appurl, ref.address()); if (!b) { var stringsbundle = document.getelementbyid("string-bundle"); alert(stringsbundle.getstring('alert_download_
error_string')); } else { var array = ctypes.cast(mutablearray, corefoundation.cfarrayref); appservices.lsopenurlswithrole(array, 0, null, appparams.address(), null, 0); } corefoundation.cfrelease(appurl); // clean up corefoundation.cfrelease(array); } appservices.shutdown(); carbon.shutdown(); corefoundation.shutdown(); } this code begins by initializing al...
...create a cfstring referring to file:///applications/iphoto.app, which is iphoto's default path, using cfstringcreatewithcharacters(). create the corresponding cfurl object by calling cfurlcreatewithstring(). release the string using cfrelease(), since we're done with it. call cfurlgetfsref() to fill out the fsref structure to reference the same file as the cfurl. if that fails, we display an
error; otherwise, we cast the cfmutablearrayref into a cfarrayref by calling ctypes.cast(), then call lsopenurlswithrole() to actually send the image to iphoto. after doing that, we clean up after ourselves by releasing the cfurl object and the array, then shutting down the three libraries we used. downloading the image the downloadimage() method handles actually downloading the image to a temporary...
Using COM from js-ctypes
sid lpunknown, // punkouter dword, // dwclscontext refiid, // riid lpvoid // *ppv ); // helper functions function checkhresult(hr /*primative hresult*/, funcname /*jsstr*/) { // primative because thats what is returned by declared functions that // return hresult hr = hr.tostring(); // makes it primative if (hr < 0) { console.
error('hresult', hr, 'returned from function ', funcname /*, 'getstrofresult:', getstrofresult(hr)*/); throw new
error('hresult ' + hr + ' returned from function ' + funcname); } } let clsidfromarr = iidfromarr = function(jsarr_pieces) { let guid = guid(); // clsid and iid are same they are guid guid.data1 = parseint(jsarr_pieces[0], 16); guid.data2 = par...
...this example uses ipropertystore::setvalue to change the system.usermodelapp.id of an open fi...
Working with ArrayBuffers
ctypes.winapi_abi : ctypes.default_abi, ctypes.void_t, // return ctypes.void_t.ptr, // *dest ctypes.void_t.ptr, // *src ctype...
...ting system, "' + os.constants.sys.name + '"'); lib.close(); } } try { var memcpy = lib.declare('memcpy', os.constants.sys.name.tolowercase().indexof('win') == 0 ? ...
FunctionType
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 type
error 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 function. read only. ...
... 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 type
error func is not either pointer value or javascript function. see also ctype cdata abi library type conversion ...
ctypes
cast(data, type); ctype functiontype(abi, returntype[, argtype1, ...]); cdata int64(n); string libraryname(name); library open(libspec); ctype pointertype(typespec); ctype structtype(name[, fields]); cdata uint64(n); properties property type description errno number the value of the latest system
error. similar to errno in libc, available on all platforms. cannot be set. winlast
error number|undefined the value of the latest windows
error. similar to getlast
error under windows, available only for windows. cannot be set. constants abi constants these constants are used to specify the abi used to call a native function in the library. constant description ...
... credit for this example is to nmaier (stackoverflow :: getting tb_button is crashing and not working) example of cast and functiontype on windows components.utils.import("resource://gre/modules/...
Constants - Plugins
« previous this section is a reference to the program definitions used by the plug-in api. all program definitions are found in npapi.h.
error codes code value description nperr_no_
error 0 no
errors occurred. nperr_generic_
error 1
error with no specific
error code occurred. nperr_invalid_instance_
error 2 invalid instance passed to the plug-in. nperr_invalid_functable_
error 3 function table invalid. nperr_module_load_failed_
error 4 loading of plug-in failed. nperr_out_of_memory_
error 5 memory allocation failed. nperr_invalid_plugin_
error 6 plug-in missing or invalid. nperr_invalid_plugin_dir_
error 7 plug-in directory missing or invalid. ...
... nperr_invalid_param 9 parameter missing or invalid. nperr_invalid_url 10 url missing or invalid. nperr_file_not_found 11 file missing or invalid. nperr_no_data 12 stream contains no data. nperr_stream_not_seekable 13 seekable stream expected. ...
Version, UI, and Status Information - Plugins
the string you want to display on the status line. the browser always displays the last status line message it receives, regardless of the message source. for this reason, your message is always displayed, but you have no control over how long it stays in the status line before another message replaces it. you should use a different method to display messages that the user needs to see, such as
error messages. getting agent information a plug-in can check which browser is running on the user's current system. browsers communicate with http servers, which store agent software name, version, and operating system in a user_agent field. if you want to gather usage statistics or just find out the version of your plug-in's host browser, this information can help you. the plug-in calls the npn_us...
... /* that has windowless support */ return true; } detecting windowless support on other platforms browser implementations on other platforms did not have windowless plug-in support at the time it was added to ms windows and mac os x, so a different method must be used to detect whether the browser provides support. bool has_windowless() { npbool supportswindowless = false; np
error ret = npn_getvalue(instance, npnvsupportswindowless, &supportswindowless); return ret == nperr_no_
error && supportswindowless; } reloading a plug-in when the browser starts up, it loads all the plug-ins it finds in the plugins directory for the platform. if you call npn_reloadplugins, the browser reloads all plug-ins in the plugins directory without restarting. this causes the browser to i...
Debugger.Memory - Firefox Developer Tools
s allocated. this accessor property has both a getter and setter: assigning to it enables or disables the allocation site tracking. reading the accessor produces true if the debugger is capturing stacks for object allocations, and false otherwise. allocation site tracking is initially disabled in a new debugger. assignment is fallible: if the debugger cannot track allocation sites, it throws an
error instance. you can retrieve the allocation site for a given object with the debugger.object.prototype.allocationsite accessor property. allocationsamplingprobability a number between 0 and 1 that indicates the probability with which each new allocation should be entered into the allocations log. 0 is equivalent to “never”, 1 is “always”, and .05 would be “one out of twenty”. ...
...its 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 uncaughtexceptionhandler 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 type
error 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 debuggee compartment. ongarbagec...
Migrating from Firebug - Firefox Developer Tools
can set different types of breakpoints, which are all listed within the breakpoints side panel. in the devtools the breakpoints are shown below each script source within the sources side 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) ...
...the devtools storage inspector allows to remove all cookies and a single one by right-clicking on a cookie and choosing delete all resp. delete "<cookie name>". additionally, it allows to delete all cookies from a specific domain via the context menu option delete all from "<domain name>". it currently does not allow to only delete session cookies (see bug 1336934). developer toolbar display of
error count when there are javascript
errors on a page, the firebug start button shows a badge with their number. the devtools show the number of
errors in the developer toolbar. command api firebug offers a great variety of commands, which can be executed within its command line. the developer toolbar also provides an api with a lot of different commands to control the devtools and execute differen...
Shader Editor - Firefox Developer Tools
agment shaders are shown in the other two panes, and you can edit them. ...
...ers the middle and right hand panes show the vertex and fragment shaders for the currently selected program. ...
Animation.finish() - Web APIs
ing 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. ...
...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.log("finish() called on paused or finished animation."); } catch(e); logmy
errors(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. ...
AudioContext() - Web APIs
y 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 notsupported
error 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 specification doesn't indicate...
...um 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 type
error 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.webkitaudiocontext; var audioctx = new audiocontext({ latencyhint: 'interactive', samplerate: 44100,...
AudioNode.disconnect() - Web APIs
de is 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 invalidaccess
error 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 indexsize
error exception is thrown. input optional an index describing which input into the specified destination audionode is to be disconnec...
...fined according to the number of output channels (see audio channels). if this parameter is out-of-bound, an indexsize
error exception is thrown. input optional an index describing which input into the specified destination audionode is to be disconnected. the index numbers are defined according to the number of input channels (see audio channels). if this parameter is out-of-bound, an indexsize
error exception is thrown. exceptions indexsize
error a value specified for input or output is invalid, referring to a node which doesn't exist or outside the permitted range. invalidaccess
error the node on which disconnect() was called isn't connected to the specified destination node. example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audioconte...
AudioParam.setValueCurveAtTime() - Web APIs
the given 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 type
error 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 a...
...ntext.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 invalidstate
error the specified array of values has fewer than 2 items in it. range
error the specified starttime is either negative or a non-finite value, or duration is not a finite, strictly positive number. type
error 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 following the curve, its val...
AuthenticatorResponse - Web APIs
ionresponse var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.
error(err); }); getting an authenticatorattestationresponse var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publ...
... recommendation initial definition. ...
BaseAudioContext.createGain() - Web APIs
mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // ...
... mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // connected your source into the output in addition to using the gainnod...
BroadcastChannel - Web APIs
reates an object linking to the named channel. properties this interface also inherits properties from its parent, eventtarget. broadcastchannel.name read only returns a domstring, the name of the channel. event handlers broadcastchannel.onmessage an eventhandler property that specifies the function to execute when a message event is fired on this object. broadcastchannel.onmessage
error an eventhandler called when a messageevent of type message
error is fired—that is, when it receives a message that cannot be deserialized. methods this interface also inherits methods from its parent, eventtarget. broadcastchannel.postmessage() sends the message, of any type of object, to each broadcastchannel object listening to the same channel. broadcastchannel.close() closes the ch...
...hannel.postmessage() sends the message, of any type of object, to each broadcastchannel object listening to the same channel. broadcastchannel.close() closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected. events message fired when when a message arrives on the channel. also available via the onmessage property. message
error fired when a message arrives that can't be deserialized. also available via the onmessage
error property. specifications specification status comment html living standardthe definition of 'broadcastchannel' in that specification. living standard initial definition. ...
CSSStyleSheet.insertRule() - Web APIs
. (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 domexception. if index > cssrulelist.length, the method aborts with an indexsize
error. if rule cannot be inserted at index 0 due to some css constraint, the method aborts with a hierarchyrequest
error. if more than one rule is given in the rule parameter, the method aborts with a syntax
error. if trying to insert an @import at-rule after a style rule, the method aborts with a hierarchyrequest
error. if rule is @namespace and the rule-list has more than just @import at-rules and/o...
... examples inserting a new rule this snippet pushes a new rule onto the top of my stylesheet. ...
Cache.add() - Web APIs
note: add() will overwrite any key/value pair previously stored in the cache that matches the request. ...
...ite 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 type
error 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 an installevent to fire, then calls waituntil() to handle t...
Cache.put() - Web APIs
e cache interface allows key/value pairs to be added to the current cache object. often, you will just want to fetch() one or more requests, then add the result straight to your cache. in such cases you are better off using cache.add()/cache.addall(), as they are shorthand functions for one or more of these operations. fetch(url).then(function(response) { if (!response.ok) { throw new type
error('bad response status'); } return cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request. note: cache.add/cache.addall do not cache responses with response.status values that are not in the 200 range, whereas cache.put lets you store any request/response pair. as a result, cache.add/cache.addall can't be used to...
...que responses, whereas cache.put can. syntax cache.put(request, response).then(function() { // request/response pair has been added to the cache }); parameters request the request object or url that you want to add to the cache. response the response you want to match up to the request. return value a promise that resolves with undefined. note: the promise will reject with a type
error if the url scheme is not http or https. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachestorage.match(). if so, serve that. if not, open the v1 cache using open(), put the default network request in th...
CacheStorage - Web APIs
ssl certificate is configured. maintains a mapping of string names to corresponding cache objects. use cachestorage.open() to obtain a cache instance. use cachestorage.match() to check if a given request is a key in any of the cache objects that the cachestorage object tracks. you can access cachestorage through the global caches property. note: cachestorage always rejects with a security
error on untrusted origins (i.e. those that aren't using https, although this definition will likely become more complex in the future.) when testing, you can get around this by checking the "enable service workers over http (when toolbox is open)" option in the firefox devtools options/gear menu. note: cachestorage.match() is a convenience method. equivalent functionality to match a cache entry can b...
...to respect user's disk space. async function deleteoldcaches( currentcache ) { const keys = await caches.keys(); for ( const key of keys ) { const isourcache = 'myapp-' === key.substr( 0, 6 ); if ( currentcache === key || ! isourcache ) { continue; } caches.delete( key ); } } try { const data = await getdata(); console.log( { data } ); } catch (
error ) { console.
error( {
error } ); } specifications specification status comment service workersthe definition of 'cachestorage' in that specification. working draft initial definition. ...
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 hierarchyrequest
error: 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 ...
...div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.after(span, "text"); console.log(parent.outerhtml); // "<div><p></p><span></span>text</div>" childnode.after() is unscopable the after() method is not scoped into the with statement. see symbol.unscopables for more information. ...
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 hierarchyrequest
error: 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 child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.before(span, "text"); console.log(parent.outerhtml); // "<div><span></span>text<p></p></div>" childnode.before() is unscopable the before() method is not scoped into the with statement. see symbol.unscopables for more information. ...
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 hierarchyrequest
error: 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 s...
... 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 scoped into the with statement. see symbol.unscopables for more information. ...
Clipboard.write() - Web APIs
the code begins by creating a new clipboarditem object into which the text will be placed for sending to the clipboard. the key of the object passed to the clipboarditem constructor indicates the content type, the value indicates the content. the content could be a text or even a blob (e.g. for copying images to the clipboard). ...
...y of the object passed to the clipboarditem constructor indicates the content type, the value indicates the content. the content could be a text or even a blob (e.g. for copying images to the clipboard). then write() is called, specifying both a fulfilment function and an
error function. example of copying canvas contents to the clipboard function copycanvascontentstoclipboard(canvas, ondone, on
error) { canvas.toblob(function (blob) { let data = [new clipboarditem({ [blob.type]: blob })]; navigator.clipboard.write(data).then(function () { ondone(); }, function (err) { on
error(err); }) }); } note: you can only pass in one clipboard item at a time. specifications specification status comment clipboard api and eventsthe definition of ...
ClipboardItem.types - Web APIs
lipboarditem syntax var types = clipboarditem.types; value an array of available mime types. examples in the below example, we're returning all items on the clipboard via the clipboard.read() method. then checking the types property for available types before utilizing the clipboarditem.gettype() method to return the blob object. ...
...found for the specified type, an
error is returned. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.
error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification. working draft initial definition. ...
CloseEvent - Web APIs
0–999 reserved and not used. 1000 normal closure normal closure; the connection successfully completed whatever purpose for which it was created. 1001 going away the endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection. 1002 protocol
error the endpoint is terminating the connection due to a protocol
error. 1003 unsupported data the connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data). 1004 reserved. a meaning might be defined in the future. 1005 no status received reserved...
...atus code, used when codes 1003 and 1009 are not suitable. 1009 message too big the endpoint is terminating the connection because a data frame was received that is too large. 1010 missing extension the client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn't. 1011 internal
error the server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request. 1012 service restart the server is terminating the connection because it is restarting. [ref] 1013 try again later the server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casti...
console - Web APIs
message to the console with the log level debug. console.dir() displays an interactive listing of the properties of 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. howev...
...race() outputs a stack trace. console.warn() outputs a warning message. you may use string substitution and additional arguments with this method. examples outputting text to the console the most frequently-used feature of the console is logging of text and other data. there are four categories of output you can generate, using the console.log(), console.info(), console.warn(), and console.
error() methods respectively. each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you. there are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you ca...
CustomElementRegistry.define() - Web APIs
es 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. ...
... return value void. exceptions exception description notsupported
error 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. syntax
error the provided name is not a valid custom element name. type
error the referenced constructor is not a constructor. note: you'll often get notsupported
errors thrown that seem like define() is failing, but instead it is likely a problem with element.attachshadow(). examples autonomous custom element the following code is taken from our popup-info-box-web-component example (...
DOMMatrixReadOnly - Web APIs
syntax. 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 invalidstate
error 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. dommatri...
...efault, 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 type
error 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 type
error exception is thrown. frommatrix() creates a new mutable dommatrix object given an existing matrix or a dommatrixini...
Binary strings - Web APIs
l binary format, however this will not be visible to the final user, since the length of javascript strings is calculated using two bytes as the unit. binary strings are not part of the javascript language design. however at least one native function requires binary strings as its input, btoa(): invoking it on a string that contains codepoints greater than 255 will cause a character out of range
error. the reason that brought to use utf-16 code units as placeholders for uint8 numbers is that as web applications become more and more powerful (adding features such as audio and video manipulation, access to raw data using websockets, and so forth) it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. in...
...ess to raw data using websockets, and so forth) it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer (i.e., using binary strings). however, this is slow and
error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently. the stringview non native constructor is one level above typed arrays and provides a c-like interface for strings. ...
DedicatedWorkerGlobalScope - Web APIs
ndlers from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.onmessage is an eventhandler representing the code to be called when the message event is raised. these events are of type messageevent and will be called when the worker receives a message from the document that started it (i.e. from the worker.postmessage method.) dedicatedworkerglobalscope.onmessage
error is an eventhandler representing the code to be called when the message
error event is raised. methods this interface inherits methods from the workerglobalscope interface, and its parent eventtarget, and therefore implements methods from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.close() discards any tasks queued in the workerglobalscope's event loop, e...
...tinterval(). windowtimers.cleartimeout() cancels the repeated execution set using windowtimers.settimeout(). windowtimers.setinterval() schedules the execution of a function every x milliseconds. windowtimers.settimeout() sets a delay for executing a function. events message fired when the worker receives a message from its parent. also available via the onmessage property. message
error fired when a worker receives a message that can't be deserialized. also available via the onmessage
error property. specifications specification status comment html living standardthe definition of 'dedicatedworkerglobalscope' in that specification. living standard ...
DirectoryReaderSync - Web APIs
the list of entry file system urls. var paths = []; function getallentries(dirreader) { var entries = dirreader.readentries(); for (var i = 0, entry; entry = entries[i]; ++i) { // stash this entry's filesystem in url paths.push(entry.tourl()); // if this is a directory, traverse. if (entry.isdirectory) { getallentries(entry.createreader()); } } } // forward the
error to main app. function on
error(e) { postmessage('
error: ' + e.tostring()); } self.onmessage = function(e) { 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: path...
...call this method until an empty array is returned. ...
DisplayMediaStreamConstraints.video - Web APIs
s video 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 type
error 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; d...
...raints; displaymediastreamconstraints = { video: allowvideoflag | mediatrackconstraints; } value the value may be either a boolean or a mediatrackconstraints object. if a boolean is specified, a value of true (the default) indicates that the stream returned by getdisplaymedia() should be in whatever format the user agent feels is best. a value of false is not permitted and will throw a type
error. if a mediatrackconstraints object is given instead, the video track will be processed to match the settings given in the constraints object. constraints specific to screen sharing these constraints apply to mediatrackconstraints objects specified as part of the displaymediastreamconstraints object's video property when using getdisplaymedia() to obtain a stream for screen sharing. cursor ...
Document.exitFullscreen() - Web APIs
ent which is currently being presented in full-screen mode be taken out of full-screen mode, restoring the previous state of the screen. this usually reverses the effects of a previous call to element.requestfullscreen(). syntax exitpromise = document.exitfullscreen(); parameters none. return value a promise which is resolved once the user agent has finished exiting full-screen mode. if an
error occurs while attempting to exit full-screen mode, the catch() handler for the promise is called. example this example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. document.onclick = function (event) { if (document.fullscreenelement) { document.exitfullscreen() .then(() => console.log("document exited ...
...catch() handler for the promise is called. example this example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. document.onclick = function (event) { if (document.fullscreenelement) { document.exitfullscreen() .then(() => console.log("document exited form full screen mode")) .catch((err) => console.
error(err)) } else { document.documentelement.requestfullscreen(); } } note: for a more complete example, see the example in element.requestfullscreen(). specifications specification status comment fullscreen apithe definition of 'document.exitfullscreen()' in that specification. living standard initial definition ...
Document.getElementById() - Web APIs
note that the id parameter is case-sensitive, so document.getelementbyid("main") will return null instead of the element <div id="main"> because "m" and "m" are different for the purposes of this method. elements not in the ...
...note that the id parameter is case-sensitive, so document.getelementbyid("main") will return null instead of the element <div id="main"> because "m" and "m" are different for the purposes of this method. elements not in the document are not searched by ...
Document.querySelectorAll() - Web APIs
ng a list 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 syntax
error 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 l...
...ing 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 syntax
error 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"); here, we g...
Document.write() - Web APIs
after writing, call document.close() to tell the browser to finish loading the page. if the document.write() call is embedded within an inline html <script> tag, then it will not call document.open(). for example: <script> document.write("<h1>main title</h1>") </script> note: document.write() and document.writeln do not work in xhtml documents (you'll get an "operation is not supported" [ns_
error_dom_not_supported_err]
error in the
error console). this happens when opening a local file with the .xhtml file extension or for any document served with an application/xhtml+xml mime type. more information is available in the w3c xhtml faq. note: using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "a call to document.write() from an asynchron...
...e). this happens when opening a local file with the .xhtml file extension or for any document served with an application/xhtml+xml mime type. more information is available in the w3c xhtml faq. note: using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "a call to document.write() from an asynchronously-loaded external script was ignored" in the
error console. note: in edge only, calling document.write() more than once in an <iframe> causes the
error "script70: permission denied". note: starting with version 55, chrome will not execute <script> elements injected via document.write() when specific conditions are met. for more information, refer to intervening against document.write(). specifications specification status comme...
Document Object Model (DOM) - Web APIs
ment's structure, 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. ...
... obsolete dom interfaces the document object model has been highly simplified. to achieve this, the following interfaces present in the different dom level 3 or earlier specifications have been removed. ...
Element.innerHTML - Web APIs
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 syntax
error an attempt was made to set the value of innerhtml using a string which is not properly-formed html. nomodificationallowed
error 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 loaded. reading the ...
...case although this may look like a cross-site scripting attack, the result is harmless. html5 specifies that a <script> tag inserted with innerhtml should not execute. however, there are ways to execute javascript without using <script> elements, so there is still a security risk whenever you use innerhtml to set strings over which you have no control. for example: const name = "<img src='x' on
error='alert(1)'>"; el.innerhtml = name; // shows the alert for that reason, it is recommended that you do not use innerhtml when inserting plain text; instead, use node.textcontent. this doesn't parse the passed content as html, but instead inserts it as raw text. warning: if your project is one that will undergo any form of security review, using innerhtml most likely will result in your code bein...
Element.querySelector() - Web APIs
the queryselector() 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 syntax
error 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...
...escendants; 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 syntax
error 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 hierarchy counts this...
Element.querySelectorAll() - Web APIs
of selectors 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 syntax
error 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 l...
...pecial 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 syntax
error 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-name*="funnel-char...
Event - Web APIs
the mdn api reference. note that all event interfaces have names which end in "event". ...
...ent cssfontfaceloadevent customevent devicelightevent devicemotionevent deviceorientationevent deviceproximityevent domtransactionevent dragevent editingbeforeinputevent
errorevent fetchevent focusevent gamepadevent hashchangeevent idbversionchangeevent inputevent keyboardevent mediastreamevent messageevent mouseevent mutationevent offlineaudiocompletionevent overconstrained
error pagetransitionevent paymentrequestupdateevent pointerevent popstateevent progressevent relatedevent rtcdatachannelevent rtcidentity
errorevent rtcidentityevent rtcpeerconnectioniceevent sensorevent storageevent svgevent svgzoomevent timeevent touchevent trackevent transitionevent uievent userproximityevent webglcontextevent wheelevent constructor event() creates an eve...
EventSource - Web APIs
presenting the state of the connection. possible values are connecting (0), open (1), or closed (2). eventsource.url read only a domstring representing the url of the source. eventsource.withcredentials read only a boolean indicating whether the eventsource object was instantiated with cross-origin (cors) credentials set (true), or not (false, the default). event handlers eventsource.on
error is an eventhandler called when an
error occurs and the
error event is dispatched on an eventsource object. eventsource.onmessage is an eventhandler called when a message event is received, that is when a message is coming from the source. eventsource.onopen is an eventhandler called when an open event is received, that is when the connection was just opened. methods this interface also in...
...coming from the source. eventsource.onopen is an eventhandler called when an open event is received, that is when the connection was just opened. methods this interface also inherits methods from its parent, eventtarget. eventsource.close() closes the connection, if any, and sets the readystate attribute to closed. if the connection is already closed, the method does nothing. events
error fired when a connection to an event source failed to open. message fired when data is received from an event source. open fired when a connection to an event source has opened. additionally, the event source itself may send messages with an event field, which will create ad-hoc events keyed to that value. examples in this basic example, an eventsource is created to receive unnamed events...
ExtendableEvent - Web APIs
ent interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. this ensures that any functional events (like fetchevent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. if waituntil() is called outside of the extendableevent handler, the browser should throw an invalidstate
error; note also that multiple calls will stack up, and the resulting promises will be added to the list of extend lifetime promises. note: the behaviour described in the above paragraph was fixed in firefox 43 (see bug 1180274.) this interface inherits from the event interface. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 8.57142857...
...l event. resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { return cache.addall(urlstoprefetch.map(function(urltoprefetch) { return new request(urltoprefetch, {mode: 'no-cors'}); })).then(function() { console.log('all resources have been fetched and cached.'); }); }).catch(function(
error) { console.
error('pre-fetching failed:',
error); }) ); }); important: when fetching resources, it's very important to use {mode: 'no-cors'} if there is any chance that the resources are served off of a server that doesn't support cors. in this example, www.chromium.org doesn't support cors. specifications specification status comment service workersthe defin...
FetchEvent.request - Web APIs
cope.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(response) { if (response) { console.log('found response in cache:', resp...
...quest).then(function(response) { if (response) { console.log('found response in cache:', response); return response; } console.log('no response found in cache. about to fetch from network...'); return fetch(event.request).then(function(response) { console.log('response from network is:', response); return response; }).catch(function(
error) { console.
error('fetching failed:',
error); throw
error; }); }) ); }); specifications specification status comment service workersthe definition of 'request' in that specification. working draft initial definition. ...
FileReaderSync.readAsArrayBuffer() - Web APIs
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: notfound
error is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. security
error 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 the resource is unsafe for a use from the web (like it is a system file). ...
...en the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. security
error 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 the resource is unsafe for a use from the web (like it is a system file). notreadable
error is raised when the resource cannot be read due to a permission problem, like a concurrent lock. encoding
error is raised when the resource is a data url and exceed the limit length defined by each browser. specifications specification status comment file apithe definition of 'readasarraybuffersync' in that specification. working draft initial definition. ...
FileReaderSync.readAsBinaryString() - Web APIs
jects 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: notfound
error is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. security
error 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 the resource is unsafe for a use from the web (like it is a system file). ...
...en the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. security
error 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 the resource is unsafe for a use from the web (like it is a system file). notreadable
error is raised when the resource cannot be read due to a permission problem, like a concurrent lock. encoding
error is raised when the resource is a data url and exceed the limit length defined by each browser. specifications specification status comment file apithe definition of 'readasbinarystringsync' in that specification. working draft initial definition. ...
FileReaderSync.readAsDataURL() - Web APIs
nto 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: notfound
error is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. security
error 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 the resource is unsafe for a use from the web (like it is a system file). ...
...en the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. security
error 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 the resource is unsafe for a use from the web (like it is a system file). notreadable
error is raised when the resource cannot be read due to a permission problem, like a concurrent lock. encoding
error is raised when the resource is a data url and exceed the limit length defined by each browser. specifications specification status comment file apithe definition of 'readasdataurl' in that specification. working draft initial definition. browser ...
FileReaderSync.readAsText() - Web APIs
text(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: notfound
error is raised when the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. security
error 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 the resource is unsafe for a use from the web (like it is a system file). ...
...en the resource represented by the dom file or blob cannot be found, e.g. because it has been erased. security
error 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 the resource is unsafe for a use from the web (like it is a system file). notreadable
error is raised when the resource cannot be read due to a permission problem, like a concurrent lock. encoding
error is raised when the resource is a data url and exceed the limit length defined by each browser. specifications specification status comment file apithe definition of 'readastext' in that specification. working draft initial definition. browser com...
FileSystemDirectoryReader.readEntries() - Web APIs
adentries() method retrieves the directory entries within the directory being read and delivers them in an array to a provided callback function. the objects in the array are all based upon filesystementry. generally, they are either filesystemfileentry objects, which represent standard files, or filesystemdirectoryentry objects, which represent directories. syntax readentries(successcallback[,
errorcallback]); parameters successcallback a function which is called when the directory's contents have been retrieved. the function receives a single input parameter: an array of file system entry objects, each based on filesystementry. generally, they are either filesystemfileentry objects, which represent standard files, or filesystemdirectoryentry objects, which represent directories. if th...
...ved. the function receives a single input parameter: an array of file system entry objects, each based on filesystementry. generally, they are either filesystemfileentry objects, which represent standard files, or filesystemdirectoryentry objects, which represent directories. if there are no files left, or you've already called readentries() on this filesystemdirectoryreader, the array is empty.
errorcallback optional a callback function which is called if an
error occurs while reading from the directory. it receives one input parameter: a file
error object describing the
error which occurred. return value undefined. example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory l...
FileSystemFlags.create - Web APIs
create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the
errorcallback is called with an appropriate
error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesyst...
...file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. true true path exists the
errorcallback is called with an appropriate
error, such as file
error.path_exists_err. true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. [1] when create is false, the value of exclusive is irrelevant and ignored. specifications specification statu...
FileSystemFlags.exclusive - Web APIs
create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the
errorcallback is called with an appropriate
error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesyst...
...file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. true true path exists the
errorcallback is called with an appropriate
error, such as file
error.path_exists_err. true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. [1] when create is false, the value of exclusive is irrelevant and ignored. specifications specification statu...
FileSystemFlags - Web APIs
create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the
errorcallback is called with an appropriate
error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesyst...
...file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. true true path exists the
errorcallback is called with an appropriate
error, such as file
error.path_exists_err. true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. [1] when create is false, the value of exclusive is irrelevant and ignored. specifications specification statu...
File and Directory Entries API - Web APIs
rectoryentry represents a single directory in a file system. filesystemdirectoryreader created by calling filesystemdirectoryentry.createreader(), this interface provides the functionality which lets you read the contents of a directory. filesystemflags defines a set of values which are used when specifying option flags when calling certain methods in the file and directory entries api. file
error represents an
error which is generated by asynchronous 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 window object and implemented in localfilesystem: requestfilesystem() and resolvelocalfilesystemurl(). synchronous api the synchronous api is should only be us...
... 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. fileexception 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 access to a sandboxed ...
Guide to the Fullscreen API - Web APIs
te in order to opt-in to allowing their content to be displayed in fullscreen mode. in addition, certain kinds of content, such as windowed plug-ins, cannot be presented in fullscreen mode. attempting to put an element which can't be displayed in fullscreen mode (or the parent or descendant of such an element) won't work. instead, the element which requested fullscreen will receive a mozfullscreen
error event. when a fullscreen request fails, firefox will log an
error message to the web console explaining why the request failed. in chrome and newer versions of opera however, no such warning is generated. note: fullscreen requests need to be called from within an event handler or otherwise they will be denied. getting out of full screen mode the user always has the ability to exit fullscree...
...n mozfullscreen - document.fullscreenenabled webkitfullscreenenabled mozfullscreenenabled msfullscreenenabled documentorshadowroot.fullscreenelement webkitfullscreenelement mozfullscreenelement msfullscreenelement document.onfullscreenchange onwebkitfullscreenchange onmozfullscreenchange onmsfullscreenchange document.onfullscreen
error onwebkitfullscreen
error onmozfullscreen
error onmsfullscreen
error document.exitfullscreen() webkitexitfullscreen() mozcancelfullscreen() msexitfullscreen() element.requestfullscreen() webkitrequestfullscreen() mozrequestfullscreen() msrequestfullscreen() specifications specification status comment fullscreen api li...
GainNode.gain - Web APIs
mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // ...
... mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // connected your source into the output in addition to using the gainnod...
GainNode - Web APIs
mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // ...
... mute.onclick = voicemute; function voicemute() { if(mute.id == "") { // 0 means mute. if you still hear something, make sure you haven't // connected your source into the output in addition to using the gainnod...
Geolocation.clearWatch() - Web APIs
the geolocation.clearwatch() method is used to unregister location/
error monitoring handlers previously installed using geolocation.watchposition(). syntax navigator.geolocation.clearwatch(id); parameters id the id number returned by the geolocation.watchposition() method when installing the handler you wish to remove. ...
... id the id number returned by the geolocation.watchposition() method when installing the handler you wish to remove. example var id, target, option; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulation, you reach the target'); navigator.geolocation.clearwatch(id); } }; function
error(err) { console.warn('
error(' + err.code + '): ' + err.message); }; target = { latitude : 0, longitude: 0, } options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0 }; id = navigator.geolocation.watchposition(success,
error, options); specifications specification status comment geolocation api recommendation initial specification. ...
Geolocation.getCurrentPosition() - Web APIs
the geolocation.getcurrentposition() method is used to get the current position of the device. syntax navigator.geolocation.getcurrentposition(success[,
error[, [options]]) parameters success a callback function that takes a geolocationposition object as its sole input parameter.
error optional an optional callback function that takes a geolocationposition
error object as its sole input parameter. options optional an optional positionoptions object. options includes: maximumage: integer (milliseconds) | infinity - maximum cached position age. timeout: integer (milliseconds) - amount of time before the
error callback is invoked, if 0 it will never invoke. enablehighaccuracy: false | true examples var options = { enablehighaccuracy: true, timeout: 5000, maximuma...
...ll never invoke. enablehighaccuracy: false | true examples var options = { enablehighaccuracy: true, timeout: 5000, maximumage: 0 }; function success(pos) { var crd = pos.coords; console.log('your current position is:'); console.log(`latitude : ${crd.latitude}`); console.log(`longitude: ${crd.longitude}`); console.log(`more or less ${crd.accuracy} meters.`); } function
error(err) { console.warn(`
error(${err.code}): ${err.message}`); } navigator.geolocation.getcurrentposition(success,
error, options); specifications specification status comment geolocation api recommendation initial specification. ...
HTMLImageElement.complete - Web APIs
he src nor the srcset attribute is specified. the srcset attribute is absent and the src attribute, while specified, is the empty string (""). the image resource has been fully fetched and has been queued for rendering/compositing. the image element has previously determined that the image is fully available and ready for use. the image is "broken;" that is, the image failed to load due to an
error or because image loading is disabled. it's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running. examples consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. these photos may be very large, so you don't want to wait...
...te property before attempting to do its work. this is demonstrated in the code below. let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.on
error = reject; elem.src = url; }); } async function lightbox(url) { lightboxelem.style.display = "block"; await loadimage("https://somesite.net/huge-image.jpg", lightboximgelem); lightboxcontrolselem.disabled = false; } /* ... */ function fixredeyecommand() { if (lightboxelem.style.display === "block" && lightboximgelem.complete) { fixredeye(lightboximgelem); } else { /* can...
HTMLImageElement.decode() - Web APIs
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 encoding
error a domexception 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 the full-resolutio...
...r use. at that time, you can then replace the low-resolution image with the full-resolution one that's now available. examples the following example shows how to use the decode() method to control when an image is appended to the dom. without a promise-returning method, you would add the image to the dom in a load event handler, such as by using the img.onload event handler, and by handling the
error in the
error event's handler. const img = new image(); img.src = 'nebula.jpg'; img.decode() .then(() => { document.body.appendchild(img); }) .catch((encoding
error) => { // do something with the
error. }) specifications specification status comment html living standardthe definition of 'decode()' in that specification. living standard initial definition. ...
HTMLSelectElement.add() - Web APIs
his 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 dom
error of the type hierarchyrequest
error 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"; sel.add(opt1...
... */ specifications specification status comment html living standardthe definition of 'htmlselectelement.add()' in that specification. living standard html5the definition of 'htmlselectelement.add()' in that specification. recommendation is a snapshot of html living standard. the value of before can now be a long and is optional. it throws a dom
error of the type hierarchyrequest
error 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...
HTMLSelectElement.setCustomValidity() - Web APIs
specifications specification status comment html living standardthe definition of 'htmlselectelement.setcustomvalidity()' in that specification. ...
... specifications specification status comment html living standardthe definition of 'htmlselectelement.setcustomvalidity()' in that specification. ...
The HTML DOM API - Web APIs
i as well as the <img> element and <picture> elements. canvasgradient canvaspattern canvasrenderingcontext2d imagebitmap imagebitmaprenderingcontext imagedata offscreencanvas offscreencanvasrenderingcontext2d path2d textmetrics media interfaces the media interfaces provide html access to the contents of the media elements: <audio> and <video>. audiotrack audiotracklist media
error texttrack texttrackcue texttrackcuelist texttracklist timeranges trackevent videotrack videotracklist drag and drop interfaces these interfaces are used by the html_drag_and_drop_api to represent individual draggable (or dragged) items, groups of dragged or draggable items, and to handle the drag and drop process. datatransfer datatransferitem datatransferitemlist dragevent ...
...faces these interfaces are used by the web components api to create and manage the available custom elements. customelementregistry miscellaneous and supporting interfaces these supporting object types are used in a variety of ways in the html dom api. in addition, promiserejectionevent represents the event delivered when a javascript promise is rejected. domstringlist domstringmap
errorevent htmlallcollection mimetype mimetypearray promiserejectionevent interfaces belonging to other apis several interfaces are technically defined in the html specification while actually being part of other apis. web storage interfaces the web_storage_api provides the ability for web sites to store data either temporarily or permanently on the user's device for later re-use. storage...
IDBCursor.continue() - Web APIs
meter. 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 domexception of one of the following types: exception description transactioninactive
error this idbcursor's transaction is inactive. data
error 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 direction is next or nextunique. the key is greater than or equal to this cursor's position and this cursor's direction is prev or prevunique. ...
... 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. the cursor does not require us to select the data based on a key; we can just grab all of it. ...
IDBDatabase.deleteObjectStore() - Web APIs
tabase.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. ...
...eteobjectstore(name); parameters name the name of the object store you want to delete. exceptions this method may raise a domexception of one of the following types: exception description invalidstate
error occurs if the method was not called from a versionchange transaction callback. for older webkit browsers, you must call first. transactioninactive
error occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstate
error was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) notfound
error you are trying to delete an object store that does not exist. names are case sensitive. example var dbna...
IDBFactory.deleteDatabase() - Web APIs
the deletedatabase() method of the idbfactory interface requests the deletion of a database. the method returns an idbopendbrequest object immediately, and performs the deletion operation asynchronously. if the database is successfully deleted, then a success event is fired on the request object returned from this method, with its result set to undefined. if an
error occurs while the database is being deleted, then an
error event is fired on the request object that is returned from this method. when deletedatabase() is called, any other open connections to this particular database will get a versionchange 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 bel...
...ion 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 idbopendbrequest on which subsequent events related to this request are fired. example var dbdeleterequest = window.indexeddb.deletedatabase("todolist"); dbdeleterequest.on
error = function(event) { console.log("
error deleting database."); }; dbdeleterequest.onsuccess = function(event) { console.log("database deleted successfully"); console.log(event.result); // should be undefined }; specifications specification status comment indexed database api draftthe definition of 'deletedatabase()' in that specification. recommendation ...
IDBIndex.getAll() - Web APIs
bindex.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 type
error 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 domexception of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. invalidstate
error the idbindex has been deleted or removed. a ...
...eption will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. invalidstate
error the idbindex has been deleted or removed. a type
error 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. r...
IDBIndex.getAllKeys() - Web APIs
index.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 type
error 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 domexception of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. invalidstate
error the idbindex has been deleted or removed. ...
... will be thrown. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. invalidstate
error the idbindex has been deleted or removed. a type
error 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 sp...
IDBObjectStore.autoIncrement - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.autoincrement); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); o...
...rite db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.autoincrement); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our re...
IDBObjectStore.clear() - Web APIs
ecords 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 domexception of one of the following types: exception description readonly
error the transaction associated with this operation is in read-only mode. transactioninactive
error this idbobjectstore's transaction is inactive. example in the following code snippet, we open a read/write transaction on our database and clear all the current data out of the object store using clear(). for a full working example, see our to-do notifications app (view examp...
...orm the object store cleardata(); }; function cleardata() { // open a read/write db transaction, ready for clearing the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error: ' + transaction.
error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to clear all the data out of the object store var objectstorerequest = objectstore.clear(); objectstorerequest.onsuccess = function(event) { /...
IDBObjectStore.delete() - Web APIs
rs 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 domexception of the following types: exception description transactioninactive
error this object store's transaction is inactive. readonly
error the object store's transaction mode is read-only. invalidstate
error the object store has been deleted. data
error the key is not a valid key or a key range. example in the following code snippet, we open a read/write transaction on our database and delete one specific record out of ou...
... from the database deletedata(); }; function deletedata() { // open a read/write db transaction, ready for deleting the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error: ' + transaction.
error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to delete the specified record out of the object store var objectstorerequest = objectstore.delete("walk dog"); objectstorerequest.onsuccess = fun...
IDBObjectStore.get() - Web APIs
able 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 domexception of one of the following types: exception description transactioninactive
error this idbobjectstore's transaction is inactive. data
error the key or key range provided contains an invalid key. invalidstate
error the idbobjectstore has been deleted or removed. example in the following code snippet, we open a read/write transaction on our database and get one specific record from object store using get() — a sample record with ...
...data from the database getdata(); }; function getdata() { // open a read/write db transaction, ready for retrieving the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error: ' + transaction.
error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to get a record by key from the object store var objectstorerequest = objectstore.get("walk dog"); objectstorerequest.onsuccess = function(event) ...
IDBObjectStore.getAll() - Web APIs
); var 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. ...
... 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 type
error 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 domexception of one of the following types: exception description transactioninactive
error this idbobjectstore's transaction is inactive. data
error the key or key range provided contains an invalid key or is null. invalidstate
error the idbobjectstore has been deleted or removed. a type
error exception is thrown if the count parameter is not between 0 and 232-1 included. specifications specification status comment ...
IDBObjectStore.getAllKeys() - Web APIs
rd exists, 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. ...
... 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 type
error 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 domexception of one of the following types: exception description transactioninactive
error this idbobjectstore's transaction is inactive. data
error the key or key range provided contains an invalid key or is null. invalidstate
error the idbobjectstore has been deleted or removed. specifications specification status comment indexed database api draftthe definition of 'getallkeys()' in that specification. recomme...
IDBObjectStore.indexNames - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.indexnames); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); object...
...write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.indexnames); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our reque...
IDBObjectStore.keyPath - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.keypath); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectsto...
.../write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.keypath); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request ...
IDBObjectStore.put() - Web APIs
ld 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 domexception of one of the following types: exception description readonly
error the transaction associated with this operation is in read-only mode. transactioninactive
error this idbobjectstore's transaction is inactive. data
error any of the following conditions apply: the object store uses in-line keys or has a key generator, and a key parameter was provided. the object store uses out-of-line keys and has no key generator, and...
...s in-line keys or has a key generator, and a key parameter was provided. the object store uses out-of-line keys and has no key generator, and no key parameter was provided. the object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key. the key parameter was provided but does not contain a valid key. invalidstate
error the idbobjectstore has been deleted or removed. dataclone
error the data being stored could not be cloned by the internal structured cloning algorithm. parameters value the value to be stored. key the key to use to identify the record. if unspecified, it results to null. if the object store has a key generator (e.g. autoincrement) the key of the object must be pas...
IDBObjectStore.transaction - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.transaction); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); obj...
...rite db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.transaction); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our requ...
IDBOpenDBRequest.onblocked - Web APIs
abase is still in use (that is, not closed) somewhere, even after the versionchange event was sent. note: this feature is available in web workers. syntax idbopendbrequest.onblocked = function(event) { ... }; example var db; // let us open our database var request = indexeddb.open("todolist", 4); // these two event handlers act on the database being opened // successfully, or not request.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; request.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. // this is used a lot below db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data already in...
...st data already in the idb displaydata(); }; // this event handles the event whereby a new version of the // database needs to be created. either one has not been created // before, or a new version number has been submitted via the // window.indexeddb.open line above //it is only implemented in recent browsers request.onupgradeneeded = function(event) { var db = event.target.result; db.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); ... }; request.onblocked = function() { console.log("your database version can't be upgraded because the app is open somewhere else."); } specifications specification sta...
IDBOpenDBRequest.onupgradeneeded - Web APIs
var db; // request version 3 of the database. var request = window.indexeddb.open("library", 3); // this event handles the event whereby a new version of the // database needs to be created. either one has not been created // before, or a new version number has been submitted via the // window.indexeddb.open line above. request.onupgradeneeded = function(event) { db = request.result; db.on
error = function(
errorevent) { note.innerhtml += '<li>
error loading database.</li>'; }; if (event.oldversion < 1) { // version 1 is the first version of the database. var store = db.createobjectstore("books", {keypath: "isbn"}); var titleindex = store.createindex("by_title", "title", {unique: true}); var authorindex = store.createindex("by_author", "author"); } if (event.ol...
... var yearindex = bookstore.createindex("by_year", "year"); } if (event.oldversion < 3) { // version 3 introduces a new object store for magazines with two indexes. var magazines = db.createobjectstore("magazines"); var publisherindex = magazines.createindex("by_publisher", "publisher"); var frequencyindex = magazines.createindex("by_frequency", "frequency"); } }; request.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; request.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; db = request.result; populateanddisplaydata(); }; specifications specification status comment indexed database api 2.0the definition of 'onupgradeneeded' in that specification. recommendation ...
IDBOpenDBRequest - Web APIs
g example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these event handlers act on the database being opened. dbopenrequest.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable. this is used a lot below db = dbopenrequest.result; // run the displaydata() function to populate the task // listwith all the to-do list data...
...list data already in the idb displaydata(); }; // this event handles the event whereby a new version of // the database needs to be created either one has not // been created before, or a new version number has been // submitted via the window.indexeddb.open line above // it is only implemented in recent browsers dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false...
IDBRequest: success event - Web APIs
bubbles no cancelable no interface event event handler property onsuccess examples this example tries to open a database and listens for the success event using addeventlistener(): // open the database const openrequest = window.indexeddb.open('todolist', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.on
error = () => { console.log('
error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createinde...
...ctstore.createindex('year', 'year', { unique: false }); }; openrequest.addeventlistener('success', (event) => { console.log('database opened successfully!'); }); the same example, but using the onsuccess event handler property: // open the database const openrequest = window.indexeddb.open('todolist', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.on
error = () => { console.log('
error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createinde...
IDBTransaction.commit() - Web APIs
ve transaction. 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 invalidstate
error domexception. note: this feature is available in web workers. syntax transaction.commit(); parameters none. return value void. exceptions exception description invalidstate
error 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...
... invalidstate
error 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 success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("myobjstore"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success ...
IDBTransaction.db - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // repor...
... db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored su...
IDBTransaction.mode - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // repor...
... db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored su...
Browser storage limits and eviction criteria - Web APIs
lder title. note: if you are looking around in your profile at the data stored, you might see a fourth folder: persistent. basically, the persistent folder was renamed to permanent a while ago to keep upgrades/migration simpler. note: users shouldn’t add their own directories or files under <profile>/storage. this will cause storage initialization to fail; for example, open() will fire an
error event. storage limits the maximum browser storage space is dynamic — it is based on your hard drive size. the global limit is calculated as 50% of free disk space. in firefox, an internal browser tool called the quota manager keeps track of how much disk space each origin is using up, and deletes data if necessary. so if your hard drive is 500 gb, then the total storage for a browser is 250...
... freed and the operation can continue. note: the group limit can't be more than the global limit, despite the minimum group limit mentioned above. if you had a really low memory situation where the global limit was, say, 8 mb, then the group limit would also be 8 mb. note: if the group limit is exceeded, or if origin eviction couldn't free enough space, the browser will throw a quotaexceeded
error. note: in chrome the soft and hard storage quota limits has changed since m66. more information can be found here. lru policy when the available disk space is filled up, the quota manager will start clearing out data based on an lru policy — the least recently used origin will be deleted first, then the next one, until the browser is no longer over the limit. we track the "last access ti...
Checking when a deadline is due - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var request = objectstore.add(newitem[0]); in this section we create an object called newitem that store...
...ite db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction opened for task addition.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var request = objectstore.add(newitem[0]); in this section we create an object called newitem that stores the data in the format required to insert it into the database. the next few lines ...
LocalFileSystemSync - Web APIs
ts, see the counterpart article for the asynchronous api. example //taking care of the browser-specific prefix window.requestfilesystemsync = window.requestfilesystemsync || window.webkitrequestfilesystemsync; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success callback // and the last one is the
error callback // for denial of access and other
errors. var fs = requestfilesystemsync(temporary, 1024*1024 /*1mb*/); because you are using a synchronous api, you don't need success and
error callbacks. method overview filesystemsync requestfilesystemsync (in unsigned short type, in long long size) raises fileexception; entrysync resolvelocalfilesystemsyncurl (in domstring url) ...
...gned 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 fileexception 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 directory referred to by a local url. void resolvelocalfilesystemurl( in domstring url ); parameter url the url of a local f...
MediaCapabilities.decodingInfo() - Web APIs
rs 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. ...
...pabilitiesinfo interface containing three boolean attributes: supported smooth powerefficient exceptions a type
error is raised if the mediaconfiguration passed to the decodinginfo() method is invalid, either because the type is not video or audio, the contenttype is not a valid codec mime type, the media decoding configuration is not a valid value for the media decoding type, or any other
error in the media configuration passed to the method, including omitting values required in the media decoding configuration. example //create media configuration to be tested const mediaconfig = { type : 'file', // or 'media-source' audio : { contenttype : "audio/ogg", // valid content type channels : 2, // audio channels used by the track bitrate : 1...
MediaRecorder.resume() - Web APIs
the mediarecorder.resume() method (part of the mediarecorder api) is used to resume media recording when it has been previously paused. when the resume() method is invoked, the browser queues a task that runs the following steps: if mediarecorder.state is "inactive", raise a dom invalidstate
error and terminate these steps. if mediarecorder.state is not "inactive", continue to the next step. set mediarecorder.state to "recording". continue gathering data into the current blob. ...
... resume() method is invoked, the browser queues a task that runs the following steps: if mediarecorder.state is "inactive", raise a dom invalidstate
error and terminate these steps. if mediarecorder.state is not "inactive", continue to the next step. set mediarecorder.state to "recording". continue gathering data into the current blob. raise a resume event. syntax mediarecorder.resume()
errors an invalidstate
error is raised if the resume() method is called while the mediarecorder object’s mediarecorder.state is "inactive" — the recording cannot be resumed if it is not already paused; if mediarecorder.state is already "recording", resume() has no effect. example ... pause.onclick = function() { if(mediarecorder.state === "recording") { mediarecorder.pause(); ...
MediaStreamAudioSourceNode() - Web APIs
ns 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 invalidstate
error 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 mediastreamaudiosourcenode if (navigator.
... working draft ...
MediaStreamAudioSourceNode - Web APIs
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 invalidstate
error 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 keep the following in mi...
...so playing/pausing the stream can still be done through the media...
MediaStreamTrackAudioSourceNode() - Web APIs
ns 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 notsupported
error the specified context is not an audiocontext. invalidstate
error 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.audiocontext || window.webkitau...
... working draft ...
MediaStream Recording API - Web APIs
d to you so you can filter it, save it, or whatever. recording stops automatically when the source media stops playing. you can stop recording at any time by calling mediarecorder.stop(). note: individual blobs containing slices of the recorded media will not necessarily be individually playable. the media needs to be reassembled before playback. if anything goes wrong during recording, an
error event is sent to the mediarecorder. you can listen for
error events by setting up a on
error event handler. example here, we use an html canvas as source of the mediastream, and stop recording after 9 seconds. var canvas = document.queryselector("canvas"); // optional frames per second argument. var stream = canvas.capturestream(25); var recordedchunks = []; console.log(stream); var options ...
...e a stream from an <audio> or <video> element and use the captured stream (in this case, recording it and saving it to 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. mediarecorder
errorevent the interface that represents
errors thrown by the mediastream recording api. its
error property is a domexception that specifies that
error occurred. specifications specification status comment mediastream recording working draft initial definition ...
MediaTrackSupportedConstraints - Web APIs
atracksupportedconstraints dictionary establishes the list of constrainable properties recognized by the user agent or browser in its implementation of the mediastreamtrack object. an object conforming to mediatracksupportedconstraints is returned by mediadevices.getsupportedconstraints(). ...
...ject. an object conforming to mediatracksupportedconstraints is returned by mediadevices.getsupportedconstraints(). because of the way interface definitions in webidl work, if a constraint is requested but not supported, no
error will occur. instead, the specified constraints will be applied, with any unrecognized constraints stripped from the request.that can lead to confusing and hard to debug
errors, so be sure to use getsupportedconstraints() to retrieve this information before attempting to establish constraints if you need to know the difference between silently ignoring a constraint and a constraint being accepted. an actual constraint set is described using an object based on the mediatrackconstraints dictionary. to learn more about how constraints work, see capabilities, constraints...
Transcoding assets for Media Source Extensions - Web APIs
summary with your video properly encoded and adaptive bitrate media generated, you're now ready to begin adaptive bitrate streaming ...
...tput output ├── audio │ └── und ├── stream.mpd └── video ├── 1 ├── 2 ├── 3 ├── 4 └── 5 8 directories, 1 file note: mp4-dash-encode.py does not display ffmpeg
error messages. you can see it by specifying the -d option. note: if "invalid duration specification for force_key_frames: 'expr:eq(mod(n" is displayed as an
error message, modify mp4-dash-encode.py and remove two "'" from "-force_key_frames 'expr:eq(mod(n,%d),0)'". summary with your video properly encoded and adaptive bitrate media generated, you're now ready to begin adaptive bitrate streaming on the web using dash and mse. ...
Media Capture and Streams API (Media Stream) - Web APIs
the media capture and streams api, often called the media streams api or simply mediastream api, is an api related to webrtc which provides support for streaming audio and video data. it provides the interfaces and methods for working with the streams and their constituent tracks, the constraints associated with data formats, the success and
error callbacks when using the data asynchronously, and the events that are fired during the process. concepts and usage the api is based on the manipulation of a mediastream object representing a flux of audio- or video-related data. see an example in get the video. a mediastream consists of zero or more mediastreamtrack objects, representing various audio or video tracks. each mediastreamtrack may have one or more channels. the channel represents the ...
...you'll need to know about each of the interfaces that make up the media capture and streams api. blobevent canvascapturemediastreamtrack inputdeviceinfo mediadevicekind mediadeviceinfo mediadevices mediastream mediastreamconstraints mediastreamevent mediastreamtrack mediastreamtrackevent mediatrackconstraints mediatracksettings mediatracksupportedconstraints overconstrained
error url early versions of the media capture and streams api specification included separate audiostreamtrack and videostreamtrack interfaces—each based upon mediastreamtrack—which represented streams of those types. these no longer exist, and you should update any existing code to instead use mediastreamtrack directly. events addtrack ended muted overconstrained removetrack started ...
MessagePort - Web APIs
queued on the port (only needed when using eventtarget.addeventlistener; it is implied when using messageport.onmessage.) close() disconnects the port, so it is no longer active. event handlers inherits event handlers from its parent, eventtarget onmessage an eventlistener called when messageevent of type message is fired on the port—that is, when the port receives a message. ...
...tener; it is implied when using messageport.onmessage.) close() disconnects the port, so it is no longer active. event handlers inherits event handlers from its parent, eventtarget onmessage an eventlistener called when messageevent of type message is fired on the port—that is, when the port receives a message. onmessage
error an eventlistener called when a messageevent of type message
error is fired—that is, when it receives a message that cannot be deserialized. events message fired when a messageport object receives a message. also available via the onmessage property. message
error fired when a messageport object receives a message that can't be deserialized. also available via the onmessage
error property. example in the following example, you can see a new channel ...
NDEFWriter.write() - Web APIs
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. ...
...this write operation. return value a promise that resolves with undefined when and if the message transfer is successfully completed. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: abort
error the write operation was aborted with abortsignal passed in options. notallowed
error the permission for this operation was rejected or overwrite is false and there are already records on the tag. notsupported
error there is no nfc adapter compatible with web nfc, or the available nfc adapter does not support pushing messages, or connection can not be established. notreadable
error the ua is not allowed to access underlying nfc adapter (e.g., due to user preference). networker...
Navigator.registerProtocolHandler() - Web APIs
dle [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 security
error 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 url be over https. ...
... 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 url be over https. syntax
error the %s placeholder is missing from the handler url. permitted schemes for security reasons, registerprotocolhandler() restricts which schemes can be registered. a custom scheme may be registered as long as: the custom scheme's name begins with web+ the custom scheme's name includes at least 1 letter after the web+ prefix the custom scheme has only lowercase ascii letters in its name. ...
Navigator.requestMediaKeySystemAccess() - Web APIs
ble configuration will be used. return value a promise that, when resolved, delivers a mediakeysystemaccess object to your fulfillment handler function. ...
...akeysystemaccess 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 domexception whose name indicates what kind of
error occurred. notsupported
error 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). type
error either keysystem is an empty string or the supportedconfigurations array is empty. specifications spec...
Navigator.share() - Web APIs
then include an array of files in the call to navigator.share(): notice: that the sample handles feature detection by testing for navigator.canshare() rather than for navigator.share(). the data object passed to canshare() only supports the files property. image, video, audio, and text files can be sh...
...anshare() rather than for navigator.share(). the data object passed to canshare() only supports the files property. image, video, audio, and text files can be shared. if (navigator.canshare && navigator.canshare({ files: filesarray })) { navigator.share({ files: filesarray, title: 'pictures', text: 'our pictures.', }) .then(() => console.log('share was successful.')) .catch((
error) => console.log('sharing failed',
error)); } else { console.log(`your system doesn't support sharing files.`); } specifications specification status comment web share apithe definition of 'share()' in that specification. draft ...
Node.insertBefore() - Web APIs
se [ 2 ] : childelement is of type undefined let sp2 = undefined // non-existent node of id "childelement" parentdiv.insertbefore(newnode, sp2) // implicit dynamic cast to type node // end test case [ 2 ] // begin test case [ 3 ] : childelement is of type "undefined" ( string ) let sp2 = "undefined" // non-existent node of id "childelement" parentdiv.insertbefore(newnode, sp2) // generates "type
error: invalid argument" // end test case [ 3 ] </script> example 2 <div id="parentelement"> <span id="childelement">foo bar</span> </div> <script> // create a new, plain <span> element let sp1 = document.createelement("span") // get the reference element let sp2 = document.getelementbyid("childelement") // get the parent element let parentdiv = sp2.parentnode // insert the new element into bef...
...ild is null. the element is still appended to the parent, after the last child. since the parent element did not have a first child, it did not have a last child, either. consequently, the newly inserted element is the only element. specifications specification status comment domthe definition of 'node.insertbefore' in that specification. living standard fixes
errors in the insertion algorithm dom4the definition of 'node.insertbefore' in that specification. obsolete describes the algorithm in more detail document object model (dom) level 3 core specificationthe definition of 'node.insertbefore' in that specification. obsolete no notable changes document object model (dom) level 2 core specificationthe definition of 'nod...
ParentNode.append() - Web APIs
.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 hierarchyrequest
error: 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) // "some text" appending an e...
... = document.createelement("div") let p = document.createelement("p") parent.append("some text", p) console.log(parent.childnodes) // nodelist [ #text "some text", <p> ] parentnode.append() is unscopable the append() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ParentNode.prepend() - Web APIs
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 hierarchyrequest
error: 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.createelement("div"); parent.app...
...t.createelement("div"); var p = document.createelement("p"); parent.prepend("some text", p); console.log(parent.childnodes); // nodelist [ #text "some text", <p> ] parentnode.prepend() is unscopable the prepend() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ParentNode.querySelector() - Web APIs
queryselectorall() 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 syntax
error 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 l...
...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 syntax
error 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 dom4the definition ...
ParentNode.querySelectorAll() - Web APIs
ider the 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 syntax
error 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 l...
...pecial 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 syntax
error 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 <p> elements who...
PaymentAddress.country - Web APIs
specifications specification status comment payment request apithe definition of 'paymentaddress.country' in that specification. candidate recommendation initial definition. ...
...s located, or an empty string if no country is available, which frequently can be assumed to mean "same country as the site owner." usage notes if the payment handler validates the address and determines that the value of country is invalid, a call to paymentrequestupdateevent.updatewith() will be made with a details object containing a shippingaddress
errors field. that field contains an address
errors-compliant object whose country property is a string indicating the validation
error that occurred and, if possible, suggests how to fix it. specifications specification status comment payment request apithe definition of 'paymentaddress.country' in that specification. candidate recommendation initial definition. ...
PaymentResponse.complete() - Web APIs
tification, even if it normally would. this is the default value. 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 abort
error the document in which the payment request is taking place became inactive while the user interface was shown. invalidstate
error 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 reques...
... candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the d...
PaymentResponse: payerdetailchange event - Web APIs
payerdetailchange events are delivered by the payment request api to a paymentresponse object when the user makes changes to their personal information while filling out a payment request form. the event handler for payerdetailchange should check each value in the form that has changed and ensure that the values are valid. if any are invalid, appropriate
error messages should be configured and the retry() method should be called on the paymentresponse to ask the user to update the invalid entries. bubbles no cancelable no interface paymentrequestupdateevent event handler property onpayerdetailchange examples in the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to va...
...ame(payername)); oldpayername = payername; } if (oldpayeremail !== payeremail) { promisestovalidate.push(validateemail(payeremail)); oldpayeremail = payeremail; } if (oldpayerphone !== payerphone) { promisestovalidate.push(validatephone(payerphone)); oldpayerphone = payerphone; } // as each validation promise resolves, add the results of the // validation to the
errors list const
errors = await promise.all(promisestovalidate).then(results => results.reduce((
errors, result), object.assign(
errors, result)) ); // if we found any
errors, wait for them to be corrected if (object.getownpropertynames(
errors).length) { await response.retry(
errors); } else { // we have a good payment; send the data to the server await fetch("/pay-for-things...
PerformanceTiming - Web APIs
g.fetchstart. performancetiming.domainlookupend read only when the domain lookup is finished. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. performancetiming.connectstart read only when the request to open a connection is sent to the network. ...
...if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. ...
PromiseRejectionEvent() - Web APIs
the promiserejectionevent() constructor returns a newly created promiserejectionevent, which represents events fired when a javascript promise is rejected. with promise rejection events, it becomes possible to detect and report promises which fail and whose failures go unnoticed. it also becomes easier to write a global handler for
errors. there are two types of promiserejectionevent: unhandledrejection is sent by the javascript runtime when a promise is rejected but the rejection goes unhandled. a rejectionhandled event is emitted if a promise is rejected but the rejection is caught by a rejection handler.. syntax promiserejectionevent = promiserejectionevent(type, options); parameters the promiserejectionevent() constructor also inherits parameters from event(). type a string repre...
...onhandled" or "unhandledrejection", to match the event names of the possible (non-synthetic) promiserejectionevent events that user agents can actually fire). options an object specifying details about the rejection which occurred: promise the promise that was rejected. reason any value or object which represents the reason the promise was rejected. this can be anything from a numeric
error code to an
error domstring to an object which contains detailed information describing the situation resulting in the promise being rejected. return value a new promiserejectionevent configured as specified by the parameters. examples this example creates a new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire". the reason could just...
PublicKeyCredential - Web APIs
var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server ...
...ting credential from an authenticator, using navigator.credentials.get(). var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.
error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'publickeycredential interface' in that specification. recommendation initial definition. ...
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
ted 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 domexception "notallowed
error". examples var options = { allowcredentials: [ { transports: ["usb"], type: "public-key", id: new uint8array(26) // actually provided by the server }, { transports: ["internal"], type: "public-key", id: new uint8array(26) // actually provided by the server } ], challenge: new uint8array([/* bytes sent from the server */]) }; navigator.c...
... recommendation initial definition. ...
PushManager - Web APIs
rviceworker.js').then( function(serviceworkerregistration) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest. ...
...{ serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest. }, function(
error) { // during development it often helps to log
errors to the // console. in a production environment it might make sense to // also report information about
errors back to the // application server. console.log(
error); } ); }); specifications specification status comment push apithe definition of 'pushmanager' in that specification. working draft initial definition. ...
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. ...
...ional 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 operation
error 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 s...
RTCIceCandidateInit.candidate - Web APIs
handler for the icecandidate event. if your client-side signaling layer builds and transmits a json string including the candidate to the remote peer, the remote peer might handle receiving that json message like this: function goticecandidatemessage(msg) { var icecandidate = new rtcicecandidate({ candidate: msg.candidate; }); pc.addicecandidate(icecandidate).catch({ /* handle
error */ }); } it's helpful to note that for backward compatibility with older versions of the webrtc specification, the rtcicecandidate() constructor accepts the value of candidate as its only input, in place of the rtcicecandidateinit dictionary. that usage would change the above sample to look like this: function goticecandidatemessage(msg) { var icecandidate = new rtcicecandidate(msg.candida...
...ity with older versions of the webrtc specification, the rtcicecandidate() constructor accepts the value of candidate as its only input, in place of the rtcicecandidateinit dictionary. that usage would change the above sample to look like this: function goticecandidatemessage(msg) { var icecandidate = new rtcicecandidate(msg.candidate); pc.addicecandidate(icecandidate).catch({ /* handle
error */ }); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidateinit.candidate' in that specification. candidate recommendation initial specification. ...
RTCInboundRtpStreamStats.fecPacketsDiscarded - Web APIs
this can happen if all the packets covered by the fec packet have already been received or recovered using another fec packet, or if the fec packet arrived outside the recovery window and the lost rtp packets have already been skipped during playback as a result. ...
... this can happen if all the packets covered by the fec packet have already been received or recovered using another fec packet, or if the fec packet arrived outside the recovery window and the lost rtp packets have already been skipped during playback as a result. ...
RTCPeerConnection.getStats() - Web APIs
e 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: invalidaccess
error 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 using a promise. this version of getstats() is obsolete; in addition, the data it returns is entirely different f...
... for which to gather statistics. if this is null (the default value), statistics will be 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 domexception 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 spec...
RTCPeerConnection: negotiationneeded event - Web APIs
to create an event handler for negotiationneeded. its role is to create an sdp offer and send it through the signaling channel to the remote peer. pc.addeventlistener("negotiationneeded", ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle
error */ ); }, false); after creating the offer, the local end is configured by calling rtcpeerconnection.setlocaldescription(); then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer. the other peer should recognize this message and follow up by creating its own rtcpeerconnection, setting the remote description with set...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'negotiationneeded' in that specification. candidate recommendation ...
RTCPeerConnection.oniceconnectionstatechange - Web APIs
n be set to function which is passed a single input parameter: an event object describing the iceconnectionstatechange event which occurred. your code can look at the value of rtcpeerconnection.iceconnectionstate to determine what the new state is. ...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.oniceconnectionstatechange' in that specification. ...
RTCRtpStreamStats - Web APIs
object associated with this rtp stream. obsolete fields mediatype renamed to kind in the specification in february 2018. see browser compatibility in rtcrtpstreamstats.kind to determine when browsers made the transition. local-only measurements these properties are computed locally, and are only available to the device receiving the media stream. their primary purpose is to examine the
error resiliency of the connection, as they provide information about lost packets, lost frames, and how heavily compressed the data is. fircount a count of the total number of full intra request (fir) packets received by the sender. this statistic is only available to the device which is receiving the stream and is only available for video tracks. a fir packet is sent by the receiving end of the s...
...l when compared against the same codec. slicount the number of times the receiver notified the sender that one or more consecutive (in scan order) encoded video macroblocks have been lost or corrupted; this notification is sent by the receiver to the sender using a slice loss indication (sli) packet. this is a fairly technical part of how codecs work and while the higher this value is, the more
errors occurred in the stream, generally most of the time this value is only interesting to very intensively hardcore media developers. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcrtpstreamstats' in that specification. candidate recommendation initial definition. ...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
ach 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 invalidaccess
error 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 listed, the browser will t...
...ludes 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 invalidaccess
error 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 getcapabilit...
ReadableStream.ReadableStream() - Web APIs
s can be used by the developer to control the stream during set up. pull(controller) optional this method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. if pull() returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become
errored. the controller parameter passed to this method is a readablestreamdefaultcontroller or a readablebytestreamcontroller, depending on the value of the type property. this can be used by the developer to control the stream as more chunks are fetched. cancel(reason) optional this method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. i...
...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 range
error 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 readablestream.canc...
ReadableStreamBYOBRequest.respond() - Web APIs
examples tbd. specifications specification status comment streamsthe definition of 'respond()' in that specification. living standard initial definition. ...
... examples tbd. specifications specification status comment streamsthe definition of 'respond()' in that specification. living standard initial definition. ...
Request() - Web APIs
sing the get or head method cannot have a body. mode: the mode you want to use for the request, e.g., cors, no-cors, same-origin, or navigate. the default is cors. credentials: the request credentials you want to use for the request: omit, same-origin, or include. the default is same-origin. cache: the cache mode you want to use for the request. ...
... default is same-origin. cache: the cache mode you want to use for the request. redirect: the redirect mode to use: follow,
error, or manual. the default is follow. referrer: a usvstring specifying no-referrer, client, or a url. the default is about:client. integrity: contains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=).
errors type description type
error since firefox 43, request() will throw a type
error if the url has credentials, such as http://user:password@example.com. example in our fetch request example (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call. since we are fetching an image, we run body.blob on...
Request - Web APIs
ntains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). request.method read only contains the request's method (get, post, etc.) request.mode read only contains the mode of the request (e.g., cors, no-cors, same-origin, navigate.) request.redirect read only contains the mode for how redirects are handled. it may be one of follow,
error, or manual. request.referrer read only contains the referrer of the request (e.g., client). request.referrerpolicy read only contains the referrer policy of the request (e.g., no-referrer). request.url read only contains the url of the request. request implements body, so it also inherits the following properties: body read only a simple getter used to expose a readablestream of t...
...r readablestream type, so for adding a json object to the payload you need to stringify that object. you could then fetch this api request by passing the request object in as a parameter to a windoworworkerglobalscope.fetch() call, for example and get the response: fetch(request) .then(response => { if (response.status === 200) { return response.json(); } else { throw new
error('something went wrong on api server!'); } }) .then(response => { console.debug(response); // ... }).catch(
error => { console.
error(
error); }); specifications specification status comment fetchthe definition of 'request' in that specification. living standard initial definition ...
Response.type - Web APIs
the type read-only property of the response interface contains the type of the response. it can be one of the following: basic: normal, same origin response, with all headers exposed except “set-cookie” and “set-cookie2″. cors: response was received from a valid cross-origin request. certain headers and the body may be accessed.
error: network
error. no useful information describing the
error is available. the response’s status is 0, headers are empty and immutable. this is the type for a response obtained from response.
error(). opaque: response for “no-cors” request to cross-origin resource. severely restricted. opaqueredirect: the fetch request was made with redirect: "manual". the response's status is 0, headers are empty, body is null and trailer is empty. note: an ...
... syntax var mytype = response.type; value a responsetype string indicating the type of the response. ...
Using server-sent events - Web APIs
the code above generates an event every second, with the event type "ping". each event's data is a json object containing the iso 8601 timestamp corresponding to the time at which the event was generated. at random intervals, a simple message (with no event type) is sent. note: you can find a full example that uses the code shown in this article on github — see simple sse demo using php. ...
...object containing the iso 8601 timestamp corresponding to the time at which the event was generated. at random intervals, a simple message (with no event type) is sent. note: you can find a full example that uses the code shown in this article on github — see simple sse demo using php.
error handling when problems occur (such as a network timeout or issues pertaining to access control), an
error event is generated. you can take action on this programmatically by implementing the on
error callback on the eventsource object: evtsource.on
error = function(err) { console.
error("eventsource failed:", err); }; closing event streams by default, if the connection between the client and server closes, the connection is restarted. the connection is terminated with the .close() method. evtsour...
ServiceWorker - Web APIs
}); } else { // the current browser doesn't support service workers. } specifications specification status comment service workersthe definition of 'serviceworker' in that specification. working draft initial definiti...
...ive'; } if (serviceworker) { // logstate(serviceworker.state); serviceworker.addeventlistener('statechange', function (e) { // logstate(e.target.state); }); } }).catch (function (
error) { // something went wrong during registration. the service-worker.js file // might be unavailable or contain a syntax
error. }); } else { // the current browser doesn't support service workers. } specifications specification status comment service workersthe definition of 'serviceworker' in that specification. working draft initial definition. ...
ServiceWorkerContainer - Web APIs
itely until the serviceworkerregistration associated with the current page has an serviceworkerregistration.active worker. once that condition is met, it resolves with the serviceworkerregistration. events controllerchange occurs when the document's associated serviceworkerregistration acquires a new active worker. also available via the serviceworkercontainer.oncontrollerchange property.
error fired whenever an
error occurs in the associated service workers. also available via the serviceworkercontainer.on
error property. message occurs when incoming messages are received by the serviceworkercontainer object (e.g. via a messageport.postmessage() call.) also available via the serviceworkercontainer.onmessage property. methods serviceworkercontainer.register() creates or updat...
...n navigator) { // register a service worker hosted at the root of the // site using the default scope. navigator.serviceworker.register('/sw.js').then(function(registration) { console.log('service worker registration succeeded:', registration); // at this point, you can optionally do something // with registration. see /docs/web/api/serviceworkerregistration }).catch(function(
error) { console.log('service worker registration failed:',
error); }); // independent of the registration, let's also display // information about whether the current page is controlled // by an existing service worker, and when that // controller changes. // first, do a one-off check if there's currently a // service worker in control. if (navigator.serviceworker.controller) { ...
ServiceWorkerGlobalScope.onfetch - Web APIs
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 (response) { console.log('found response in cache:', resp...
...quest).then(function(response) { if (response) { console.log('found response in cache:', response); return response; } console.log('no response found in cache. about to fetch from network...'); return fetch(event.request).then(function(response) { console.log('response from network is:', response); return response; }).catch(function(
error) { console.
error('fetching failed:',
error); throw
error; }); }) ); }); specifications specification status comment service workersthe definition of 'event handlers' in that specification. working draft initial definition ...
ServiceWorkerGlobalScope - Web APIs
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 (response) { console.log('found response in cache:', resp...
...ent.request).then(function(response) { if (response) { console.log('found response in cache:', response); return response; } console.log('no response found in cache. about to fetch from network...'); return fetch(event.request).then(function(response) { console.log('response from network is:', response); return response; }, function(
error) { console.
error('fetching failed:',
error); throw
error; }); }) ); }); specifications specification status comment service workersthe definition of 'serviceworkerglobalscope' in that specification. working draft initial definition ...
ServiceWorkerRegistration.pushManager - Web APIs
ation) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.subscriptionid); console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest. ...
...).then( function(pushsubscription) { console.log(pushsubscription.subscriptionid); console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest. }, function(
error) { // during development it often helps to log
errors to the // console. in a production environment it might make sense to // also report information about
errors back to the // application server. console.log(
error); } ); }); specifications specification status comment push apithe definition of 'pushmanager' in that specification. working draft initial definition. ...
ServiceWorkerRegistration.showNotification() - Web APIs
e notification. image: a usvstring containing the url of an image to be displayed in the notification. lang: specify the lang used within the notification. this string must be a valid bcp 47 language tag. renotify: a boolean that indicates whether to suppress vibrations and audible alerts when reusing a tag value. if options’s renotify is true and options’s tag is the empty string a type
error will be thrown. the default is false. requireinteraction: indicates that on devices with sufficiently large screens, a notification should remain active until the user clicks or dismisses it. if this value is absent or false, the desktop version of chrome will auto-minimize notifications after approximately twenty seconds. the default value is false. silent: when set indicates that no sounds ...
...tly large screens, a notification should remain active until the user clicks or dismisses it. if this value is absent or false, the desktop version of chrome will auto-minimize notifications after approximately twenty seconds. the default value is false. silent: when set indicates that no sounds or vibrations should be made. if options’s silent is true and options’s vibrate is present a type
error 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 i...
SourceBuffer.changeType() - Web APIs
r 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. ...
...e 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 type
error the specified string is empty, rather than indicating a valid mime type. invalidstate
error 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. notsupported
error the specified mime type is not supported, or is not supported with the types of sourcebuffer objects present in the mediasource.sourcebuffers list. usage notes if the pare...
SourceBuffer - Web APIs
), or sourcebuffer.remove() operation is currently in progress. sourcebuffer.videotracks read only a list of the video tracks currently contained inside the sourcebuffer. event handlers sourcebuffer.onabort fired whenever sourcebuffer.appendbuffer() or sourcebuffer.appendstream() is ended by a call to sourcebuffer.abort(). sourcebuffer.updating changes from true to false. sourcebuffer.on
error fired whenever an
error occurs during sourcebuffer.appendbuffer() or sourcebuffer.appendstream(). sourcebuffer.updating changes from true to false. sourcebuffer.onupdate fired whenever sourcebuffer.appendbuffer() method or the sourcebuffer.remove() completes. sourcebuffer.updating changes from true to false. this event is fired before onupdateend. sourcebuffer.onupdateend fired whenever sour...
... codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.
error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystat...
SubtleCrypto.deriveKey() - Web APIs
s. 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. ...
... supported algorithms the three algorithms supported by derivekey() have quite different characteristics and are appropriate in different situations. ecdh ecdh (elliptic curve diffie-hellman) is a key-agreement algorithm. ...
WebGLRenderingContext.getProgramInfoLog() - Web APIs
the webglrenderingcontext.getprograminfolog returns the information log for the specified webglprogram object. it contains
errors that occurred during failed linking or validation of webglprogram objects. syntax gl.getprograminfolog(program); parameters program the webglprogram to query. return value a domstring that contains diagnostic messages, warning messages, and other information about the last linking or validation operation. when a webglprogram object is initially created, its information log will be a string of length 0. ...
...ation of webglprogram objects. syntax gl.getprograminfolog(program); parameters program the webglprogram to query. return value a domstring that contains diagnostic messages, warning messages, and other information about the last linking or validation operation. when a webglprogram object is initially created, its information log will be a string of length 0. examples checking program
errors var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.getprograminfolog(program); specifications specification status comment webgl 1.0the definition of 'getprograminfolog' in that specification. recommendation initial definition. ...
WebGLRenderingContext.readPixels() - Web APIs
nt_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. ...
...ype 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 is not framebuffer complete. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcon...
Boilerplate 1 - Web APIs
tting up webgl rendering context by now you are quite used to seeing the same pieces of html, css, and javascript repeated again and again. so we are going to hide them from now on. this would allow us to focus on the interesting pieces of code that are most relevant for learning webgl. specifically, the html has a <p> element that contains some descriptive text about the page and may also hold
error messages; a <canvas> element; and optionally a <button>. the css contains rules for body, canvas, and button. any additional non-trivial css and html will be displayed on the pages of specific examples. in following examples, we will use a javascript helper function, getrenderingcontext(), to initialize the webgl rendering context. by now, you should be able to understand what the function does.
...n the pages of specific examples. in following examples, we will use a javascript helper function, getrenderingcontext(), to initialize the webgl rendering context. by now, you should be able to understand what the function does. basically, it gets the webgl rendering context from the canvas element, initializes the drawing buffer, clears it black, and returns the initialized context. in case of
error, it displays an
error message and returns null. finally, all javascript code will run within an immediate function, which is a common javascript technique (see function). the function declaration and invocation will also be hidden. html <p>[ some descriptive text about the example. ]</p> <button>[ optional button element. ]</button> <canvas>your browser does not seem to support html5 can...
WebGL model view projection - Web APIs
vector. if this homogeneous coordinate is multiplied against a matrix with a translation then the translation is effectively stripped out. when numbers are extremely large (or extremely small) on computers they begin to become less and less precise because there are only so many ones and zeros that are used to represent them. the more operations that are done on larger numbers, the more and more
errors accumulate into the result. when dividing by w, this can effectively increase the precision of very large numbers by operating on two potentially smaller, less
error-prone numbers. the final benefit of using homogeneous coordinates is that they fit very nicely for multiplying against 4x4 matrices. a vertex must match at least one of the dimensions of a matrix in order to be multiplied against i...
... perpendicular to the floor, nearer than which everything gets clipped away. this is mapped to -1 in clip space, and should not be set to 0. farclippingplanedistance a positive number indicating the distance to the plane beyond which geometry is clipped away. this is mapped to 1 in clip space. this value should be kept reasonably close to the distance of the geometry in order to avoid precision
errors creeping in while rendering. in the latest version of the box demo, the computesimpleprojectionmatrix() method has been replaced with the computeperspectivematrix() method. cubedemo.prototype.computeperspectivematrix = function() { var fieldofviewinradians = math.pi * 0.5; var aspectratio = window.innerwidth / window.innerheight; var nearclippingplanedistance = 1; var farclippingplane...
Taking still photos with WebRTC - Web APIs
it returns a promise which we attach success and failure callbacks to. the success callback receives a stream object as input. it is the <video> element's source to our new stream. once the stream is linked to the <video> element, we start it playing by calling htmlmediae...
... }); here, we're calling mediadevices.getusermedia() and requesting a video stream (without audio). it returns a promise which we attach success and failure callbacks to. the success callback receives a stream object as input. it is the <video> element's source to our new stream. once the stream is linked to the <video> element, we start it playing by calling htmlmediaelement.play(). the
error callback is called if opening the stream doesn't work. this will happen for example if there's no compatible camera connected, or the user denied access. listen for the video to start playing after calling htmlmediaelement.play() on the <video>, there's a (hopefully brief) period of time that elapses before the stream of video begins to flow. to avoid blocking until that happens, we add an even...
WebRTC Statistics API - Web APIs
ated, and then setinterval() is used to set the function getconnectionstats() to be called every second. that function, in turn, uses getstats() to obtain statistics for the connection and to make use of that data. ...
...nd then setinterval() is used to set the function getconnectionstats() to be called every second. that function, in turn, uses getstats() to obtain statistics for the connection and to make use of that data. ...
WebSocket - Web APIs
n 1 websocket.closing 2 websocket.closed 3 properties websocket.binarytype the binary data type used by the connection. websocket.bufferedamount read only the number of bytes of queued data. websocket.extensions read only the extensions selected by the server. websocket.onclose an event listener to be called when the connection is closed. websocket.on
error an event listener to be called when an
error occurs. websocket.onmessage an event listener to be called when a message is received from the server. websocket.onopen an event listener to be called when the connection is opened. websocket.protocol read only the sub-protocol selected by the server. websocket.readystate read only the current state of the connection. websocket.url read onl...
...bsolute url of the websocket. methods websocket.close([code[, reason]]) closes the connection. websocket.send(data) enqueues data to be transmitted. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. close fired when a connection with a websocket is closed. also available via the onclose property
error fired when a connection with a websocket has been closed because of an
error, such as when some data couldn't be sent. also available via the on
error property. message fired when data is received through a websocket. also available via the onmessage property. open fired when a connection with a websocket is opened. also available via the onopen property. examples // create websocket co...
Writing a WebSocket server in C# - Web APIs
console.writeline("{0}", text); } else console.writeline("mask bit not set"); console.writeline(); } } } } client.html <!doctype html> <style> textarea { vertical-align: bottom; } #output { overflow: auto; } #output > p { overflow-wrap: break-word; } #output span { color: blue; } #output span.
error { color: red; } </style> <h2>websocket test</h2> <textarea cols=60 rows=6></textarea> <button>send</button> <div id=output></div> <script> // http://www.websocket.org/echo.html var button = document.queryselector("button"), output = document.queryselector("#output"), textarea = document.queryselector("textarea"), // wsuri = "ws://echo.websocket.org/", wsur...
...cket(wsuri); button.addeventlistener("click", onclickbutton); websocket.onopen = function (e) { writetoscreen("connected"); dosend("websocket rocks"); }; websocket.onclose = function (e) { writetoscreen("disconnected"); }; websocket.onmessage = function (e) { writetoscreen("<span>response: " + e.data + "</span>"); }; websocket.on
error = function (e) { writetoscreen("<span class=
error>
error:</span> " + e.data); }; function dosend(message) { writetoscreen("sent: " + message); websocket.send(message); } function writetoscreen(message) { output.insertadjacenthtml("afterbegin", "<p>" + message + "</p>"); } function onclickbutton() { var text = textarea.value; ...
Using bounded reference spaces - Web APIs
then... xrsession.requestanimationframe(ondrawframe); } if you compare this code to the code used in examples using unbounded reference spaces, yo...
...nbounded reference spaces, you'll confirm that, indeed, the biggest difference is the reference space type bounded-floor. the code begins by trying to get a bounded-floor reference space, but if that fails, it requests a local-floor space. in either case, successfully getting a reference space passes the new space into the function onrefspacecreated(). if neither type of space can be created, an
error handler is called (handle
error()). in either case, once a reference space has been created, it's handed off to a function called onrefspacecreated(), which takes over the process of setting up the space for use. it's important, however, to keep in mind that while a local-floor space provides a floor-relative space and is always available for immersive sessions, it also has significant differenc...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
function myanimationframecallback(time, frame) { let adjustedrefspace = applypositionoffsets(xrreferencespace); let pose = frame.getviewerpose(adjustedrefspace); animationframerequestid = frame.session.requestanimationframe(myanimationframecallback); if (pose) { let gllayer = frame.session.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); checkgl
error("binding the framebuffer"); gl.clearcolor(0, 0, 0, 1.0); gl.cleardepth(1.0); gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); checkgl
error("clearing the framebuffer"); const deltatime = (time - lastframetime) * 0.001; lastframetime = time; for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, vie...
...lor(0, 0, 0, 1.0); gl.cleardepth(1.0); gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); checkgl
error("clearing the framebuffer"); const deltatime = (time - lastframetime) * 0.001; lastframetime = time; for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); checkgl
error(`setting viewport for eye: ${view.eye}`); myrenderscene(gl, view, scenedata, deltatime); } } } the callback begins by calling a custom function, applypositionoffsets(), which takes a reference space and applies to its transform matrix any changes that need to be made to take into account things such as user inputs from devices not controlled by webxr, such as the keyboard and mouse...
Web Speech API - Web APIs
details on using these features, see using the web speech api. web speech api interfaces speech recognition speechrecognition the controller interface for the recognition service; this also handles the speechrecognitionevent sent from the recognition service. speechrecognitionalternative represents a single word that has been recognised by the speech recognition service. speechrecognition
error represents
error messages from the recognition service. speechrecognitionevent the event object for the result and nomatch events, and contains all the data associated with an interim or final speech recognition result. speechgrammar the words or patterns of words that we want the recognition service to recognize. speechgrammarlist represents a list of speechgrammar objects. speechrecogni...
... speechrecognitionresultlist represents a list of speechrecognitionresult objects, or a single one if results are being captured in continuous mode. speech synthesis speechsynthesis the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides. speechsynthesis
errorevent contains information about any
errors that occur while processing speechsynthesisutterance objects in the speech service. speechsynthesisevent contains information about the current state of speechsynthesisutterance objects that have been processed in the speech service. speechsynthesisutterance represents a speech request. it contains the content the speech service should read and info...
window.dump() - Web APIs
o debug javascript. the message passed to dump() is sent to the system console (native console) if the firefox process was started with the -console option. if the -console option was not specified then the output goes to stderr. output from dump() is not sent to the browser console. output can be sent to the browser console using console.log(). privileged code can also use components.utils.report
error and nsiconsoleservice to log messages to the
error console/browser console. dump() is also available to xpcom components implemented in javascript, even though window is not the global object in components. it is also explicitly made available in sandboxes. however, this use of dump is not affected by the preference mentioned below -- it will always be shown. it is therefore advisable to either ...
...ither check this preference yourself or use a debugging preference of your own to make sure you don't send lots of debugging content to a user's console when they might not be interested in it at all. note that dump output from xpcom components goes to stderr, while dump called elsewhere will output to stdout. in gecko dump() is disabled by default – it doesn't do anything but doesn't raise an
error either. to see the dump output you have to enable it by setting the preference browser.dom.window.dump.enabled to true. you can set the preference in about:config or in a user.js file. note: this preference is not listed in about:config by default, you may need to create it (right-click the content area -> new -> boolean). on windows, you will need a console to actually see anything. if you don'...
Window.getComputedStyle() - Web APIs
th css property names. syntax var style = window.getcomputedstyle(element [, pseudoelt]); element the element for which to get the computed style. pseudoeltoptional a string specifying the pseudo-element to match. omitted (or null) for real elements. the returned style is a live cssstyledeclaration object, which updates automatically when the element's styles are changed. throws type
error if the passed object is not an element or the pseudoelt is not a valid pseudo-element selector or is ::part() or ::slotted(). note: valid pseudo-element selector refers to syntactic validity, e.g. ::unsupported is considered valid, even though the pseudo-element itself is not supported. examples in this example we style a <p> element, then retrieve those styles using getcomputedstyle...
...style is read-only, and should be used to inspect the element's style — including those set by a <style> element or an external stylesheet. the element.style object should be used to set styles on that element, or inspect styles directly added to it from javascript manipulation or the global style attribute. the first argument must be an element. non-elements, like a text node, will throw an
error. defaultview in many code samples, getcomputedstyle is used from the document.defaultview object. in nearly all cases, this is needless, as getcomputedstyle exists on the window object as well. it's likely the defaultview pattern was a combination of folks not wanting to write a testing spec for window and making an api that was also usable in java. use with pseudo-elements getcomputedstyle c...
Window.requestFileSystem() - Web APIs
pi, requestfilesystem() is especially non-standard; only chrome implements it, and all other browser makers have decided that they will not implement it. it has even been removed from the proposed specification. do not use this method! syntax this method is prefixed with webkit in all browsers that implement it (that is, google chrome). window.requestfilesystem(type, size, successcallback[,
errorcallback]); parameters type the type of storage to request. specify window.temporary if it's acceptable for the browser to delete the files at its own discretion, such as if storage space runs low, or window.persistent if you need the files to remain in place unless the user or the web site or app explicitly permit it. persistent storage requires that the user grant the site quota. size the...
...te or app explicitly permit it. persistent storage requires that the user grant the site quota. size the amount of storage space you wish to have allocated for your app's use. successcallback a function which is invoked when the file system has been successfully obtained. the callback receives a single parameter: a filesystem object representing the file system the app has permission to use.
errorcallback optional an optional parameter specifying a function which is called if an
error occurs while attempting to obtain the file system, or if the user denies permission to create or access the file system. the callback receives as input a single parameter: a file
error object describing the
error. return value undefined example specifications specification status comment ...
WorkerGlobalScope.self - Web APIs
etc. this provides a full list of the objects available to that worker scope, so it is quite a useful test if you want to see whether something is available to your worker or not. we also maintain a list of functions and classes available to web workers. specifications specification status comment html living standardthe defi...
...etc. this provides a full list of the objects available to that worker scope, so it is quite a useful test if you want to see whether something is available to your worker or not. we also maintain a list of functions and classes available to web workers. specifications specification status comment html living standardthe definition of 'self'...
WritableStreamDefaultWriter.ready - Web APIs
xtencoder(); var encoded = encoder.encode(message, {stream: true}); encoded.foreach(function(chunk) { // make sure the stream and its writer are able to // receive data. ...
... living standard initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
WritableStreamDefaultWriter.releaseLock() - Web APIs
syntax writablestreamdefaultwritere.releaselock() parameters none. return value undefined. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... ...
... syntax writablestreamdefaultwritere.releaselock() parameters none. return value undefined. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... ...
XMLHttpRequest.upload - Web APIs
to track its process. the following events can be triggered on an upload object and used to monitor the upload: event event listener description loadstart onloadstart the upload has begun. progress onprogress periodically delivered to indicate the amount of progress made so far. abort onabort the upload operation was aborted.
error on
error the upload failed due to an
error. load onload the upload completed successfully. timeout ontimeout the upload timed out because a reply did not arrive within the time interval specified by the xmlhttprequest.timeout. loadend onloadend the upload finished. this event does not differentiate between success or failure, and is sent at the en...
...the upload completed successfully. timeout ontimeout the upload timed out because a reply did not arrive within the time interval specified by the xmlhttprequest.timeout. loadend onloadend the upload finished. this event does not differentiate between success or failure, and is sent at the end of the upload regardless of the outcome. prior to this event, one of load,
error, abort, or timeout will already have been delivered to indicate why the upload ended. specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest - Web APIs
obsolete since gecko 22 this gecko-only feature, a boolean, was removed in firefox/gecko 22. please use server-sent events, web sockets, or responsetext from progress events instead. event handlers onreadystatechange as a property of the xmlhttprequest instance is supported in all browsers. since then, a number of additional event handlers have been implemented in various browsers (onload, on
error, onprogress, etc.). see using xmlhttprequest. more recent browsers, including firefox, also support listening to the xmlhttprequest events via standard addeventlistener() apis in addition to setting on* properties to a handler function. methods xmlhttprequest.abort() aborts the request if it has already been sent. xmlhttprequest.getallresponseheaders() returns all the response headers, se...
...st. this method is to be used from native code; to initialize a request from javascript code, use open() instead. see the documentation for open(). xmlhttprequest.sendasbinary() a variant of the send() method that sends binary data. events abort fired when a request has been aborted, for example because the program called xmlhttprequest.abort(). also available via the onabort property.
error fired when the request encountered an
error. also available via the on
error property. load fired when an xmlhttprequest transaction completes successfully. also available via the onload property. loadend fired when a request has completed, whether successfully (after load) or unsuccessfully (after abort or
error). also available via the onloadend property. loadstart fired when a request...
XMLSerializer.serializeToString() - Web APIs
zer 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 type
error the specified rootnode is not a compatible node type. the root node must be either node or attr. invalidstate
error the tree could not be successfully serialized, probably due to issues with the content's compatibility with xml serialization. syntax
error a serialization of html was requested but could not succeed due to the content not being well-formed. usage notes compatible node types ...
... root 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 type
error 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 ...
XRWebGLLayer() - Web APIs
at 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. ...
...fault 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 invalidstate
error 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. operation
error the resources (including memory buffers) needed for the layer to operate could not be allocated. specifications specifi...
XRWebGLLayer.framebuffer - Web APIs
e default webgl framebuffer: opaque framebuffers may support anti-aliasing, even under webgl 1.0, which don't normally do so. opaque framebuffers' attachments (buffers and the like) can't be inspected or changed. calling functions such as framebuffertexture2d(), framebufferrenderbuffer(), deleteframebuffer(), or getframebufferattachmentparameter() on an opaque framebuffer results in the webgl
error invalid_operation (0x0502). opaque framebuffers are considered incomplete and are not available for rendering other than while executing the requestanimationframe() callback. attempting to clear, draw to, or read from the framebuffer results in a webgl invalid_framebuffer_operation
error (0x0506). calling checkframebufferstatus() on the webgl context from outside the animation frame callback cau...
...ramebuffers are considered incomplete and are not available for rendering other than while executing the requestanimationframe() callback. attempting to clear, draw to, or read from the framebuffer results in a webgl invalid_framebuffer_operation
error (0x0506). calling checkframebufferstatus() on the webgl context from outside the animation frame callback causes the webgl framebuffer_unsupported
error (0x8cdd) to be reported. opaque framebuffers initialized with the depth property set to false will not have a depth buffer and will rely on the coordinates alone to determine distance. opaque framebuffers initialized without specifying a stencil will not have a stencil buffer. opaque framebuffers will not have an alpha channel available unless the alpha property is true when creating the layer...
ARIA live regions - Accessibility
the live region will only be announced for the planet finally chosen. ...
...alerts are particularly important for client side validation notices to users. (tbd: link to aria form tutorial with aria info) to maximize compatibility, some people recommend adding a redundant aria-live="assertive" when using this role. however, adding both aria-live and role="alert" causes double speaking issues in voiceover on ios. ...
Using the alert role - Accessibility
one of those opinions and therefore not normative. examples example 1: adding the role in the html code the snippet below shows how the alert role is added directly into the html source code. the moment the element finishes loading the screen reader should be notified of the alert. if the element was already in the original source code when the page loaded, the screen reader will announce the
error immediately after announcing the page title. <h2 role="alert">your form could not be submitted because of 3 validation
errors.</h2> example 2: dynamically adding an element with the alert role this snippet dynamically creates an element with an alert role and adds it to the document structure. let myalert = document.createelement("p"); myalert.setattribute("role", "alert"); let myalerttext = ...
...setattribute("role", "alert"); example 4: making an element with an alert role visible if an element already has role="alert" and is initially hidden using css, making it visible will cause the alert to fire as if it was just added to the page. this means that an existing alert can be "reused" multiple times. note: in most cases this approach is not recommended, because it's not ideal to hide
error or alert text that is currently not applicable. users of older assistive technology may still be able to perceive the alert text even when the alert does not currently applies, causing users to incorrectly believe that there is a problem. .hidden { display:none; } <p id="expirationwarning" role="alert" class="hidden">your log in session will expire in 2 minutes</p> // removing the 'hidden'...
Using the aria-invalid attribute - Accessibility
clude formats such as email addresses or telephone numbers. aria-invalid can also be used to indicate that a required field has not been filled in.the attribute should be programmatically set as a result of a validation process. this attribute can be used with any typical html form element; it is not limited to elements that have an aria role assigned. values vocabulary: false (default) no
errors detected grammar a grammatical
error has been detected. spelling a spelling
error has been detected. true the value has failed validation. any value not in this vocabulary should be treated as true. possible effects on user agents and assistive technology user agents should inform the user when a field is invalid. application authors should provide suggestions for correcting the probl...
...lidity(aid, asearchterm, amsg){ var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); updatealert(amsg); } else { elem.setattribute("aria-invalid", "false"); updatealert(); } } the snippet below shows the alert functions, which add (or remove) the
error message: function updatealert(msg) { var oldalert = document.getelementbyid("alert"); if (oldalert) { document.body.removechild(oldalert); } if (msg) { var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var content = document.createtextnode(msg); newalert.appen...
Using ARIA: Roles, states, and properties - Accessibility
esentation row rowgroup rowheader separator table term textbox toolbar tooltip landmark roles banner complementary contentinfo form main navigation region search live region roles alert log marquee status timer window roles alertdialog dialog states and properties widget attributes aria-autocomplete aria-checked aria-current aria-disabled aria-
errormessage aria-expanded aria-haspopup aria-hidden aria-invalid aria-label aria-level aria-modal aria-multiline aria-multiselectable aria-orientation aria-placeholder aria-pressed aria-readonly aria-required aria-selected aria-sort aria-valuemax aria-valuemin aria-valuenow aria-valuetext live region attributes aria-live aria-relevant aria-atomic aria-busy drag & drop ...
...readonly aria-required aria-selected aria-sort aria-valuemax aria-valuemin aria-valuenow aria-valuetext live region attributes aria-live aria-relevant aria-atomic aria-busy drag & drop attributes aria-dropeffect aria-dragged relationship attributes aria-activedescendant aria-colcount aria-colindex aria-colspan aria-controls aria-describedby aria-details aria-
errormessage aria-flowto aria-labelledby aria-owns aria-posinset aria-rowcount aria-rowindex aria-rowspan aria-setsize microsoftedge-specific properties x-ms-aria-flowfrom ...
Accessibility documentation index - Accessibility
programmatically expose dynamic content changes in a way that can be announced by assistive technologies. 8 forms aria, accessibility the following pages provide various techniques for improving the accessibility of web forms: 9 alerts aria, accessibility, forms, web you have a form — a contact form, for example — that you want to put some accessible
error checking into. examples of common problems include e-mail addresses which are not valid, or a name field which does not contain at least a first name or a surname. 10 basic form hints aria, accessibility, forms when implementing forms using traditional html form-related elements, it is important to provide labels for controls, and explicitly associate a label with its control...
...ontrol, dialog, or other website feature should be given a descriptive name or label to allow users of assistive technologies to understand what its purpose is and to be able to understand and operate it correctly. 103 understandable accessibility, help, language, navigation, principle 3, text, understandable, wcag, web content accessibility guidelines, abbreviations, consistency,
error messages, form validation, labels, slang this article provides practical advice on how to write your web content so that it conforms to the success criteria outlined in the understandable principle of the web content accessibility guidelines (wcag) 2.0 and 2.1. understandable states that information and the operation of user interface must be understandable. 104 web accessibility...
Pseudo-elements - CSS: Cascading Style Sheets
on (:). this distinguishes pseudo-classes from pseudo-elements. however, since this distinction was not present in older versions of the w3c spec, most browsers support both syntaxes for the original pseudo-elements. ...
...tinction was not present in older versions of the w3c spec, most browsers support both syntaxes for the original pseudo-elements. ...
overflow - CSS: Cascading Style Sheets
...
...} examples setting different overflow values for text p { width: 12em; height: 6em; border: dotted; overflow: visible; /* content is not clipped */ } visible (default) sed ut perspiciatis unde omnis iste natus
error sit voluptatem accusantium doloremque laudantium. p { overflow: hidden; /* no scrollbars are provided */ } overflow: hidden sed ut perspiciatis unde omnis iste natus
error sit voluptatem accusantium doloremque laudantium. p { overflow: scroll; /* always show scrollbars */ } overflow: scroll sed ut perspiciatis unde omnis iste natus
error sit voluptatem accusantium doloremque laudantium. p { overflow: auto; /* append scrollbars if necessary */ } overflow: auto sed ut perspiciatis unde omnis iste natus
error sit voluptatem accusantium doloremque laudantium. ...
text-decoration-line - CSS: Cascading Style Sheets
nates between visible and invisible). conforming user agents may simply not blink the text. this value is deprecated in favor of css animations. formal definition initial valuenoneapplies toall elements. ...
...sible and invisible). conforming user agents may simply not blink the text. this value is deprecated in favor of css animations. formal definition initial valuenoneapplies toall elements. ...
text-shadow - CSS: Cascading Style Sheets
e>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ...
...tis unde omnis iste natus
error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore.</p> multiple shadows .white-text-with-blue-shadow { text-shadow: 1px 1px 2px black, 0 0 1em blue, 0 0 0.2em blue; color: white; font: 1.5em georgia, serif; } <p class="white-text-with-blue-shadow">sed ut perspiciatis unde omnis iste natus
error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore.</p> specifications specification status comment css text decoration module level 3the definition of 'text-shadow' in that specification. candidate recommendation the css property text-shadow was improperly defined in css2 and dropped in css2 (level 1).
DOM onevent handlers - Developer guides
nchoronclick(event)'); log(`changed the property to: <code> ${el.onclick.tostring()} </code>`); log(`now even the html attribute has changed: <code> ${el.getattribute("onclick")} </code><br>`); result for historical reasons, some attributes/properties on the <body> and <frameset> elements instead set event handlers on their parent window object. (the html specification names these: onblur, on
error, onfocus, onload, and onscroll.) event handler's parameters, this binding, and the return value when the event handler is specified as an html attribute, the specified code is wrapped into a function with the following parameters: event — for all event handlers except on
error. event, source, lineno, colno, and
error for the on
error event handler. note that the event parameter actually con...
... onload, and onscroll.) event handler's parameters, this binding, and the return value when the event handler is specified as an html attribute, the specified code is wrapped into a function with the following parameters: event — for all event handlers except on
error. event, source, lineno, colno, and
error for the on
error event handler. note that the event parameter actually contains the
error message as a string. when the event handler is invoked, the this keyword inside the handler is set to the dom element on which the handler is registered. for more details, see the this keyword documentation. the return value from the handler determines if the event is canceled. the specific handling of the return value depends on the kind of event; for details, see "the event handler processin...
Using HTML sections and outlines - Developer guides
conclusion the new semantic elements introduced in html5 bring the ability to describe the structure of a web document in a standard way. they bring a big advantage for people having html5 browsers and needing the structure to help them understand the page...
...led.</strong></p> <p>javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> note: this code will also cause the html validator to return
errors. this isn't a really bad thing neccessarily — sites will often have a few validation
errors — but it's something to be aware of still. conclusion the new semantic elements introduced in html5 bring the ability to describe the structure of a web document in a standard way. they bring a big advantage for people having html5 browsers and needing the structure to help them understand the page, for instance people needing the help of some assistive technology. these new semantic elemen...
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
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 a tainted canvas will result in an
error: calling getimagedata() on the canvas's context calling toblob() on the <canvas> element itself calling todataurl() on the canvas attempting any of these when the canvas is tainted will cause a security
error to be thrown. this protects users from having private data exposed by using images to pull information from remote web sites without permission. storing an image from a foreign origin...
...this event is triggered once the downloaded data is all available. it begins by creating a new <canvas> element that we'll use to convert the image into a data url, and by getting access to the canvas's 2d drawing context (canvasrenderingcontext2d) in the variable con...
<img>: The Image Embed element - HTML: Hypertext Markup Language
ttribute is required, and contains the path to the image you want to embed. the alt attribute holds a text description of the image, which isn't mandatory but is incredibly useful for accessibility — screen readers read this description out to their users so they know what the image means. alt text is also displayed on the page if the image can't be loaded for some reason: for example, network
errors, content blocking, or linkrot. there are many other attributes to achieve various purposes: referrer/cors control for security and privacy: see crossorigin and referrerpolicy. use both width and height to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts. responsive image hints with sizes and srcset (see also the <picture>...
...none built-in; add-ons required webp web picture format image/webp .webp chrome, edge, firefox, opera the abbreviation for each format links to a longer description of the format, its capabilities, and detailed browser compatibility information; including which versions introduced support and specific special features that may have been introduced later. image loading
errors if an
error occurs while loading or rendering an image, and an on
error event handler has been set on the
error event, that event handler will get called. this can happen in a number of situations, including: the src attribute is empty ("") or null. the src url is the same as the url of the page the user is currently on. the image is corrupted in some way that prevents it from being loaded.
<input type="text"> - HTML: Hypertext Markup Language
input value length you can specify a minimum length (in characters) for the entered value using the minlength attribute; similarly, use maxlength to set the maximum length of the entered value, in characters. the example below requires that the entered value be 4–8 characters in length. <form> <div> <label for="uname">choose a username: </label> <input type="text" id="una...
...if you try to enter more than 8 characters, the browser won't let you. note: if you specify a minlength but do not specify required, the input is considered valid, since the user is not required to specify a value. specifying a pattern you can use the pattern attribute to specify a regular expression that the inputted value must match in order to be ...
<input type="url"> - HTML: Hypertext Markup Language
s a valid url, and also in a myco domain." this isn't perfect, but it is good enough for this simple demo's requirements. it's advisable to use the title attribute along with pattern. if you do, the title must describe the pattern; it should explain what format the data should take on, rather than any other information. that's because the title may be displayed or spoken as part of a validation
error message. for example, the browser might present the message "the entered text doesn't match the required pattern." followed by your specified title. if your title is something like "url", the result would be the message "the entered text doesn't match the required pattern. url", which is not a good user experience. that's why, instead, we specify the string "the url must be in a myco domain". by...
...er might present the message "the entered text doesn't match the required pattern." followed by your specified title. if your title is something like "url", the result would be the message "the entered text doesn't match the required pattern. url", which is not a good user experience. that's why, instead, we specify the string "the url must be in a myco domain". by doing that, the resulting full
error message might be something like "the entered text doesn't match the required pattern. the url should be in a myco domain." note: if you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful
error messages there to aid you in solving the problem. examples there's not much else to say about url ty...
<input type="week"> - HTML: Hypertext Markup Language
ding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the result here is that only weeks between w01 and w52 in 2017 will be seen as valid and be selectable in supporting browsers. making week values required in addition you can use the required attribute to make filling in the week mandatory. as a result, supporting browsers will display an
error if you try to submit an empty week field. let's look at an example; here we've set minimum and maximum weeks, and also made the field required: <form> <div> <label for="week">what week would you like to start?</label> <input id="week" type="week" name="week" min="2017-w01" max="2017-w52" required> <span class="validity"></span> </div> <div> <input type="submit" ...
...ks, and also made the field required: <form> <div> <label for="week">what week would you like to start?</label> <input id="week" type="week" name="week" min="2017-w01" max="2017-w52" required> <span class="validity"></span> </div> <div> <input type="submit" value="submit form"> </div> </form> if you try to submit the form with no value, the browser displays an
error. try playing with the example now: here's'a screenshot for those of you who aren't using a supporting browser: important: html form validation is not a substitute for scripts that ensure that the entered data is in the proper format. it's far too easy for someone to make adjustments to the html that allow them to bypass the validation, or to remove it entirely. it's also possible for someo...
<script>: The Script element - HTML: Hypertext Markup Language
inuing to parse. defer has a similar effect in this case. this is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. see browser compatibility for notes on browser support. see also async scripts for asm.js. crossorigin normal script elements pass minimal information to the window.on
error for scripts which do not pass the standard cors checks. to allow
error logging for sites which use a separate domain for static media, use this attribute. see cors settings attributes for a more descriptive explanation of its valid arguments. defer this boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firi...
...er or type="module" attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page. the script should be served with the text/javascript mime type, but browsers are lenient and only block them if the script is served with an image type (image/*); a video type (video/*); an audio (audio/*) type; or text/csv. if the script is blocked, an
error is sent to the element, if not a load event is sent. examples basic usage these examples show how to import (an external) script using the <script> element. <script src="javascript.js"></script> and the following examples show how to put (an inline) script inside the <script> element. <script> alert("hello world!"); </script> module fallback browsers that support the module value for t...
Using the application cache - HTML: Hypertext Markup Language
knows it needs to fetch all the resources again. if the manifest file has changed, all the files listed in the manifest—as well as those added to the cache by calling applicationcache.add()—are fetched into a temporary cache, following the appropriate http caching rules. for each file fetched into this temporary cache, the browser sends a progress event to the applicationcache object. if any
errors occur, the browser sends an
error event, and the update halts. once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a cached event is sent to the applicationcache object. since the document has already been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manuall...
...e cache manifest file http://www.example.com/example.appcache includes the following content: cache manifest fallback: example/bar/ example.html any request to http://www.example.com/example/bar/ or any of its subdirectories and their content cause the browser to issue a network request to attempt to load the requested resource. if the attempt fails, due to either a network failure or a server
error of some kind, the browser loads the file example.html instead. cache states each application cache has a state, which indicates the current condition of the cache. caches that share the same manifest uri share the same cache state, which can be one of the following: uncached a special value that indicates that an application cache object is not fully initialized. idle the application cach...
Browser detection using the user agent - HTTP
follows. in 2017, chrome unflagged experimental lookbehind support in regular expressions, but no other browser supported it. so, you might have thought to do this: // this code snippet splits a string in a special notation if (navigator.useragent.indexof("chrome") !== -1){ // yes! the user is suspected to support look-behind regexps // do not use /(?<=[a-z])/. it will cause a syntax
error in // browsers that do not support look-behind expressions // because all browsers parse the entire script, including // sections of the code that are never executed. var camelcaseexpression = new regexp("(?<=[a-z])"); var splitupstring = function(str) { return (""+str).split(camelcaseexpression); }; } else { /*this fallback code is much less performant, but...
...ng for this. lastly, the above code snippets bring about a critical issue with cross-browser coding that must always be taken into account. don't unintentionally use the api you are testing for in unsupported browsers. this may sound obvious and simple, but sometimes it is not. for example, in the above code snippets, using lookbehind in short-regexp notation (e.g. /reg/igm) will cause a parser
error in unsupported browsers. thus, in the above example, you would use new regexp("(?<=look_behind_stuff)"); instead of /(?<=look_behind_stuff)/, even in the lookbehind supported section of your code. progressive enhancement this design technique involves developing your web site in 'layers', using a bottom-up approach, starting with a simpler layer and improving the capabilities of the site in s...
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
der ‘access-control-allow-methods’ what went wrong? the http method being used by the cors request is not included in the list of methods specified by the response's access-control-allow-methods header. ...
...ified by the response's access-control-allow-methods header. this header specifies a comma-delineated list of the http methods which may be used when using cors to access the url specified in the request; if the request is using any other method, this
error occurs. for example, if the response includes: access-control-allow-methods: get,head,post trying to use a put request will fail with this
error. make sure your code only uses the permitted http methods when accessing the service. note: if the server includes any unrecognized or undefined method names in its access-control-allow-methods header, a different
error occurs: reason: invalid token ‘xyz' in cors header ‘access-control-allow-methods’. ...
Cross-Origin Resource Sharing (CORS) - HTTP
st with certain mime types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the http options request method, and then, upon "approval" from the server, sending the actual request. servers can also inform clients whether "credentials" (such as cookies and http authentication) should be sent with requests. cors failures result in
errors, but for security reasons, specifics about the
error are not available to javascript. all the code knows is that an
error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. subsequent sections discuss scenarios, as well as provide a breakdown of the http headers used. examples of access control scenarios we present three scenarios...
...ing another preflight request. in this case, 86400 seconds is 24 hours. note that each browser has a maximum internal value that takes precedence when the access-control-max-age is greater. preflighted requests and redirects not all browsers currently support following redirects after a preflighted request. if a redirect occurs after a preflighted request, some browsers currently will report an
error message such as the following. the request was redirected to 'https://example.com/foo', which is disallowed for cross-origin requests that require preflight request requires preflight, which is disallowed to follow cross-origin redirect the cors protocol originally required that behavior but was subsequently changed to no longer require it. however, not all browsers have implemented the ch...
HTTP conditional requests - HTTP
e potential problem: if the downloaded resource has been modified between both downloads, the obtained ranges will correspond to two different versions of the resource, and the final document will be corrupted. to prevent this, conditional requests are used. for ranges, there are two ways of doing this. the more flexible one makes use of if-unmodified-since and if-match and the server returns an
error if the precondition fails; the client then restarts the download from the beginning: even if this method works, it adds an extra response/request exchange when the document has been changed. this impairs performance, and http has a specific header to avoid this scenario: if-range: this solution is more efficient, but slightly less flexible, as only one etag can be used in the condition. rar...
...rency by successfully allowing the first client submitting an update. all subsequent updates, based on the now obsolete version of the resource, are rejected: this is implemented using the if-match or if-unmodified-since headers. if the etag doesn't match the original file, or if the file has been modified since it has been obtained, the change is simply rejected with a 412 precondition failed
error. it is then up to the client to deal with the
error: either by notifying the user to start again (this time on the newest version), or by showing the user a diff of both versions, helping them decide which changes they wish to keep. dealing with the first upload of a resource the first upload of a resource is an edge case of the previous. like any update of a resource, it is subject to a race c...
Cache-Control - HTTP
he-control: max-age=<seconds> cache-control: s-maxage=<seconds> extension cache-control directives extension cache-control directives are not part of the core http caching standards document. check the compatibility table for their support; user-agents that don't recognize them should ignore them. ...
...a response that will still be fresh for at least the specified number of seconds. stale-while-revalidate=<seconds> indicates the client will accept a stale response, while asynchronously checking in the background for a fresh one. the seconds value indicates how long the client will accept a stale response. see "keeping things fresh with stale-while-revalidate" for more information. stale-if-
error=<seconds> indicates the client will accept a stale response if the check for a fresh one fails. the seconds value indicates how long the client will accept the stale response after the initial expiration. revalidation and reloading must-revalidate indicates that once a resource becomes stale, caches must not use their stale copy without successful validation on the origin server. proxy-...
Want-Digest - HTTP
entifiers for one or more digest algorithms that the sender wishes the responder to use to create the digest. the sender may use quality values to indicate its preference ordering among the choices it offers. if want-digest does not include any digest algorithms that the server supports, the server may respond with: a digest calculated using a different digest algorithm, or a 400 bad request
error, and include another want-digest header with that response, listing the algorithms that it does support. see the page for the digest header for more information. header type general header forbidden header name no syntax want-digest: <digest-algorithm> // multiple algorithms, weighted with the quality value syntax: want-digest: <digest-algorithm><q-value>,<dige...
...56=x48e9qookqqrvdts8nojrjn3owduoywxbf7kbu9dbpe= unsupported digests the server does not support any of the requested digest algorithms, so uses a different algorithm: request: get /item want-digest: sha;q=1 response: http/1.1 200 ok digest: sha-256=x48e9qookqqrvdts8nojrjn3owduoywxbf7kbu9dbpe= the server does not support any of the requested digest algorithms, so responds with a 400
error and includes another want-digest header, listing the algorithms that it does support: request: get /item want-digest: sha;q=1 response: http/1.1 400 bad request want-digest: sha-256, sha-512 specifications specification title draft-ietf-httpbis-digest-headers-latest resource digests for http this header was originally defined in rfc 3230, ...
406 Not Acceptable - HTTP
the hypertext transfer protocol (http) 406 not acceptable client
error response code indicates that the server cannot produce a response matching the list of acceptable values defined in the request's proactive content negotiation headers, and that the server is unwilling to supply a default representation. proactive content negotiation headers include: accept accept-charset accept-encoding accept-language in practice, this
error is very rarely used. instead of responding using this
error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. ...
...tion headers include: accept accept-charset accept-encoding accept-language in practice, this
error is very rarely used. instead of responding using this
error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. it is assumed that even if the user won't be completely happy, they will prefer this to an
error code. if a server returns such an
error status, the body of the message should contain the list of the available representations of the resources, allowing the user to choose among them. status 406 not acceptable specifications specification title rfc 7231, section 6.5.6: 406 not acceptable hypertext transfer protocol (http/1.1): semantics and content ...
501 Not Implemented - HTTP
the hypertext transfer protocol (http) 501 not implemented server
error response code means that the server does not support the functionality required to fulfill the request. this status can also send a retry-after header, telling the requester when to check back to see if the functionality is supported by then. 501 is the appropriate response when the server does not recognize the request method and is incapable of supporting it for any resource. the only methods that servers are required to support (and therefore that must not return 501) are get and head. if the server does recognize the method, but intentionally does not support it, the appropriate response is 405 method not allowed. ...
...hen. 501 is the appropriate response when the server does not recognize the request method and is incapable of supporting it for any resource. the only methods that servers are required to support (and therefore that must not return 501) are get and head. if the server does recognize the method, but intentionally does not support it, the appropriate response is 405 method not allowed. a 501
error is not something you can fix, but requires a fix by the web server you are trying to access. a 501 response is cacheable by default; that is, unless caching headers instruct otherwise. status 501 not implemented specifications specification title rfc 7231, section 6.6.2: 501 not implemented hypertext transfer protocol (http/1.1): semantics and content ...
Indexed collections - JavaScript
reted as an arraylength, not as a single element. let arr = [42] // creates an array with only one element: // the number 42. let arr = array(42) // creates an array with no elements // and arr.length set to 42. // // this is equivalent to: let arr = [] arr.length = 42 calling array(n) results in a range
error, if n is a non-whole number whose fractional portion is non-zero. the following example illustrates this behavior. let arr = array(9.3) // range
error: invalid array length if your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. alternatively, create an empty array first before adding the single element to it. in es2015, you can ...
...() or the arguments object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. the arguments object provides a length attribute but does not implement the foreach() method, for example. array methods cannot be called directly on array-like objects. function printarguments() { arguments.foreach(function(item) { // type
error: arguments.foreach is not a function console.log(item); }); } but you can call them indirectly using function.prototype.call(). function printarguments() { array.prototype.foreach.call(arguments, function(item) { console.log(item); }); } array prototype methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays: ...
Numbers and dates - JavaScript
mode (511 in decimal) note that decimal literals can start with a zero (0) followed by another decimal digit, but if every digit after the leading 0 is smaller than 8, the number gets parsed as an octal number. binary numbers binary number syntax uses a leading zero followed by a lowercase or uppercase latin letter "b" (0b or 0b). if the digits after the 0b are not 0 or 1, the following syntax
error is thrown: "missing binary digits after 0b". var flt_signbit = 0b10000000000000000000000000000000; // 2147483648 var flt_exponent = 0b01111111100000000000000000000000; // 2139095040 var flt_mantissa = 0b00000000011111111111111111111111; // 8388607 octal numbers octal number syntax uses a leading zero. if the digits after the 0 are outside the range 0 through 7, the number will be interpreted ...
...ng the octal number with a zero: 0644 === 420 and "\045" === "%". in ecmascript 2015, octal numbers are supported if they are prefixed with 0o, e.g.: var a = 0o10; // es2015: 8 hexadecimal numbers hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase latin letter "x" (0x or 0x). if the digits after 0x are outside the range (0123456789abcdef), the following syntax
error is thrown: "identifier starts immediately after numeric literal". 0xfffffffffffffffff // 295147905179352830000 0x123456789abcdef // 81985529216486900 0xa // 10 exponentiation 1e3 // 1000 2e6 // 2000000 0.1e2 // 10 number object the built-in number object has properties for numerical constants, such as maximum value, not-a-number, and infinity. you cannot change the val...
Default parameters - JavaScript
e defined for one or more parameter, then a second scope (environment record) is created, specifically for the identifiers within the parameter list. this scope is a parent of the scope created for the function body. this means that functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time reference
error. ...
...and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time reference
error. it also means that variables declared inside the function body using var will mask parameters of the same name, instead of the usual behavior of duplicate var declarations having no effect. the following function will throw a reference
error when invoked, because the default parameter value does not have access to the child scope of the function body: function f(a = go()) { // throws a `reference
error` when `f` is invoked. function go() { return ':p' } } ...and this function will print undefined because variable var a is hoisted only to the top of the scope created for the function body (and not the parent scope created for the ...
Rest parameters - JavaScript
however, the thir...
... function sortarguments() { let args = array.from(arguments) let sortedargs = args.sort() return sortedargs } console.log(sortarguments(5, 3, 7, 1)) // 1, 3, 5, 7 specifications specification ecmascript (ecma-262)the definition of 'function...
Array.prototype.every() - JavaScript
polyfill every was added to the ecma-262 standard in the 5th edition, and it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and type
error have their original values, and that callbackfn.call evaluates to the original value of function.prototype.call. if (!array.prototype.every) { array.prototype.every = function(callbackfn, thisarg) { 'use strict'; var t, k; if (this == null) { throw new type
error('this is null or not defined'); } // 1. let o be the result of calling toobject passing the this // ...
...ll or 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 type
error exception. if (typeof callbackfn !== 'function' && object.prototype.tostring.call(callbackfn) !== '[object function]') { throw new type
error(); } // 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 kva...
Array.prototype.lastIndexOf() - JavaScript
stindexof was added to the ecma-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of lastindexof in implementations which do not natively support it. ...
...tion, assuming object, type
error, number, math.floor, math.abs, and math.min have their original values. ...
Array - JavaScript
// logs 'this is the first element' console.log(arr[1]) // logs 'this is the second element' console.log(arr[arr.length - 1]) // logs 'this is the last element' array elements are object properties in the same way that tostring is a property (to be specific, however, tostring() is a method). nevertheless, trying to access an element of an array as follows throws a syntax
error because the property name is not valid: console.log(arr.0) // a syntax
error there is nothing special about javascript arrays and the properties that cause this. javascript properties that begin with a digit cannot be referenced with dot notation and must be accessed using bracket notation. for example, if you had an object with a property named 3d, it can only be referenced using bracket not...
...special about javascript arrays and the properties that cause this. javascript properties that begin with a digit cannot be referenced with dot notation and must be accessed using bracket notation. for example, if you had an object with a property named 3d, it can only be referenced using bracket notation. let years = [1950, 1960, 1970, 1980, 1990, 2000, 2010] console.log(years.0) // a syntax
error console.log(years[0]) // works properly renderer.3d.settexture(model, 'character.png') // a syntax
error renderer['3d'].settexture(model, 'character.png') // works properly in the 3d example, '3d' had to be quoted (because it begins with a digit). but it's also possible to quote the array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. the 2 in year...
BigInt - JavaScript
-1 : ((a > b) ? 1 : 0)) // ↪ [ -12n, 0, 0n, 4n, 4, 6, 10 ] note that comparisons with object-wrapped bigints act as with other objects, only indicating equality when the same object instance is compared: 0n === object(0n) // false object(0n) === object(0n) // false const...
...g between number and bigint can lead to loss of precision, it is recommended to only use bigint when values greater than 253 are reasonably expected and not to coerce between the two types. cryptography the operations supported on bigints are not constant time. bigint is therefore unsuitable for use in cryptography. use within json using json.stringify() with any bigint value will raise a type
error as bigint values aren't serialized in json by default. however, you can implement your own tojson method if needed: bigint.prototype.tojson = function() { return this.tostring() } instead of throwing, json.stringify now produces a string like this: json.stringify(bigint(1)) // '"1"' examples calculating primes // returns true if passed bigint is a prime number function isprime(p) { for (...
FinalizationRegistry.prototype.unregister() - JavaScript
r in your cleanup callback. only call unregister if you haven't received a cleanup callback and no longer need to receive one. examples using unregister this example shows registering a target object using that same object as the unregister token, then later unregistering it via unregister: class thingy { #cleanup = label => { // ^^^^^−−−−− held value console.
error( `the \`release\` method was never called for the object with the label "${label}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance. be sure to call `release` when you're done with it. * * @param label a label for the `thingy`. */ constructor(label) { // ...
... unregister token } /** * releases resources held by this `thingy` instance. */ release() { this.#registry.unregister(this); // ^^^^−−−−− unregister token } } this example shows registering a target object using a different object as its unregister token: { // ^^^^−−−−− held value console.
error( `the \`release\` method was never called for the \`thingy\` for the file "${file.name}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance for the given file. be sure to call `release` when you're done with it. * * @param filename the name of the file. */ constructor(filename) { th...
Function.prototype.toString() - JavaScript
object; 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. ...
...o 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 type
error exception ("function.prototype.tostring called on incompatible object"), if its this value object is not a function object. ...
Object.getOwnPropertyDescriptor() - JavaScript
table: true // } o = {}; object.defineproperty(o, 'qux', { value: 8675309, writable: false, enumerable: false }); d = object.getownpropertydescriptor(o, 'qux'); // d is { // value: 8675309, // writable: false, // enumerable: false, // configurable: false // } non-object coercion in es5, if the first argument to this method is not an object (a primitive), then it will cause a type
error. ...
...wnpropertydescriptor(o, 'qux'); // d is { // value: 8675309, // writable: false, // enumerable: false, // configurable: false // } non-object coercion in es5, if the first argument to this method is not an object (a primitive), then it will cause a type
error. in es2015, a non-object first argument will be coerced to an object at first. object.getownpropertydescriptor('foo', 0); // type
error: "foo" is not an object // es5 code object.getownpropertydescriptor('foo', 0); // object returned by es2015 code: { // configurable: false, // enumerable: true, // value: "f", // writable: false // } specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertydescriptor' in that specification. ...
Object.getPrototypeOf() - JavaScript
ull request. syntax object.getprototypeof(obj) parameters obj the object whose prototype is to be returned. return value the prototype of the given object. if there are no inherited properties, null is returned. ...
... 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 type
error exception if the obj parameter isn't an object. in es2015, the parameter will be coerced to an object. object.getprototypeof('foo'); // type
error: "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.isSealed() - JavaScript
...
...r s3 = object.seal({ get p() { return 0; } }); object.isfrozen(s3); // === true // (only configurability matters for accessor properties) non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. in es2015, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. object.issealed(1); // type
error: 1 is not an object (es5 code) object.issealed(1); // true (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.issealed' in that specification. ...
Object.keys() - JavaScript
g'), dontenums = [ 'tostring', 'tolocalestring', 'valueof', 'hasownproperty', 'isprototypeof', 'propertyisenumerable', 'constructor' ], dontenumslength = dontenums.length; return function(obj) { if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) { throw new type
error('object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasownproperty.call(obj, prop)) { result.push(prop); } } if (hasdontenumbug) { for (i = 0; i < dontenumslength; i++) { if (hasownproperty.call(obj, dontenums[i])) { result.push(dontenums[i]); } } }...
...which isn't enumerable const myobj = object.create({}, { getfoo: { value: function () { return this.foo; } } }); myobj.foo = 1; console.log(object.keys(myobj)); // console: ['foo'] if you want all properties—including non-enumerables—see object.getownpropertynames(). non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. from es2015 onwards, a non-object argument will be coerced to an object. // in es5 object.keys('foo'); // type
error: "foo" is not an object // in es2015+ object.keys('foo'); // ["0", "1", "2"] specifications specification ecmascript (ecma-262)the definition of 'object.keys' in that specification. ...
Promise.resolve() - JavaScript
e.resolve(33); var cast = promise.resolve(original); cast.then(function(value) { console.log('value: ' + value); }); console.log('original === cast ? ' + (original === cast)); // logs, in order: // original === cast ? true // value: 33 the inverted order of the logs is due to the fact that the then handlers are called asynchronously. see how then works here. ...
... thenable object var p1 = promise.resolve({ then: function(onfulfill, onreject) { onfulfill('fulfilled!'); } }); console.log(p1 instanceof promise) // true, object casted to a promise p1.then(function(v) { console.log(v); // "fulfilled!" }, function(e) { // not called }); // thenable throws before callback // promise rejects var thenable = { then: function(resolve) { throw new type
error('throwing'); resolve('resolving'); }}; var p2 = promise.resolve(thenable); p2.then(function(v) { // not called }, function(e) { console.
error(e); // type
error: throwing }); // thenable throws after callback // promise resolves var thenable = { then: function(resolve) { resolve('resolving'); throw new type
error('throwing'); }}; var p3 = promise.resolve(thenable); p3.then(function(v) {...
handler.defineProperty() - JavaScript
defineproperty() method must return a boolean indicating whether or not the property has been successfully defined. description the handler.defineproperty() method is a trap for object.defineproperty(). interceptions this trap can intercept these operations: object.defineproperty() reflect.defineproperty() invariants if the following invariants are violated, the proxy will throw a type
error: a property cannot be added, if the target object is not 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.
...ts 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 type
error 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: 10 }; object.defineproperty(p, 'a', desc); // "called: a" when calling object.defineproperty...
handler.get() - JavaScript
the proxy. return value the get() method can return any value. description the handler.get() method is a trap for getting a property value. interceptions this trap can intercept these operations: property access: proxy[foo]and proxy.bar inherited property access: object.create(proxy)[foo] reflect.get() invariants if the following invariants are violated, the proxy will throw a type
error: the value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. the value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has undefined as its [[get]] attribute. examples trap...
... ...
handler.getOwnPropertyDescriptor() - JavaScript
e the getownpropertydescriptor() method must return an object or undefined. description the handler.getownpropertydescriptor() method is a trap for object.getownpropertydescriptor(). interceptions this trap can intercept these operations: object.getownpropertydescriptor() reflect.getownpropertydescriptor() invariants if the following invariants are violated, the proxy will throw a type
error: getownpropertydescriptor() must return an object or undefined. a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. a property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. a property cannot be reported as existent, if it does not exists as an ...
... ...
handler.has() - JavaScript
lue the has() method must return a boolean value. description the handler.has() method is a trap for the in operator. interceptions this trap can intercept these operations: property query: foo in proxy inherited property query: foo in object.create(proxy) with check: with(proxy) { (foo); } reflect.has() invariants if the following invariants are violated, the proxy will throw a type
error: a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. a property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. examples trapping the in operator the following code traps the in operator. const p = new proxy({}, { has: function(target, prop)...
...rator. const p = new proxy({}, { has: function(target, prop) { console.log('called: ' + prop); return true; } }); console.log('a' in p); // "called: a" // true the following code violates an invariant. const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { has: function(target, prop) { return false; } }); 'a' in p; // type
error is thrown specifications specification ecmascript (ecma-262)the definition of '[[hasproperty]]' in that specification. ...
handler.isExtensible() - JavaScript
s bound to the handler. target the target object. return value the isextensible() method must return a boolean value. description the handler.isextensible() method is a trap for object.isextensible(). interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the following invariants are violated, the proxy will throw a type
error: object.isextensible(proxy) must return the same value as object.isextensible(target). examples trapping of isextensible the following code traps object.isextensible(). const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the followin...
...ps object.isextensible(). const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant. const p = new proxy({}, { isextensible: function(target) { return false; } }); object.isextensible(p); // type
error is thrown specifications specification ecmascript (ecma-262)the definition of '[[isextensible]]' in that specification. ...
handler.ownKeys() - JavaScript
arget object. return value the ownkeys() method must return an enumerable object. description the handler.ownkeys() method is a trap for reflect.ownkeys(). interceptions this trap can intercept these operations: object.getownpropertynames() object.getownpropertysymbols() object.keys() reflect.ownkeys() invariants if the following invariants are violated, the proxy will throw a type
error: the result of ownkeys() must be an array. the type of each array element is either a string or a symbol. the result list must contain the keys of all non-configurable own properties of the target object. if the target object is not extensible, then the result list must contain all the keys of the own properties of the target object and no other values. examples trapping of getownpropert...
... // [ 'a', 'b', 'c' ] the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: true, value: 10 } ); const p = new proxy(obj, { ownkeys: function(target) { return [123, 12.5, true, false, undefined, null, {}, []]; } }); console.log(object.getownpropertynames(p)); // type
error: proxy [[ownpropertykeys]] must return an array // with only string and symbol elements specifications specification ecmascript (ecma-262)the definition of '[[ownpropertykeys]]' in that specification. ...
handler.preventExtensions() - JavaScript
target the target object. return value the preventextensions() method must return a boolean value. description the handler.preventextensions() method is a trap for object.preventextensions(). interceptions this trap can intercept these operations: object.preventextensions() reflect.preventextensions() invariants if the following invariants are violated, the proxy will throw a type
error: object.preventextensions(proxy) only returns true if object.isextensible(proxy) is false. examples trapping of preventextensions the following code traps object.preventextensions(). const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); return true; } }); console.log(object.preventextensions(p)); // "calle...
... ...
Proxy.revocable() - JavaScript
ted revocable proxy object is returned. description a revocable proxy is an object with following two properties {proxy: proxy, revoke: revoke}. proxy a proxy object created with new proxy(target, handler) call. revoke a function with no argument to invalidate (switch off) the proxy. if the revoke() function gets called, the proxy becomes unusable: any trap to a handler will throw a type
error. ...
...ll throw a type
error. once a proxy is revoked, it will remain revoked and can be garbage collected. calling revoke() again has no effect. examples using proxy.revocable var revocable = proxy.revocable({}, { get: function(target, name) { return "[[" + name + "]]"; } }); var proxy = revocable.proxy; console.log(proxy.foo); // "[[foo]]" revocable.revoke(); console.log(proxy.foo); // type
error is thrown proxy.foo = 1 // type
error again delete proxy.foo; // still type
error typeof proxy // "object", typeof doesn't trigger any trap specifications specification ecmascript (ecma-262)the definition of 'proxy revocation functions' in that specification. ...
Reflect.defineProperty() - JavaScript
ll 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 type
error, 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 type
error if the property has not been successfully defined. reflect.defineproperty, however, simply returns a...
... however, simply returns a boolean indicating whether or not the property was successfully defined. examples using reflect.defineproperty() let obj = {} reflect.defineproperty(obj, 'x', {value: 7}) // true obj.x // 7 checking if property definition has been successful with object.defineproperty, which returns an object if successful, or throws a type
error otherwise, you would use a try...catch block to catch any
error that occurred while defining a property. ] because reflect.defineproperty returns a boolean success status, you can just use an if...else block here: if (reflect.defineproperty(target, property, attributes)) { // success } else { // failure } specifications specification ecmascript (ecma-262)the definition o...
Reflect.getPrototypeOf() - JavaScript
epository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax 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 type
error, 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)) // null compar...
...ototypeof({}) // object.prototype reflect.getprototypeof(object.prototype) // null reflect.getprototypeof(object.create(null)) // null compared to object.getprototypeof() // same result for objects object.getprototypeof({}) // object.prototype reflect.getprototypeof({}) // object.prototype // both throw in es5 for non-objects object.getprototypeof('foo') // throws type
error reflect.getprototypeof('foo') // throws type
error // in es2015 only reflect throws, object coerces non-objects object.getprototypeof('foo') // string.prototype reflect.getprototypeof('foo') // throws type
error // to mimic the object es2015 behavior you need to coerce reflect.getprototypeof(object('foo')) // string.prototype specifications specification ecmascript (ecma...
Reflect.isExtensible() - JavaScript
le 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 type
error, if target is not an object. description the reflect.isextensible method allows you determine if an object is extensible (whether it can have new properties added to it). it is the same method as object.isextensible(). examples using reflect.isextensible() see also object.isextensible(). // new objects are extensible. let empty = {} reflect.isextensible(empty) // === true // ...but that c...
...== false // sealed objects are by definition non-extensible. let sealed = object.seal({}) reflect.isextensible(sealed) // === false // frozen objects are also by definition non-extensible. let frozen = object.freeze({}) reflect.isextensible(frozen) // === false difference to object.isextensible() if the target argument to this method is not an object (a primitive), then it will cause a type
error. with object.isextensible(), a non-object first argument will be coerced to an object at first. reflect.isextensible(1) // type
error: 1 is not an object object.isextensible(1) // false specifications specification ecmascript (ecma-262)the definition of 'reflect.isextensible' in that specification. ...
Reflect.preventExtensions() - JavaScript
itory. 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 type
error, 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.isext...
...reventextensions() see also object.preventextensions(). // objects are extensible by default. let empty = {} reflect.isextensible(empty) // === true // ...but that can be changed. reflect.preventextensions(empty) reflect.isextensible(empty) // === false difference from object.preventextensions() if the target argument to this method is not an object (a primitive), then it will cause a type
error. with object.preventextensions(), a non-object target will be coerced to an object. reflect.preventextensions(1) // type
error: 1 is not an object object.preventextensions(1) // 1 specifications specification ecmascript (ecma-262)the definition of 'reflect.preventextensions' in that specification. ...
String.prototype.codePointAt() - JavaScript
number(position) : 0; if (index != index) { // better `isnan` index = 0; } // account for out-of-bounds indices: ...
...ty = (function() { // ie 8 only supports `object.defineproperty` on dom elements try { var object = {}; var $defineproperty = object.defineproperty; var result = $defineproperty(object, object, object) && $defineproperty; } catch(
error) {} return result; }()); var codepointat = function(position) { if (this == null) { throw type
error(); } var string = string(this); var size = string.length; // `tointeger` var index = position ? number(position) : 0; if (index != index) { // better `isnan` index = 0; } // account for out-of-bounds indices: if (index < 0 || index >= size) { return undefined; } // get the first code unit var first = string.ch...
String.prototype.matchAll() - 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 str.matchall(regexp) parameters regexp a regular expression object. if a non-regexp object obj is passed, it is implicitly converted to a regexp by using new regexp(obj). the regexp object must have the /g flag, otherwise a type
error will be thrown. return value an iterator (which is not a restartable iterable). examples regexp.exec() and matchall() prior to the addition of matchall to javascript, it was possible to use calls to regexp.exec (and regexes with the /g flag) in a loop to obtain all the matches: const regexp = regexp('foo[a-z]*','g'); const str = 'table football, foosball'; let match; while ((match = reg...
...6 end=14." // expected output: "found foosball start=16 end=24." // matches iterator is exhausted after the for..of iteration // call matchall again to create a new iterator array.from(str.matchall(regexp), m => m[0]); // array [ "football", "foosball" ] matchall will throw an exception if the g flag is missing. const regexp = regexp('[a-c]',''); const str = 'abc'; str.matchall(regexp); // type
error 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]}`); // array [ "1 b", "1 c" ] better access to capturing groups (than string.prototype.match()) another compelling reason f...
String.prototype.replaceAll() - 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 const newstr = str.replaceall(regexp|substr, newsubstr|function) when using a `regexp` you must have to set the global ("g") flag; otherwise, it will throw a type
error: "replaceall must be called with a global regexp". parameters regexp (pattern) a regexp object or literal with the global flag. the matches are replaced with newsubstr or the value returned by the specified function. a regexp without the global ("g") flag will throw a type
error: "replaceall must be called with a global regexp". substr a string that is to be replaced by newsubstr. it is tr...
...le string being examined. (the exact number of arguments depends on whether the first argument is a regexp object—and, if so, how many parenthesized submatches it specifies.) examples using replaceall 'aabbcc'.replaceall('b', '.'); // 'aa..cc' non-global regex throws when using a regular expression search value, it must be global. this won't work: 'aabbcc'.replaceall(/b/, '.'); type
error: replaceall must be called with a global regexp this will work: 'aabbcc'.replaceall(/b/g, '.'); "aa..cc" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.replaceall' in that specification. ...
Symbol.match - JavaScript
xamples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description this function is also used to identify if objects have the behavior of regular expressions. for example, the methods string.prototype.startswith(), string.prototype.endswith() and string.prototype.includes(), check if their first argument is a regular expression and will throw a type
error if they are. now, if the match symbol is set to false (or a falsy value), it indicates that the object is not intended to be used as a regular expression object. property attributes of symbol.match writable no enumerable no configurable no examples disabling the isregexp check the following code wi...
...ow, if the match symbol is set to false (or a falsy value), it indicates that the object is not intended to be used as a regular expression object. property attributes of symbol.match writable no enumerable no configurable no examples disabling the isregexp check the following code will throw a type
error: '/bar/'.startswith(/bar/); // throws type
error, as /bar/ is a regular expression // and symbol.match is not modified. however, if you set symbol.match to false, the isregexp check (that uses the match property) will indicate that the object is not a regular expression object. the methods startswith and endswith won't throw a type
error as a consequence. var re = /foo/; re[symbol.match] = fals...
Symbol - JavaScript
e symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols. note that symbol("foo") does not coerce the string "foo" into a symbol. it creates a new symbol each time: symbol('foo') === symbol('foo') // false the following syntax with the new operator will throw a type
error: let sym = new symbol() // type
error this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number). if you really want to create a symbol wrapper object, you can use the object() function: l...
...urns the primitive value of the symbol object. examples using the typeof operator with symbols the typeof operator can help you to identify symbols. typeof symbol() === 'symbol' typeof symbol('foo') === 'symbol' typeof symbol.iterator === 'symbol' symbol type conversions some things to note when working with type conversion of symbols. when trying to convert a symbol to a number, a type
error will be thrown (e.g. +sym or sym | 0). when using loose equality, object(sym) == sym returns true. symbol("foo") + "bar" throws a type
error (can't convert symbol to string). this prevents you from silently creating a new string property name from a symbol, for example. the "safer" string(sym) conversion works like a call to symbol.prototype.tostring() with symbols, but note that new string(s...
TypedArray - JavaScript
hrough object.getprototypeof(int8array) and similar. all typedarrays constructors inherit common properties from the %typedarray% constructor function. additionally, all typed array prototypes (typedarray.prototype) have %typedarray%.prototype as their [[prototype]]. the %typedarray% constructor on its own is not particularly useful. calling it or using it in a new expression will throw a type
error, except when used during object creation in js engines that support subclassing. there are at present no such engines, so %typedarray% is only useful to polyfill functions or properties onto all typedarray constructors. when creating an instance of a typedarray (e.g. int8array), an array buffer is created internally in memory or, if an arraybuffer object is given as constructor argument, then t...
...ting the array and its elements. see also array.prototype.tostring(). typedarray.prototype[@@iterator]() returns a new array iterator object that contains the values for each index in the array. examples new is required starting with ecmascript 2015, typedarray constructors must be constructed with the new operator. calling a typedarray constructor as a function without new will throw a type
error. var dv = int8array([1, 2, 3]); // type
error: calling a builtin int8array constructor // without new is forbidden var dv = new int8array([1, 2, 3]); property access you can reference elements in the array using standard array index syntax (that is, using bracket notation). however, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, ...
Uint16Array() constructor - JavaScript
d, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). starting with ecmascript 2015, uint16array constructors require to be constructed with a new operator. ...
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). starting with ecmascript 2015, uint16array constructors require to be constructed with a new operator. calling a uint16array constructor as a function without new, will throw a type
error from now on. ...
WebAssembly.instantiateStreaming() - JavaScript
a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate. 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 the compiled module or else a webassembly.link
error 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 t...
...e 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 type
error is thrown. if the operation fails, the promise rejects with a webassembly.compile
error, webassembly.link
error, or webassembly.runtime
error, 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) directly streams a .wasm module from an underlying source then compiles and instantia...
decodeURI() - JavaScript
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 uri
error ("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 decodeuri('https://deve...
...ded 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 decodeuri('https://developer.mozilla.org/ru/docs/javascript_%d1%88%d0%b5%d0%bb%d0%bb%d1%8b'); // "https://developer.mozilla.org/ru/docs/javascript_шеллы" catching
errors try { var a = decodeuri('%e0%a4%a'); } catch(e) { console.
error(e); } // uri
error: malformed uri sequence specifications specification ecmascript (ecma-262)the definition of 'decodeuri' in that specification. ...
undefined - JavaScript
rator) must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. this is because null is not equivalent to undefined. see comparison operators for details. typeof operator and undefined alternatively, typeof can be used: var x; if (typeof x === 'undefined') { // these statements execute } one reason to use typeof is that it does not throw an
error if the variable has not been declared. // x has not been declared before if (typeof x === 'undefined') { // evaluates to true without
errors // these statements execute } if (x === undefined) { // throws a reference
error } however, there is another alternative. javascript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared...
... ...
Standard built-in objects - JavaScript
eval() uneval() isfinite() isnan() parsefloat() parseint() encodeuri() encodeuricomponent() decodeuri() decodeuricomponent() deprecated escape() unescape() fundamental objects these are the fundamental, basic objects upon which all other objects are based. this includes general objects, booleans, functions, and symbols. object function boolean symbol
error objects
error objects are a special type of fundamental object. they include the basic
error type, as well as several specialized
error types.
error aggregate
error eval
error internal
error range
error reference
error syntax
error type
error uri
error numbers and dates these are the base objects representing numbers, dates, and mathematical calculations. number bigint math dat...
... reflection reflect proxy internationalization additions to the ecmascript core for language-sensitive functionalities. intl intl.collator intl.datetimeformat intl.listformat intl.numberformat intl.pluralrules intl.relativetimeformat intl.locale webassembly webassembly webassembly.module webassembly.instance webassembly.memory webassembly.table webassembly.compile
error webassembly.link
error webassembly.runtime
error other arguments ...
Spread syntax (...) - JavaScript
nate an array to the end of an existing array. without spread syntax, this is done as: const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; // append all items from arr2 onto arr1 arr1 = arr1.concat(arr2); with spread syntax this becomes: let arr1 = [0, 1, 2]; let arr2 = [3, 4, 5]; arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5] // note: not to use const otherwise, it will give type
error (invalid assignment) array.prototype.unshift() is often used to insert an array of values at the start of an existing array. without spread syntax, this is done as: const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; // prepend all items from arr2 onto arr1 array.prototype.unshift.apply(arr1, arr2) // arr1 is now [3, 4, 5, 0, 1, 2] with spread syntax, this becomes: let arr1 = [0, 1, 2]; let ...
...me iterable when used in an array, or with iterating functions such as map(), reduce(), and assign(). when merging 2 objects together with the spread operator, it is assumed another iterating function is used when the merging occurs. spread syntax (other than in the case of spread properties) can be applied only to iterable objects: const obj = {'key1': 'value1'}; const array = [...obj]; // type
error: obj is not iterable spread with many values when using spread syntax for function calls, be aware of the possibility of exceeding the javascript engine's argument length limit. see apply() for more details. specifications specification ecmascript (ecma-262)the definition of 'array initializer' in that specification. ecmascript (ecma-262)the definition of 'obje...
Unary plus (+) - JavaScript
f converting something into a number, because it does not perform any other operations on the number. it can convert string representations of integers and floats, as well as the non-string values true, false, and null. integers in both decimal and hexadecimal (0x-prefixed) formats are supported. negative numbers are supported (though not for hex). using the operator on bigint values throws a type
error. ...
...ted. negative numbers are supported (though not for hex). using the operator on bigint values throws a type
error. if it cannot parse a particular value, it will evaluate to nan. examples usage with numbers const x = 1; const y = -1; console.log(+x); // 1 console.log(+y); // -1 usage with non-numbers +true // 1 +false // 0 +null // 0 +function(val){ return val } // nan +1n // throws type
error: cannot convert bigint value to number specifications specification ecmascript (ecma-262)the definition of 'unary plus operator' in that specification. ...
Function expression - JavaScript
soon as it is defined. see also the chapter about functions for more information. function expression hoisting function expressions in javascript are not hoisted, unlike function declarations. you can't use function expressions before you create them: console.log(nothoisted) // undefined // even though the variable name is hoisted, the definition isn't. so it's undefined. nothoisted(); // type
error: nothoisted is not a function var nothoisted = function() { console.log('bar'); }; named function expression if you want to refer to the current function inside the function body, you need to create a named function expression. this name is then local only to the function body (scope). this also avoids using the non-standard arguments.callee property. let math = { 'factit': function fac...
...t, it will be the function name (explicit name). this also applies to arrow functions (arrows don't have a name so you can only give the variable an implicit name). var foo = function() {} foo.name // "foo" var foo2 = foo foo2.name // "foo" var bar = function baz() {} bar.name // "baz" console.log(foo === foo2); // true console.log(typeof baz); // undefined console.log(bar === baz); // false (
errors because baz == undefined) examples creating an unnamed function the following example defines an unnamed function and assigns it to x. the function returns the square of its argument: var x = function(y) { return y * y; }; using a function as a callback more commonly it is used as a callback: button.addeventlistener('click', function(event) { console.log('button is clicked!') }) ...
function* - JavaScript
ion execution, replacing the yield expression where an execution was paused with the argument from next(). a return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true). if a value is returned, it will be set as the value property of the object returned by the generator. much like a return statement, an
error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. when a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value: undefined, done: true}. examples simple example function* idmaker() { var index = 0; while (true) yield index++; } var ge...
...value: undefined, done: true } generator as a computed property class foo { *[symbol.iterator] () { yield 1; yield 2; } } const someobj = { *[symbol.iterator] () { yield 'a'; yield 'b'; } } console.log(array.from(new foo)); // [ 1, 2 ] console.log(array.from(someobj)); // [ 'a', 'b' ] generators are not constructable function* f() {} var obj = new f; // throws "type
error: f is not a constructor generator defined in an expression const foo = function* () { yield 10; yield 20; }; const bar = foo(); console.log(bar.next()); // {value: 10, done: false} generator example function* powers(n){ //endless loop to generate for(let current =n;; current *= n){ yield current; } } for(let power of powers(2)){ //controlling generator ...
label - JavaScript
be used with looping labeled statements. description you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution. note that javascript has no goto statement, you can only use labels with break or continue. in strict mode code, you can't use "let" as a label name. it will throw a syntax
error (let is a reserved identifier). examples using a labeled continue with for loops var i, j; loop1: for (i = 0; i < 3; i++) { //the first for statement is labeled "loop1" loop2: for (j = 0; j < 3; j++) { //the second for statement is labeled "loop2" if (i === 1 && j === 1) { continue loop1; } console.log('i = ' + i + ', j = ' + j); } } // output is: /...
...ole.log('face'); break foo; console.log('this will not be executed'); } console.log('swap'); // this will log: // "face" // "swap" labeled function declarations starting with ecmascript 2015, labeled function declarations are now standardized for non-strict code in the web compatibility annex of the specification. l: function f() {} in strict mode code, however, this will throw a syntax
error: 'use strict'; l: function f() {} // syntax
error: functions cannot be labelled generator functions can neither be labeled in strict code, nor in non-strict code: l: function* f() {} // syntax
error: generator functions cannot be labelled specifications specification ecmascript (ecma-262)the definition of 'labelled statement' in that specification. ...
switch - JavaScript
use let and const statements to declare block-scoped variables. take a look at this example: const action = 'say_hello'; switch (action) { case 'say_hello': let message = 'hello'; console.log(message); break; case 'say_hi': let message = 'hi'; console.log(message); break; default: console.log('empty action received.'); break; } this example will output the
error uncaught syntax
error: identifier 'message' has already been declared which you were not probably expecting. this is because the first let message = 'hello'; conflicts with second let statement let message = 'hi'; even they're within their own separate case clauses case 'say_hello': and case 'say_hi':. ultimately, this is due to both let statements being interpreted as duplicate declarations of t...
... specifications specification ecmascript (ecma-262)the definition of 'switch statement' in that specification. ...
with - JavaScript
in associated with the execution context of the script or function containing that unqualified name. the 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. if an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. otherwise a reference
error is thrown. using with is not recommended, and is forbidden in ecmascript 5 strict mode. the recommended alternative is to assign the object whose properties you want to access to a temporary variable. performance pro & contra pro: the with statement can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. the scope chain change required b...
... object. so given this example: function f(x, o) { with (o) { console.log(x); } } only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. if you forget to define x in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an
error -- just unexpected results. contra: code using with may not be forward compatible, especially when used with something other than a plain object. consider this example: function f(foo, values) { with (foo) { console.log(values); } } if you call f([1,2,3], obj) in an ecmascript 5 environment, then the values reference inside the with statement will resolve to obj. however, ecmascript ...
MathML documentation index - MathML
e wrapped in <math> tags. in addition you must not nest a second <math> element in another, but you can have an arbitrary number of other child elements in it. 12 <menclose> mathml, mathml reference, mathml:element, mathml:general layout schemata the mathml <menclose> element renders its content inside an enclosing notation specified by the notation attribute. ...
... have an arbitrary number of other child elements in it. 12 <menclose> mathml, mathml reference, mathml:element, mathml:general layout schemata the mathml <menclose> element renders its content inside an enclosing notation specified by the notation attribute. 13 <m
error> mathml, mathml reference, mathml:element, mathml:general layout schemata the mathml <m
error> element is used to display contents as
error messages. in firefox this
error message is rendered similar to the typical xml
error message. note that this
error is not thrown when your mathml markup is wrong or not well-formed xml. you will still get an xml parsing
error (in case of the xhtml notation of mathml), which has nothing to do with <m
error>. 14 <mfenced> deprecated, mathm...
Handling media support issues in web content - Web media technologies
this places a small, but reasonably easily overcome, burden on the web developer: to properly handle the situation when the user's browser can't handle a particular type of media. this guide covers techniques you can use to develop web content that meets your media needs while providing the most broadly compatible experience possible. topics we will examine fallbacks, baseline media formats, and
error handling practices that will let your content work in as many situations as possible. using poster frames a poster frame is a still image that's representative of the content of a video. this may be simply the first frame of video; however, in many cases, the first frame is blank, or contains nothing but the logo of a business, or some other image that doesn't give the reader any context for th...
...ed loading—to present it in full quality. ...
Navigation and resource timings - Web Performance
rects is not of the same origin, the value returned is 0. redirectend when the last http redirect is completed, that is when the last byte of the http response has been received. if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. connectend when the connection is opened network. if the transport layer reports an
error and the connection establishment is started again, the last connection establishment end time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. connectstart when the request to open a connection is sent to the networ...
...started again, the last connection establishment end time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. connectstart when the request to open a connection is sent to the network. if the transport layer reports an
error and the connection establishment is started again, the last connection establishment start time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. domainlookupend when the domain lookup is finished. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as perfor...
Progressive web app structure - Progressive web apps (PWAs)
app shell approach allows websites to be: linkable: even though it behaves like a native app, it is still a website — you can click on the links within the page and send a url to someone if you want to share it. progressive: start with the "good, old basic website” and progressively add new features while remembering to detect if they are available in the browser and gracefully handle any
errors that crop up if support is not available. for example, an offline mode with the help of service workers is just an extra trait that makes the website experience better, but it's still perfectly usable without it. responsive: responsive web design also applies to progressive web apps, as both are mainly for mobile devices. there are so many varied devices with browsers — it's important to prep...
...lopers to have direct access to data streaming from the server — if you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all of it to be downloaded and converted to a blob (or whatever) — you can start right away. it provides fine-grained control — the stream can be started, chained with another stream, cancelled, checked for
errors, and more. in theory, streaming is a better model, but it's also more complex, and at the time of writing (march 2018) the streams api is still a work-in-progress and not yet fully available in any of the major browsers. when it is available, it will be the fastest way of serving the content — the benefits are going to be huge in terms of performance. for working examples and more informatio...
Structural overview of progressive web apps - Progressive web apps (PWAs)
app shell approach allows websites to be: linkable: even though it behaves like a native app, it is still a website — you can click on the links within the page and send a url to someone if you want to share it. progressive: start with the "good, old basic website” and progressively add new features while remembering to detect if they are available in the browser and gracefully handle any
errors that crop up if support is not available. for example, an offline mode with the help of service workers is just an extra trait that makes the website experience better, but it's still perfectly usable without it. responsive: responsive web design also applies to progressive web apps, as both are mainly for mobile devices. there are so many varied devices with browsers — it's important to prep...
...elopers to have direct access to data streaming from the server. if you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all of it to be downloaded and converted to a blob (or whatever). instead, you can start right away. it provides fine-grained control: the stream can be started, chained with another stream, canceled, checked for
errors, and more. in theory, streaming is a better model than the app shell model, but it's also more complex, and the streams api isn't yet fully supported by any of the major browsers. once it's available, however, it will be the fastest way to serve your app's content. the performance benefits will be truly spectacular. for working examples and more information, see the streams api documentation. ...
SVG Event Attributes - SVG: Scalable Vector Graphics
ports, svg supports that as an event attribute, following the same requirements as for html event attributes. the global event attributes are available on all svg elements. other event attributes are available on a case by case basis for each elements. all event attribute are not animatable. ...
..., onend, onrepeat document event attributes onabort, on
error, onresize, onscroll, onunload document element event attributes oncopy, oncut, onpaste global event attributes oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncuechange, ondblclick, ondrag, ondragend, ondragenter, ondragexit, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, on
error, onfocus, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onload, onloadeddata, onloadedmetadata, onloadstart, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseout, onmouseover, onmouseup, onmousewheel, onpause, onplay, onplaying, onprogress, onratechange, onreset, onresize, onscroll, onseeked, onseeking, onselect, onshow, onstalled, onsubmit, onsuspend, ontimeupdate, ontoggle, on...
Same-origin policy - Web security
n the first. it has to be set in both so their port numbers are both null. note: when using document.domain to allow a subdomain to access its parent securely, you need to set document.domain to the same value in both the parent domain and the subdomain. this is necessary even if doing so is simply setting the parent domain back to its original value. failure to do this may result in permission
errors. cross-origin network access the same-origin policy controls interactions between two different origins, such as when you use xmlhttprequest or an <img> element. these interactions are typically placed into three categories: cross-origin writes are typically allowed. examples are links, redirects, and form submissions. some http requests require preflight. cross-origin embedding is typica...
...ally allowed. (examples are listed below.) cross-origin reads are typically disallowed, but read access is often leaked by embedding. for example, you can read the dimensions of an embedded image, the actions of an embedded script, or the availability of an embedded resource. here are some examples of resources which may be embedded cross-origin: javascript with <script src="…"></script>.
error details for syntax
errors are only available for same-origin scripts. css applied with <link rel="stylesheet" href="…">. due to the relaxed syntax rules of css, cross-origin css requires a correct content-type header. restrictions vary by browser: internet explorer, firefox, chrome, safari (scroll down to cve-2010-0051) and opera. images displayed by <img>. media played by <video> and <audio...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
value for the parameter. the datatype will always bestring. select an xpath expression for the parameter. the value of the attribute is parsed as an xpath expression. the result of evaluating the expression is used as value for the parameter. if the name attribute is missing or empty the pi is ignored. if the namespace attribute is missing or empty the null namespace is used. it is not an
error to specify a parameter name that does not exist in the stylesheet (or that is a variable in the stylesheet). the pi is simply ignored. if both value and select are present or if neither value nor select are present the pi is ignored. note that value="..." is not strictly equal to select="'...'" since the value can contain both apostrophe and quote characters. examples set the parameter 'color...
...am-namespace the xslt-param-namespace uses two attributes: prefix the prefix that is mapped. namespace the namespace the prefix maps to. an xslt-param-namespace pi affects the expression in the select attribute for all xslt-params following the pi. this applies even if there are other nodes such as comments or other pis between the xslt-param-namespace and xslt-param pis. it is not an
error for multiple pis to use the same prefix, every new pi just changes what namespace the prefix maps to. if prefix is missing, empty, or equals an invalid ncname, the pi is ignored. if namespace is missing, the pi is ignored. if namespace is empty, the prefix mapping is removed. examples set the parameter 'books' to a nodeset containing all <book> elements in the 'http://www.example.org/mynamesp...
Understanding WebAssembly text format - WebAssembly
so, back to the typechecking. since webassembly is typechecked, and the funcref can be potentially any function signature, we have to supply the presumed signature of the callee at the callsite, hence we include the $return_i32 type, to tell the program a function returning an i32 is expected. if the callee doesn’t have a matching signature (say an f32 is returned instead), a webassembly.runtime
error is thrown. so what links the call_indirect to the table we are calling? the answer is that there is only one table allowed right now per module instance, and that is what call_indirect is implicitly calling. in the future, when multiple tables are allowed, we would also need to specify a table identifier of some kind, along the lines of call_indirect $my_spicy_table (type $i32_to_void) the ful...
... note: just like memory, tables can also be created from javascript (see webassembly.table()) as well as imported to/from another wasm module. mutating tables and dynamic linking because javascript has full access to function references, the table object...
Content Scripts - Archive of obsolete content
ou can listen for dom events in a content script just as you can in a normal page script, but there are two important differences: first, if you define an event listener by passing it as a string into setattribute(), then the listener is evaluated in the page's context, so it will not have access to any variables defined in the content script. for example, this content script will fail with the
error "themessage is not defined": var themessage = "hello from content script!"; anelement.setattribute("onclick", "alert(themessage);"); second, if you define an event listener by direct assignment to a global event handler like onclick, then the assignment might be overridden by the page. for example, here's an add-on that tries to add a click handler by assignment to window.onclick: var myscript...
Content Processes - Archive of obsolete content
, to limit access to the object in the other sandbox. the xray wrappers we saw earlier are an example of such a security wrapper. security wrappers are created automatically, by the underlying host application. a full discussion of the different kinds of security wrappers and how they work is out of scope for this document, but the main point is this: security wrappers are very complex, and very
error-prone. they are subject to change, in order to fix some security leak that recently popped up. as a result, code that worked just fine last week suddenly does not work the way you expect. by only passing messages between add-on modules and content scripts, these problems can be avoided, making your add-on both easier to debug and to maintain. ...
SDK API Lifecycle - Archive of obsolete content
our control, it might be shorter than this. during this time, the module will be in the deprecated state. the sdk team will track usage of deprecated modules on addons.mozilla.org and support developers migrating their code. the sdk will continue to provide warnings: api documentation will inform users that the module is deprecated. attempts to use a deprecated module at runtime will log an
error to the
error console. the amo validator will throw
errors when deprecated modules are used, and these add-ons will therefore fail amo review. all warnings should include links to further information about what to use instead of the deprecated module and when the module will be completely removed. removal the target removal date is 18 weeks after deprecation. in preparation for this date the ...
notifications - Archive of obsolete content
ations = require("sdk/notifications"); var myiconurl = "./myicon.png"; notifications.notify({ text: "i have an icon!", iconurl: myiconurl }); this module depends on the underlying system's notification service. if the user's system does not support desktop notifications or if its notifications service is not running: if firefox was started normally, notifications are logged to firefox's
error console if the user launched firefox from the command line, notifications are logged to the terminal. globals functions notify(options) displays a transient notification to the user. parameters options : object optional options: name type title string a string to display as the message's title. text string a string to disp...
page-mod - Archive of obsolete content
ern, attach will be triggered for each document, each time with a distinct worker instance. each worker then represents a channel of communication with the set of content scripts loaded by this particular page-mod into that particular document. arguments worker : the listener function is passed a worker object that can be used to communicate with any content scripts attached to this document.
error this event is emitted when an uncaught runtime
error occurs in one of the page-mod's content scripts. arguments
error : listeners are passed a single argument, the
error object. ...
page-worker - Archive of obsolete content
his event you can receive message events from content scripts associated with this page worker. when a content script posts a message using self.postmessage(), the message is delivered to the add-on code in the page worker's message event. arguments value : listeners are passed a single argument which is the message posted from the content script. the message can be any json-serializable value
error this event is emitted when an uncaught runtime
error occurs in one of the page worker's content scripts. arguments
error : listeners are passed a single argument, the
error object. ...
panel - Archive of obsolete content
listen to this event you can receive message events from content scripts associated with this panel. when a content script posts a message using self.postmessage(), the message is delivered to the add-on code in the panel's message event. arguments value : listeners are passed a single argument which is the message posted from the content script. the message can be any json-serializable value.
error this event is emitted when an uncaught runtime
error occurs in one of the panel's content scripts. arguments
error : listeners are passed a single argument, the
error object. ...
request - Archive of obsolete content
uest completes. once a request object has been created a get request can be executed by calling its get() method, a post request by calling its post() method, and so on. when the server completes 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 rul...
simple-storage - Archive of obsolete content
not write your data to the backing store. accessing storage from the console in the add-on debugger, you can access your add-on's simple-storage programmatically from the console using the following: loader.modules['resource://gre/modules/commonjs/sdk/simple-storage.js'].exports.storage clarification from mozilla needed: writing the above line in add-on debugger console results in "reference
error: loader is not defined". constructing arrays be careful to construct array objects conditionally in your code, or you may zero them each time the construction code runs. for example, this add-on tries to store the urls of pages the user visits: var ss = require("sdk/simple-storage"); ss.storage.pages = []; require("sdk/tabs").on("ready", function(tab) { ss.storage.pages.push(tab.url); }); ...
tabs - Archive of obsolete content
a: "blah" } }); } }); the values are accessible to content scripts via the self.options property: // content-script.js alert(self.options.a); onmessage function a function called when the content worker receives a message from content scripts. listeners are passed a single argument, the message posted from the content script. optional. on
error function a function called when the content worker receives an
error from content scripts. listeners are passed a single argument,
error, which is the
error posted from the content script and an object of type
error. optional returns worker : the worker object can be used to communicate with the content script. see content scripts guide to learn the details. properties id the uni...
widget - Archive of obsolete content
age: function(message) { if (message == "ready") widget.postmessage("me too"); } }); globals constructors widget(options) creates a new widget. the widget is immediately added to the add-on bar. parameters options : object required options: name type label string a string description of the widget used for accessibility, title bars, and
error reporting. id string a string used to identify your widget in order to save its location when the user moves it in the browser. this string has to be unique and must not be changed over time. optional options: name type content string an optional string value containing the displayed content of the widget. it may contain...
core/heritage - Archive of obsolete content
changed at runtime. to do that we need to freeze constructor's prototype chain to make sure functions are frozen: object.freeze(dog.prototype); object.freeze(pet.prototype); note: also, this is not quite enough as object.prototype stays mutable & in fact we do little bit more in sdk to address that, but it's not in the scope of this documentation. doing all of this manually is both tedious and
error prone task. that is why sdk provides utility functions to make it more declarative and less verbose. class module exports class utility function for making constructor functions with a proper prototype chain setup in declarative manner: var { class } = require('sdk/core/heritage'); var dog = class({ initialize: function initialize(name) { this.name = name; }, type: 'dog', bark: fun...
event/core - Archive of obsolete content
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 argument that will be passed to listeners. arguments : object|number|string|boolean more argument...
io/file - Archive of obsolete content
icle about file i/o. note that if you do decide to hardcode windows-style paths, be sure to escape backslashes in strings. for example, to specify the file at c:\users\myk, you need to use the string "c:\\users\\myk", not "c:\users\myk". read more about escaping characters in strings. globals functions basename(path) the path parameter must be an absolute path, relative paths will cause an
error. use the fs/path module for relative path support. returns the last component of the given path. for example, basename("/foo/bar/baz") returns "baz". if the path has no components, the empty string is returned. parameters path : string the path of a file. returns string : the last component of the given path. dirname(path) returns the path of the directory containing the given file. if ...
io/text-streams - Archive of obsolete content
k) 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 the background thread. if the stream is already closed, an exception is thrown immediately. parameters str : string the string to write. callback : callback callback, if given, must be a function. it's called as callback(
error) when the write completes.
error is an
error object or undefined if there was no
error. inside callback, this is the textwriter object. properties closed true if the stream is closed. ...
ui/button/action - Archive of obsolete content
was clicked"); button.removelistener("click", handleclick); } parameters event : string the event to listener is listening for. action buttons only emit one type of event, "click". listener : function the listener to remove. destroy() destroy the button. after calling this function, the button will no longer appear in the ui, and accessing any of its properties or methods will throw an
error. properties id the button's unique id. this is read-only. label the button's label. icon the button's icon or icons, as a url, relative path, or object containing a set of key-value pairs. disabled boolean property indicating whether or not the button is disabled. badge new in firefox 36. value to attach to the button as a badge. may be a number or a string. the badge can contain a...
ui/button/toggle - Archive of obsolete content
ked"); button.removelistener("click", handleclick); } parameters event : string the event to listener is listening for. toggle buttons emit two types of event, "click" and "change". listener : function the listener to remove. destroy() destroy the button. after calling this function, the button will no longer appear in the ui, and accessing any of its properties or methods will throw an
error. properties id the button's unique id. this property is read-only. label the button's label. icon the button's icon or icons, as a url, relative path, or object containing a set of key-value pairs. disabled boolean property indicating whether or not the button is disabled. checked boolean property indicating whether or not the button is checked. it's initialized to false, or the value ...
ui/frame - Archive of obsolete content
nction is an alias for removelistener(). parameters event : string the event the listener is listening for. frame supports the following events: attach, detach, load, ready, and message. listener : function the listener to remove. destroy() destroy the frame. after calling this function, the frame will no longer appear in the ui, and accessing any of its properties or methods will throw an
error. properties url url for the content loaded into the frame. this is read-only. it's only accessible after the attach event has occurred for this frame. events attach this event is emitted whenever a new frame instance is constructed and the browser has started to load its document: for example, when the user opens a new browser window, if that window has a toolbar containing this frame. sinc...
cfx to jpm - Archive of obsolete content
create an xpi with jpm xpi: if the package.json does not include an id field, then the id written into the install.rdf is the value of the name field prepended with "@". if the package.json does include an id field, and it contains "@", then this is written into the install.rdf as the add-on id. if the package.json does include an id field, and it does not contain "@", then jpm xpi raises an
error and the xpi will not be built. what you need to do all this means that: if your package.json contains an id field, and its value does not contain "@", then you must append "@jetpack" to it when switching to jpm. if you do this, the add-on's id will be the same as it was when you were using cfx. entry point the add-on's entry point is the file that's executed when the add-on needs to initial...
Tools - Archive of obsolete content
articles listed here provide a reference for the sdk's tools: cfx enables you to test, run, and package add-ons. cfx is is no longer supported as of firefox 44 and no longer accepted for add-on submission, jpm should now be used instead. cfx to jpm a guide to working with jpm if you're already familiar with cfx. console enables your add-on to log
error, warning or informational messages. jpm jpm is a command-line tool that enables you to test, run, and package add-ons. jpm-mobile the node-based replacement for cfx --force-mobile. enables you to run and test add-ons for firefox mobile (aka fennec). jpmignore use .jpmignore to ignore files from your xpi builds created via jpm. package.json the package.json file contains manifest data for your add-on, providing not onl...
Troubleshooting - Archive of obsolete content
have found an installation, or if you have multiple installations, jpm may have found the wrong one. in those cases you need to use jpm's --binary option. see the jpm guide for more information. when you run jpm to test your add-on or run unit tests, it prints out the location of the firefox or xulrunner binary that it found, so you can check its output to be sure. check your text console when
errors are generated in the sdk's apis and your code, they are logged to the text console. this should be the same console or shell from which you ran the jpm command. search for known issues someone else might have experienced your problem, too. other users often post problems to the project mailing list. you can also browse the list of known issues or search for specific keywords. contact the proj...
Unit Testing - Archive of obsolete content
o the base64.js module. this file: exports three functions, each of which expects to receive a single argument 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. yo...
Using third-party modules (jpm) - Archive of obsolete content
ze, run, test, and package add-ons. the current tool is called jpm, and is based on node.js. it replaces the old cfx tool. you can use jpm from firefox 38 onwards. this article describes how you can use third-party modules with jpm. to follow this tutorial you'll need to have installed jpm and learned the basic jpm commands. to install menuitem you'll need to have git command. if you have
error related to git, check you have latest git command installed. the add-on sdk is extensible by design: you can use the modules that ship inside firefox, but you can also create your own modules and make them available for anyone else to use. before the jpm tool was available, there wasn't any package manager for these community-developed modules, so it wasn't obvious where to find community-devel...
Windows - Archive of obsolete content
browser windows to open a new browser window, you can simply use window.open(). however, window.open() returns a window object for content, not for the browser window itself, so you should get the chrome window first. the simplest way to do that is to use nsiwindowmediator. example window.open(); //this open a pop-up window that could be "blocked" client-side //the following code generate an
error as describe in the following warning box var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var newwindow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a type
error from firefox console. in particular the components.classes is undefined and the components o...
Common Pitfalls - Archive of obsolete content
uri object in almost all cases, when creating a uri object you want to use the newuri method on the nsiioservice interface, like so: javascript: try { var ioserv = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uriobj = ioserv.newuri(uristring, uricharset, baseuri); } catch (e) { // may want to catch ns_
error_malformed_uri for some applications } c++: nsresult rv; nscomptr<nsiioservice> ioserv = do_getservice("@mozilla.org/network/io-service;1"); ns_ensure_success(rv, rv); nscomptr<nsiuri> uriobj; rv = ioserv->newuri(uristring, uricharset, baseuri, getter_addrefs(uriobj)); if (ns_failed(rv)) { // may want to handle ns_
error_malformed_uri for // some applications return rv...
Custom about: URLs - Archive of obsolete content
.newchannelfromuriwithloadinfo(uri, asecurity_or_aloadinfo); } else { channel = services.io.newchannel(aboutpage_uri, null, null); } channel.originaluri = auri; return channel; } } class factory { constructor(component) { this.component = component; this.register(); object.freeze(this); } createinstance(outer, iid) { if (outer) { throw cr.ns_
error_no_aggregation; } return new this.component(); } register() { cm.registerfactory(this.component.classid, this.component.classdescription, this.component.contractid, this); } unregister() { cm.unregisterfactory(this.component.prototype.classid, this); } } instantiation firefox 4+ now in the startup...
Default Preferences - Archive of obsolete content
directory 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 th...
Displaying web content in an extension without security issues - Archive of obsolete content
nkinbrowser(event.target.href); } safe html manipulation functions when it comes to displaying the data, it is tempting to generate some html code and to insert it into the document via innerhtml. and scripts won’t run anyway when inserted via innerhtml, right? well, not quite. it is right that <script>alert('xss')</script> won’t run if inserted via innerhtml. but <img src="does_not_exist" on
error="alert('xss')"> for example will still run javascript code, and there are many more possibilities. so properly sanitizing input is still required when using innerhtml and it is far from trivial. it is much easier to use dom manipulation methods that won’t have unexpected side-effects. for example, your template document might have this code: <style type="text/css"> #entrytemplate { display: n...
Extension Versioning, Update and Compatibility - Archive of obsolete content
he updatelink is not https then the hash must be made using one of the sha family of algorithms. the hashing algorithm used is put at the start of the string and separated from the hash by a :. <em:updatehash>sha256:78fc1d2887eda35b4ad2e3a0b60120ca271ce6e64ad2e3a0b60120ca271ce6e6</em:updatehash> note: the value of updatehash, must start with the string of hashing algorithm, it is a common
error to delete this prefix, when setting new value to updatehash:sha256:78fc1d2887eda35b4ad2e3a0b60120ca271ce6e64ad2e3a0b60120ca271ce6e6 when a hash is specified the downloaded file is compared with the hash and an
error shown if it does not match. there are quite a few tools you may use to generate hashes: various unix flavors include sha1sum, sha256sum and so on. windows users should consider h...
Install Manifests - Archive of obsolete content
compatible by default. targetplatform a string specifying a platform that the add-on supports. it contains either the value of os_target alone or combined with target_xpcom_abi, separated by an underscore (_). you can specify multiple targetplatform properties per manifest. if any value matches the application's build parameters, it will be installed; if not, the user will get an appropriate
error message. examples <em:targetplatform>winnt_x86-msvc</em:targetplatform> <em:targetplatform>linux</em:targetplatform> <em:targetplatform>darwin_ppc-gcc3</em:targetplatform> <em:targetplatform>sunos_sparc-sunc</em:targetplatform> usually, you would use only the os part for themes or for extensions that are not fully cross-platform. for extensions including binary (compiled) components, you sh...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
embedding images in addition to writing direct javascript code in event handlers, xul also allows you to embed scripts using a script element, just like in html; this can be used to read in an external script or to place the code in the script element's content. if you are embedding a script in a page, you should bracket your code inside a cdata section as shown in listing 18; this will avoid
errors caused by mistakenly reading "&" and other characters as the beginnings of entity references. <script type="application/javascript"><![cdata[ var nodes = gbrowser.mtabcontainer.childnodes; for (var i = 0; i < nodes.length; i++) alert(nodes[i].label); ]]></script> listing 18: embedding a script in xul note: although embedding javascript is permitted, it's generally encouraged that you i...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
ello.helloworld.tooltip;" oncommand="xulschoolchrome.browseroverlay.dosomething(event);" /> <!-- more buttons here. --> </toolbarpalette> <!-- more overlay stuff. --> </overlay> one detail that is easy to overlook is the fact that the toolbarpalette element is outside of the window element. if you put the toolbarpalette element inside the window element in your overlay, some weird
errors will begin to happen. always set the label and tooltiptext attributes of a toolbarbutton. in the case of a toolbaritem element (discussed later), use the title attribute instead of label. tooltips are very important for users that want to know what a button does before clicking it. setting the image for a toolbar button is done with css: #xulschoolhello-hello-world-button { list-style-ima...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
function.tosource and eval to "string-patch" the function body. // do not use! var functionbody = gbrowser.addtab.tosource(); var afterbracket = functionbody.indexof("{") + 1; functionbody = functionbody.substring(0, afterbracket) + "myaddon.onaddtab(auri);" + functionbody.substring(afterbracket); eval("gbrowser.addtab = " + functionbody); of course, this not only looks messy, but can be quite
error prone. other extensions might do something similar, trying to hook the same functions, but a little different, ending up with completely broken code. the code is hard to read and by that hard to maintain and review. (the example is a quite simple one. in real life such code is often far more complex) the code might break in the future, as certain assumptions might not longer be true, for exa...
Custom XUL Elements with XBL - Archive of obsolete content
that you can change the binding for pretty much any element in firefox by just adding a css rule! this is very powerful: it allows you to change almost any aspect of the interface of any xul window. in conjuntion with inheritance, it's even easy to do. you can enrich the ui of a firefox window by extending and replacing elements, which is what the console² extension does in order to improve the
error console window. replacing elements should always be a last resort solution, specially if it is done on the main browser window. it's very easy to break the ui of the application or other extensions if you do this the wrong way, so be very careful about it. if you only need to change some specific instances of an element, use very specific css rules. you can use the -moz-binding property with an...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
failure to do so can lead to execution or remote scripts, and in the worst cases to privilege escalation which can leave a user's pc open to remote attack. building dom trees in most cases, dom trees should be built exclusively with dom creation methods. the following methods will all safely create a dom tree without risk of remote execution. ...
Handling Preferences - Archive of obsolete content
ulschoolhello.message.count"); this._prefservice.setintpref("extensions.xulschoolhello.message.count", currentcount + 1); } one important thing to keep in mind is that the "get" methods of the service can throw an exception if the preference is not found. 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(prefname, this, false); this._prefservice.queryinterface(ci.nsiprefbranch); all the qi'ing is necessary because the addobserver method is in a different interface, and other t...
Search Extension Tutorial (Draft) - Archive of obsolete content
rl based on our url. const engine_url = "chrome://example-engine/content/search.xml"; // keep track of whether this is the first run. var firstrun = false; // decide whether to select the search engine. var selectsearch = false; function removeobserver() { try { services.obs.removeobserver(searchobserver, engine_added); } // if we've already removed this observer, ignore the
error. catch (e) {} } // observer called after our engine has been successfully added function searchobserver(engine, topic, data) { if (data != "engine-added") return; engine.queryinterface(ci.nsisearchengine); if (engine.name == engine_details.name) { // remove our observer now that we're done with it. removeobserver(); // if the engine is not hidden...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
age templates and peripheral formatting. but writers, editors, and producers have been inserting stories into vignette for years sans closing paragraph (</p>) tags. unquoted attributes and uppercase html tags? we've got them in spades, and they're embedded in all past stories of the database. fortunately, our chief engineer was able to write some code that scraped through the database looking for
errors like this which would invalidate our markup. we don't make any claims about past archived content, but we've taken many efforts to make sure even stories from a few years ago are as valid as possible. while conversion to xhtml and css definitely shaved off development time that would have normally been spent manipulating the code, it didn't come entirely easy or without cost. our engineer, aaro...
cached - Archive of obsolete content
get (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete
error ...
checking - Archive of obsolete content
get (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete
error ...
downloading - Archive of obsolete content
t eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate progress cached updateready obsolete
error ...
noupdate - Archive of obsolete content
get (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete
error ...
obsolete - Archive of obsolete content
get (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete
error ...
progress - Archive of obsolete content
inning of the operation. this doesn't include headers and other overhead, but only the content itself. read only. total unsigned long (long) the total number of bytes of content that will be transferred during the operation. if the total size is unknown, this value is zero. read only. related events checking noupdate downloading progress cached updateready obsolete
error ...
updateready - Archive of obsolete content
get (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete
error ...
Events - Archive of obsolete content
archived event pages domsubtreemodifiedmozaudioavailablemozbeforeresizemozorientationcachedchargingchangechargingtimechangecheckingdischargingtimechangedownloading
errorlevelchangenoupdateobsoleteprogressupdateready ...
Index of archived content - Archive of obsolete content
download manager improvements in firefox 3 download manager preferences drag and drop drag and drop example drag and drop javascript wrapper drag and drop events editor embedding guide embedding faq 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 reflo...
MMgc - Archive of obsolete content
ust some jpeg image data or an integer variable or some other unrelated data. when the gc encounters a false positive, it has to assume that it might be a pointer since it doesn't have an exact description of whether that memory is a pointer or not. so, the not-really-pointed-to object will be leaked. memory leaks don't sound like an ok thing, right? well, memory leaks that result from programmer
error tend to be bad leaks... leaks that grow over time. with such a leak, you can be pushing hundreds of megabytes of ram real quick. with a conservative gc, the leaks tend to be random, such that they don't grow over time. the occasional random leak from a false positive can be ok. that doesn't mean we shouldn't worry about it at all, but often conservative gc suffices. it is possible that a future v...
cert_override.txt - Archive of obsolete content
43 for https (ssl) hash algorithm oid sha1-256: oid.2.16.840.1.101.3.4.2.1 (most used) sha-384: oid.2.16.840.1.101.3.4.2.2 sha-512: oid.2.16.840.1.101.3.4.2.3 certificate fingerprint using previous hash algorithm one or more characters for override type: m : allow mismatches in the hostname u : allow untrusted certs (whether it's self signed cert or a missing or invalid issuer cert) t : allow
errors in the validity time, for example, for expired or not yet valid certs certificate's serial number and the issuer name as a base64 encoded string ...
No Proxy For configuration - Archive of obsolete content
y - not usable for local domains with numerous hostnames. not usable for large number of filters (ad blocking). mozilla implements this feature with significant limitations, users may find that writing a pac file is more suitable for their needs. testing contributors can test this feature, even without a proxy server, using a "negative proxy server test". proxy connections that fail return an
error "the proxy server you have configured cannot be found", so configure your browser to use a non-existent http proxy (hostname: "imaginary", port "80"). test each destination in an http: url. all proxied urls will return
errors, all non-proxied connections will be attempted normally (direct connection). hostnames filter test destination result basic filtering unit tests...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
tarts with "np" and ends with ".dll" (or "32.dll"? 8.3?) and copy it in mozilla's "plugins" folder start mozilla and open about:plugins to verify the plugin is detected open the file "test.html" and begin testing. make sure the mimetypes of your html embed tags match the mimetype specified in your nprt.rc file and the top of your npp_gate.cpp file version issues if vc++ compiler throws you
error c2664 on 'drawtext' function call, you may replace it by 'drawtexta'. in fact, all win32 api functions dealing with character strings can be added an 'a' to the end to avoid unicode cast
errors. visual c++ 2008 express don't support c99 standard about int32_t, uint32_t. you have to add #include "nptypes.h" in top of plugin.h file. feel free to append here your issues fixes if the above guide he...
Getting Started - Archive of obsolete content
once you have put the files in the zip folder, rename it to myskin.jar triggering the install from the web to install the theme's jar file directly from the web, you need to run some javascript. <a href='javascript:installtrigger.installchrome(installtrigger.skin, "myskin.jar", "my skin theme")'>install my skin</a> if you have jar files on your hard drive and would like to install the...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
once you have put the files in the zip folder, rename it to my_theme.jar triggering the install from the web to install the theme's jar file directly from the web, you need to run some javascript. <a href='javascript:installtrigger.installchrome(installtrigger.skin, "myskin.jar", "my skin theme")'>install my skin</a> if you have jar files on your hard drive and would like to insta...
Dehydra Object Reference - Archive of obsolete content
explicit boolean flag true for constructors declared using the c++ explicit keyword template objects property type description .name string the name of the template, for example "nscomptr". .arguments array an array where arguments are either strings representing c++ constants or type objects. location objects location objects are passed to builtin functions such as warning() and
error() to specify the location of the message. they convert to a string of the form "file:line:column". they have the following properties: property type .file string .line integer .column integer (optional) ...
Dehydra - Archive of obsolete content
-python-plugin/. dehydra was a lightweight, scriptable, general purpose static analysis tool capable of application-specific analyses of c++ code. in the simplest sense, dehydra could be thought of as a semantic grep tool. it presented a wealth of semantic information that can be queried with concise javascripts. it was also useful to find bugs in source code as it allows for much more
error checking than c++ is capable of by itself. dehydra was built as a gcc plugin, thus it is easy to use for projects that already support gcc. dehydra is also useful for generating language bindings and is used to bootstrap treehydra, a heavy-duty static analysis gcc plugin. documentation installing dehydra download, installation and dependency info for dehydra ...
Developing New Mozilla Features - Archive of obsolete content
zilla.org staff know and we will try to facilitate this. it’s possible developers may not pay much attention to you because they believe your proposed feature is not a high priority, or is not wanted at all, or that you haven’t demonstrated that you understand the codebase and mozilla coding practices well enough for them to spend a lot of time with you. in some cases the developers may be in
error and staff will work to make this clear and get you connected. in other cases, mozilla.org staff may agree with the developers that it does not make sense for them to spend much time assisting with your project. this is a painful setting and we hope it doesn’t happen often. but our developers are a precious commodity and their time is probably the most important resource we have. it’s also po...
Editor Embedding Guide - Archive of obsolete content
gsession->makewindoweditable(domwindow, editortype, pr_true). the first parameter is the nsidomwindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. ...
Extension Frequently Asked Questions - Archive of obsolete content
place to get started, try our tutorial, building an extension or mozillazine's getting started tutorial. use the extension wizard to generate a template to start with. be sure to set the development preferences. todo: add content. where can i get more help? please see extensions:other resources and extensions:community. before asking for help, be sure to set the debugging prefs and check the
error console for related messages. also, don't forget to do at least a simple web search before asking. and read this faq! ...
Block and Line Layout Cheat Sheet - Archive of obsolete content
g box. (what is a frame's "bounding box"?) if this flag is set, then <code>moverflowarea</code> will contain the total area of the frame, including the overflow. ns_frame_external_reference ns_frame_replaced_element ns_frame_generated_content ns_frame_has_loaded_images ns_frame_out_of_flow ns_frame_selected_content ns_frame_is_dirty ns_frame_is_unflowable an unflowable frame is an
error condition; for example, due to system limitations. currently, the only way to get an unflowable frame is to have a frame tree that is "too deep". (see nsframe::isframetreetoodeep().) ns_frame_has_dirty_children ns_frame_has_view ns_frame_independent_selection ns_frame_is_special nsblockframe mflags these flags are the private flags that are meaningful to block frames. ns_block_shr...
JSS build instructions for OSX 10.6 - Archive of obsolete content
cvs login cvs co -r nspr_4_8_7_rtm nspr cvs co -r nss_3_12_9_with_ckbi_1_82_rtm nss cvs co -r jss_4_3_2_rtm jss build nss for 32 and 64: cd mozilla/security/nss make nss_build_all cc="gcc -arch i386" ccc="g++ -arch i386" make nss_build_all use_64=1 build jss for 32 and 64: cd ../jss make cc="gcc -arch i386" ccc="g++ -arch i386" make use_64=1 on osx, java.library.path does...
Style System Overview - Archive of obsolete content
a style context can be obtained through nsistylecontext::getstyledata. nsiframe::getstyledata does the same thing for the frame's mstylecontext member, and the global ::getstyledata is a typesafe helper that doesn't require the style struct id. this style struct is always const, and should always be declared as such (evil old-style casts often used with the non-typesafe forms sometimes hide this
error), since the struct may be shared with other elements. the rule tree as we call nsrulewalker::forward on all the rules that are matched, we build or walk along the rule tree. the rule tree is a lexicographic tree of matched rules, where each node in the tree is represented by a nsrulenode. some style data is cached on nsrulenode objects to speed up computation and reduce memory use. the r...
JavaScript Client API - Archive of obsolete content
(don't forget that you'll need to import weave. so the top of your file should include:) const cu = components.utils; // etc... cu.import("resource://services-sync/main.js"); installing your classes into sync you can register your engine in an "weave:service:ready" observer using the weave.engines.register(fooengine) function. however, "weave:servi...
Creating a Help Content Pack - Archive of obsolete content
pack descriptor file as mentioned earlier, the content pack descriptor file is written using rdf. if you don't know rdf, that's okay - for our purposes, you won't need to learn very much. if you understand the basics of html or (preferably) xml, you'll understand the very basics of the syntax - elements, attributes, and element contents. understanding the syntax is important because small syntax
errors can mean that a whole file won't be loaded correctly. however, while it may seem like this is a disadvantage, it's actually an advantage - if you make an
error you'll know immediately, and you should be able to easily figure out what the problem is by directly loading the file in firefox. later, when we get to actually writing content, you'll need to know xhtml, but for now knowledge of the synt...
Basics - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development. read the experiment report for what we learned from it and the blog post announcing the first sdk release for what we're up to next! class 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...
Mozilla Application Framework in Detail - Archive of obsolete content
asy it is to write cross-platform installations that use the mozilla browser: // register chrome registerchrome(package | delayed_chrome, getfolder("chrome","xmlterm.jar"), "content/xmlterm/"); registerchrome(skin | delayed_chrome, getfolder("chrome","xmlterm.jar"), "skin/modern/xmlterm/"); registerchrome(locale | delayed_chrome, getfolder("chrome","xmlterm.jar"), "locale/xmlterm/"); if (getlast
error() == success) performinstall(); else { alert("
error detected: "+getlast
error()); cancelinstall(); } other features a resource description framework (rdf) parser with support for creating rdf graphs programmatically or by parsing files, compositing multiple sources into a single rdf graph, querying and manipulating graphs, and populating xul widgets (trees, menus, etc.) with graph data...
Mozilla Application Framework - Archive of obsolete content
mozilla-based application authors to take advantage of the exploding world of web services. xpinstall our cross-platform installer for trivial packaging and installation of your mozilla framework applications. and much much more... tools venkman a javascript debugger with support for breakpoints, conditional breakpoints, local variable inspection, watch variables, single step, stop on
error, profile data collection, report generation, code reformatting (pretty printing), and more. dom inspector a tool for inspecting and editing the structure and widgets of your user interface while your application is running. xulmaker a gui builder currently under development that lets you drag-and-drop widgets onto a grid to build your user interface. bugzilla the mozilla bug tracki...
HostWindow - Archive of obsolete content
r area, including the splitter are hidden. note: the sidebar is currently not supported. we are considering whether to support a sidebar in future versions of prism and welcome input on this subject. status - area of the statusbar that displays the loading status message and a "percent complete" progress bar, as well as the "gear" menu that provides access to prism commands such as displaying the
error console. to display the status bar, the statusbar option in webapp.ini must be set to true. command menu - a popup menu showing several prism-specific commands. ...
Scripting - Archive of obsolete content
following functions: startup when the app starts, before the user interface is displayed. since the web application has not yet loaded, the window object is still undefined. preload just before the user interface is displayed. returning false causes the application to terminate. load after the main application windows has finished loading. the window object has been initialized and can be used.
error if there is an
error loading the main app page (e.g. the server is not accessible). shutdown just before the application terminates. prism exposes desktop integration features through an property of the window object called platform. the platform property implements the nsiplatformglue interface, whose methods are described in the following section. methods of the window.platform object can be c...
Frequently Asked Questions - Archive of obsolete content
and if the svg file is stored gzipped they must tell the browser that too. mozilla is strict about this, and no, it's not a bug. failing to respect the mime types servers send is incorrect and has been a source of security holes in other browsers. mozilla will not be changing this behaviour. for more information on server configuration for svg see this link. why does mozilla show an "xml parsing
error" message instead of svg? this is an xml debugging message to help xml authors correct
errors in their xml documents. mozilla will show this message when there's an xml well formedness
error in the file it tried to load. (it doesn't mean there's an
error in mozilla.) there are many different xml
errors, but the most common one in svg files is "xml parsing
error: prefix not bound to a namespace". ...
Standalone XPCOM - Archive of obsolete content
mozilla_five_home not set. nsnativecomponentloader: autoregistering begins. nsnativecomponentloader: autoregistering succeeded inital print: initial value set value to: xpcom defies gravity final print : xpcom defies gravity test passed. test failed: what went wrong? the most common case of why the sample would have failed if you didn't run it from the bin directory. here are some
error messsages and possible ways of fixing them. ./nstestsample:
error in loading shared libraries: libxpcom.so: cannot open shared object file: no such file or directory ld_library_path not set. to fix, setenv ld_library_path . (note the dot). link
errors when building xpcom standalone this is usually due to xpcom not being built standalone. make sure you did configure --enable-standalone-modul...
Supporting per-window private browsing - Archive of obsolete content
instead) try { var inprivatebrowsing = components.classes["@mozilla.org/privatebrowsing;1"]. getservice(components.interfaces.nsiprivatebrowsingservice). privatebrowsingenabled; if (!inprivatebrowsing) { ... } } catch(e) { components.utils.report
error(e); return; } } obtaining an nsiloadcontext for privacy-sensitive apis some apis (such as nsitransferable and nsiwebbrowserpersist) take nsiloadcontext arguments that are used to determine whether they should be classed as private or not (for example, whether the uri being persisted by saveuri should be added to the permanent download history). to do this, import re...
Actionscript Acceptance Tests - Archive of obsolete content
that this file applies to. # these values correspond to the value returned by time.tzname tuple. # (see http://docs.python.org/library/time.html for details) # e.g.: eastern standard time/eastern daylight time = ('est','edt') # write timezones as tuples, one to each line. ('est', 'edt') ('cst', 'cdt') ('mst', 'mdt') ('pst', 'pdt') testname.err this file is used when the test throws an uncatchable
error. the first line must contain the expected
error (without the extra debugger information). the exitcode is optional, but must be defined in this file if non-zero. verify
error:
error #1021 exitcode: 1 testname.exitcode file that specifies the expected exitcode. should just be an integer with nothing else. (note that if a .err file is defined, the .exitcode file will be ignored). in this examp...
Running Tamarin acceptance tests - Archive of obsolete content
a usb. running with 2 or more phones uses threads to run tests in parallel and reduces running times dramatically. you must, in any case, at least use --androidthreads or --threads=1 (or will fail due to multiple tests running). $ cd tamarin-redux/test/acceptance $ ./runtests.py --androidthreads note on using an emulator: the emulator does seem to support hardware floating point but gives a bus
error when running avmshell -darm_vfp. it's unreliable, losing its adb connection frequently. an emulator is ok for testing a few abc files but for any consistency a real device is better. ...
Tamarin Build System Documentation - Archive of obsolete content
ercurial builds are displayed in the top 3 sections: compile, smoke, test sandbox builds are displayed in next 3 sections: sandbox compile, sandbox smoke, sandbox test tamarin-central is considered a "sandbox" and will appear under sandbox phase what are the build phases? compile, smoke, test. when all of the slave machines are free they all start the first build phase simultaneously. if an
error or failure occurs on any slave in a phase the build stops. the next phase is started when all slaves have completed the previous phase successfully. the compile phase compiles all of the tamarin source code and builds all of the shell executables, any
errors will stop the phase and a red box will appear on the slave where the
error occurred. the compile phase takes about 20-25 minutes. the sm...
Venkman Internals - Archive of obsolete content
questions why can't breakpoints be set on some source lines some of the time? sometimes the source has small ticks in the margin for every executable line in my javascript. sometimes these ticks are missing on some or all lines of a file. only lines with tick marks seem to break point properly. ...
Using Breakpoints in Venkman - Archive of obsolete content
along with the line number where the function begins whose code is being stopped. using breakpoints to debug when you set a breakpoint, you give venkman (or whatever debugger you're using) the opportunity to display information about the execution environment. one of the most important aspects of debugging a script or software program is the ability to examine variables—function return values,
errors, counters, variable scopes—as they change over the course of the script execution. the onflipx function in figure 1, for example, uses the variable newsign to figure out what image to use for the fish. when you set a breakpoint at line 81, you can start animation on the web page in the browser window and see venkman stop execution as it enters the onflipx function. stopped there, venkman displ...
File.windowsShortcut - Archive of obsolete content
ws shortcut", "test", vi, 0); f = getfolder("windows"); g = getfolder("temporary"); addfile( "miscshortcut", "2.2.2.2", xpisrc, f, xpisrc, true); target = getfolder(f, xpisrc); shortcutpath = getfolder("program"); err = file.windowsshortcut( target, shortcutpath, "misc shortcut", g, "", target, 0); logcomment("file.windowsshortcut returns: " + err); if (0 == getlast
error()) performinstall(); else cancelinstall(); ...
Install.addDirectory - Archive of obsolete content
install.adddirectory the install object's adddirectory method queues an entire directory for installation once performinstall is called. var vi = "10.10.10.10"; var xpisrc = "adddir1"; initinstall("addfilenovers1", "adddir_1", vi, 1); f = getfolder("program"); setpackagefolder(f); err = adddirectory(xpisrc); logcomment("the
error = " + err); if (0 == getlast
error()) performinstall(); else cancelinstall(); ...
Install.addFile - Archive of obsolete content
install.addfile the install object's addfile method is the standard way to queue files for installation. var xpisrc = "file.txt"; initinstall( "adding a file", "testfile", "1.0.1.7", 1); f = getfolder("program"); setpackagefolder(f); addfile(xpisrc); if (0 == getlast
error()) performinstall(); else cancelinstall(); ...
Windows Install - Archive of obsolete content
windows install example this example shows the installation of a xpi in which user profile information is contained. note the disk space verification, the editing of the windows registry, the writing to the installation log, and the
error checking before either performinstall or cancelinstall is called. // this function verifies disk space in kilobytes function verifydiskspace(dirpath, spacerequired) { var spaceavailable; // get the available disk space on the given path spaceavailable = filegetdiskspaceavailable(dirpath); // convert the available disk space into kilobytes spaceavailable = parseint(spaceavailable / 1024); // do the verification if(spaceavailable < spacerequired) { logcomment("insufficient disk space: " + dirpath); logcomment(" required : " + spa...
copy - Archive of obsolete content
summary makes a queued copy of the specified file. method of file object syntax int copy( filespecobject source, filespecobject dest ) parameters the copy method has the following parameters: source a filespecobject object reprsenting the file to be copied. dest a filespecobject object representing the destination directory. returns an integer
error code. for a list of possible values, see return codes. description the destination can be a directory or a filename. if destination does not exist a new file will be created. ...
dirCreate - Archive of obsolete content
for a list of possible values, see return codes. description the input parameter is a filespecobject that you have already created with the install object's getfolder method. ...
dirRename - Archive of obsolete content
dirrename renames a directory in place. method of file object syntax int dirrename( filespecobject directory, string newname ); parameters the dirrename method has the following parameters: directory a filespecobject representing the directory to be renamed. newname the new terminal (or leaf) name of the directory. returns an integer
error code. for a list of possible values, see return codes. ...
execute - Archive of obsolete content
cute ( filespecobject executablefile, [string aparameters] ); parameters the execute method has the following parameters: executablefile a filespecobject representing the local file already on disk to be executed. note that file names are case sensitive. aparameters an optional parameter string that is passed to the executable. (ignored on mac os) returns an integer
error code. for a list of possible values, see return codes. description the specified file is not actually executed until the performinstall method is called. see performinstall for more information about queued commands during the installation process. example f = getfolder("program", "mytexteditor.exe"); err = file.execute(f, "myfile.txt"); // indicates that 'myfile.txt' will be // opened in the e...
macAlias - Archive of obsolete content
object that represents the directory into which the program file will be installed. filename a string representing the name of the file to be installed. aliasdir a filespecobject that represents the directory into which the alias file will be installed (e.g.,"mac desktop"). aliasname a string representing the name of the alias itself. returns an integer
error code. for a list of possible values, see return codes. example see file.macalias in the script examples chapter. ...
move - Archive of obsolete content
move moves a file from one location to another. method of file object syntax int move( filespecobject source, filespecobject dest ); parameters the move method has the following parameters: source a filespecobject representing the source file. dest a filespecobject representing the target directory. returns an integer
error code. for a list of possible values, see return codes. description you must create a filespecobject for the destination directory to pass in for this function. if the destination doesn't already exist a file name for the destination is assumed. example source = getfolder("program", "file.txt"); dest = getfolder("chrome"); err = file.move(source, dest); ...
remove - Archive of obsolete content
summary deletes a specified file. method of file object syntax int remove( filespecobject file ) parameters the remove method has the following parameters: file a filespecobject representing the file to be removed. returns an integer
error code. for a list of possible values, see return codes. ...
rename - Archive of obsolete content
summary renames a specified file in place. method of file object syntax int rename( filespecobject file, string newname ) parameters the rename method has the following parameters: file a filespecobject representing the file to be renamed. newname the new terminal (or leaf) name of the file. returns an integer
error code. for a list of possible values, see return codes. ...
windowsRegisterServer - Archive of obsolete content
summary windowsregisterserver registers installed dlls with the windows registry. method of file object syntax int windowsregisterserver( object localdirspec ) parameters the windowsregisterserver method has the following parameters: localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. returns an integer
error code. for a list of possible values, see return codes. example filecdtool = getfolder("file:///", faod + "cdtool.dll"); err = file.windowsregisterserver(filecdtool); ...
windowsShortcut - Archive of obsolete content
dir for where atarget will is to be run from. aparams parameters that atarget requires. aicon a filespecobject representing the absolute path (including fiilename) to a file that contains icons. can be either .ico, .dll, .exe, or any other binary file that contains icons. aiconid index of the icon from aicon to use for this shortcut. returns an integer
error code. for a list of possible values, see return codes. example see file.windowsshortcut in the script examples chapter. ...
addDirectory - Archive of obsolete content
the directory to the getfolder method. subdir the name of a directory to append to localdirspec, using '/' as the path separator regardless of the platform.if subdir is missing, null, or "", the filenames are appended directly to the folder name specified by localdirspec. flags an optional field; reserved for future use. pass 0 as the default value. returns an integer
error code. for a list of possible values, see return codes. in some situations, adddirectory may return other
errors. description the adddirectory method puts the files in the specified directory in a temporary location. to move the files and all other subcomponents to their final location, call the performinstall method after you've successfully added all subcomponents. also see the note about binar...
confirm - Archive of obsolete content
onflags, string abutton0title, string abutton1title, string abutton2title, string acheckmsg, object acheckstate ); parameters the second, extended confirm() method is supported starting with gecko 1.8. it accepts any number of parameters up to 8. previous gecko versions only support the first, one-parameter method and will throw an
error on occuring the extended form. see the notes at the end of this document for a safe way to implement a fallback. atext the string to be displayed in the confirmation dialog. this string is typically in the form of a prompt for the user (e.g., "are you sure you want to delete the selected file(s)?"). adialogtitle the string to be used as the dialog title. defaults to...
deleteRegisteredFile - Archive of obsolete content
ently support this method.) deletes the specified file and removes its entry from the client version registry. method of install object syntax int deleteregisteredfile (string registryname); parameters the deleteregisteredfile method has the following parameter: registryname the pathname in the client version registry for the file that is to be deleted. returns an integer
error code. for a list of possible values, see return codes. description the deleteregisteredfile method deletes the specified file and removes the file's entry from the client version registry. if the file is currently being used, the name of the file that is to be deleted is saved and netscape 6 attempts to delete it each time it starts up until the file is successfully deleted. this method is used ...
getFolder - Archive of obsolete content
ubdirectory. if the specified subdirectory doesn't exist, it is created. this parameter is available in netscape 6 or later and may be case sensitive (depending on the operating system). localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. returns a filespecobject representing one of netscape's standard directories, or null in case of
error or if subdirectory refers to a file that already exists. description the getfolder method obtains an object representing one of netscape's standard directories, for use with the addfile and getwinprofile methods. the value of foldername must be one of the following (info is based on mozilla 1.7 stable branch, might also work in other versions): "chrome" "comp...
registerChrome - Archive of obsolete content
specobjects like that required by this function are created using the getfolder method on the install object. xpipath xpipath is the path within the xpi in where the contents.rdf file defining the chrome is located. for example, "locale/mylocale/aim," points to the locale/mylocale/aim subdirectory of the same xpi file in which the installation script is located. returns an integer
error code. for a list of possible values, see return codes. in some situations the method may return other
errors. in a few cases you may get a registry
error. description when the third parameter is omitted (pointing to a specific location within the xpi file), this function is being used in a somewhat deprecated way. in this case, registerchrome is supporting the old format of installation archives...
Install Object - Archive of obsolete content
ll initinstall with the name of the installation and the necessary registry and version information. add the files to the installation add files to the installation by calling getfolder to get file objects and passing those object refs to addfile as many times as necessary. perform installation check that the files have been added successfully (e.g., by checking the
error return codes from many of the main installation methods, and go ahead with the install if everything is in order: performorcancel(); function performorcancel() { if (0 == getlast
error()) performinstall(); else cancelinstall(); } for complete script examples, see script examples. ...
getValue - Archive of obsolete content
the getvalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want. returns a winregvalue object representing the value of the named value-name/value pair or null if there is no value or if there is an
error. see winregvalue for information about these values. description the getvalue method retrieves the value of an arbitraty key. use this method if the value you want is not a string. if the value is a string, the getvaluestring method is more convenient. ...
getValueString - Archive of obsolete content
y, string valname); parameters the getvaluestring method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want. returns a string representing the value of the named value-name/value pair or null if there's an
error, the value is not found, or the value is not a string. description the getvaluestring method gets the value of a string. if the value is not a string, use the getvalue method instead. ...
Installer Script - Archive of obsolete content
ayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/navigator/"); 58. registerchrome(skin | delayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/aim/"); 59. if (err==success) 60. { 61. err = performinstall(); 62. logcomment("performinstall() returned: " + err); 63. } 64. else 65. { 66. cancelinstall(err); 67. logcomment("cancelinstall() due to
error: " + err); 68. } 69. } 70. else 71. cancelinstall(insufficient_disk_space); ...
Attribute (XUL) - Archive of obsolete content
minresultsforpopup minwidth mode modifiers mousethrough movetoclick multiline multiple name negate newlines next noautofocus noautohide noinitialfocus nomatch norestorefocus object observes onbeforeaccept onbookmarkgroup onchange onclick onclosetab oncommand oncommandupdate ondialogaccept ondialogcancel ondialogclosure ondialogextra1 ondialogextra2 ondialoghelp on
error on
errorcommand onextra1 onextra2 oninput onload onnewtab onpageadvanced onpagehide onpagerewound onpageshow onpaneload onpopuphidden onpopuphiding onpopupshowing onpopupshown onsearchcomplete onselect ontextcommand ontextentered ontextrevert ontextreverted onunload onwizardback onwizardcancel onwizardfinish onwizardnext open ordinal orient pack pageid pageincrement...
Working With Directories - Archive of obsolete content
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. a reference to a directory may be created in the same way as with a file by using nsiscriptableio.getfile(). you can access a subdirectory by supplying a directory name as the second argument, or refer to one of the special directories by supplying a null string for the second argument. the first line below with retrieve the directory corresponding to the user's home directory, while the s...
Uploading and Downloading Files - Archive of obsolete content
not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related
error codes. the io object and stream objects can be used to upload files to servers in various ways. the exact method depends on the type of upload that you wish to perform. http file upload some web sites allow one to upload a file. this is done by using an html <input> element using the file type from within a form. when the user selects a file, it can be uploaded to a server. this operation can ...
appendNotification - Archive of obsolete content
function to be called when the button is activated. this function is passed three arguments: the <notification> the button is associated with the button description as passed to appendnotification. the element which was the target of the button press event. if the return value from this function is not true, then the notification is closed. the notification is also not closed if an
error is thrown. label - the label to appear on the button popup - the id of a popup for the button. if null, the button is not a button popup (e.g. a menu). the type property must also be set to "menu", or "menu-button". isdefault - if true, this is the default button. there can be only one default button. if no button has this set, the first button in the array is the default. type - a strin...
Notes - Archive of obsolete content
deleting the "(default)" values in the following registry keys will fix this: hkey_classes_root\http\shell\open\ddeexec hkey_classes_root\https\shell\open\ddeexec you can also do this from within your xpcom component using windows registry interface. ...
Providing Command-Line Options - Archive of obsolete content
try { // changeme: change "viewapp" to your command line flag that takes an argument var uristr = cmdline.handleflagwithparam("viewapp", false); if (uristr) { // convert uristr to an nsiuri var uri = cmdline.resolveuri(uristr); openwindow(chrome_uri, uri); cmdline.preventdefault = true; } } catch (e) { components.utils.report
error("incorrect parameter passed to -viewapp on the command line."); } // changeme: change "myapp" to your command line flag (no argument) if (cmdline.handleflag("myapp", false)) { openwindow(chrome_uri, null); cmdline.preventdefault = true; } }, // changeme: change the help info as appropriate, but // follow the guidelines in nsicommandlinehandler.idl // specific...
Style classes - Archive of obsolete content
« xul reference home alert-icon chromeclass-toolbar
error-icon groove header indent listcell-iconic listitem-iconic menuitem-iconic menuitem-non-iconic message-icon monospace plain question-icon small-margin statusbarpanel-iconic statusbarpanel-iconic-text statusbarpanel-menu-iconic text-link thin tree-splitter treecol-image ...
SQLite Templates - Archive of obsolete content
lso that the query statement has a where clause which restricts the rows to those with an age greater or equal to 30. query parameters sometimes, you will want to adjust the query depending on certain criteria. one possibility is to simply use methods to adjust the text within the query element and rebuild the template. however, this can become unweidly for more complex queries, and would be more
error prone if values were not escaped properly to ensure that extraneous quotes, semicolons and other characters didn't appear in the values. this is especially important when you are taking values that were entered by the user. the solution is to use query parameters, using the param element. <query> select name, email from myfriends where gender = :wantedgender <param name="wantedgender">male</...
Complete - Archive of obsolete content
sing a new xpi, you risk annoying users who cannot upgrade until you do. the approach used here is optimistic. the extension is assumed to work in any future version of the application. to adopt this approach, set the maxversion to a large number like 99. the problem with this approach is that when changes in an application do make the extension fail, users might have bad experiences ranging from
error messages that they cannot understand to crashes and data loss. for more information about version checks, see: extension versioning, update and compatibility the installed jar to use disk space efficiently on the end user's computer, the three directories (content, locale, skin) are packed in a jar file. it is normally uncompressed, trading off some disk space for speed. this jar file will be ins...
Adding Event Handlers - Archive of obsolete content
following form: <script src="findfile.js"/> <script src="chrome://findfiles/content/help.js"/> <script src="http://www.example.com/js/items.js"/> this tutorial does not attempt to describe how to use javascript (except as related to event handling) as this is a fairly large topic and there are plenty of other resources that are available for this. by default the javascript console only shows
errors from web content. to show
errors in chrome javascript, it is necessary to change the preference javascript.options.showinconsole to true. you can also change the preference javascript.options.strict for debugging. by setting this value to true, non-standard, poorly written, or syntax prone to cause logic
errors are logged to the javascript console. responding to events the script will contain ...
Adding Properties to XBL-defined Elements - Archive of obsolete content
property of the orange. the script calculates the value and returns it. the onset handler of the size property of the banana is called. this script uses the value passed in the val variable and assigns it to the size property of the banana in some manner. note that unlike a field, a property does not hold a value. attempting to set a property that does not have an onset handler will generate an
error. you will often use a separate field to hold the actual value of the property. it is also common to have the properties match an attribute on the xbl-defined element. the following example maps a property to an attribute on an element. <property name="size" onget="return this.getattribute('size');" onset="this.setattribute('size', val);" /> whenever a script attempts to get t...
Focus and Selection - Archive of obsolete content
e second is the character after the last one that you want to have selected. values are zero-based, so the first character is 0, the second is 1 and so on. tbox.setselectionrange(4,8); this example will select the fifth character displayed, as well as the sixth, seventh and eighth. if there were only six characters entered into the field, only the fifth and sixth characters would be selected. no
error would occur. if you use the same value for both parameters, the start and end of the selection changes to the same position. this results in changing the cursor position within the textbox. for example, the line below can be used to move the cursor to the beginning of the text. tbox.setselectionrange(0,0); you can retrieve the current selection by using the selectionstart and selectionend proper...
Install Scripts - Archive of obsolete content
installed. you can also set files to be moved and deleted. start the process of installing the necessary files. it is important to note that during step two, you only indicate which files should be installed and any other operations you wish to have happen. no files get copied until step three. because of this, you can easily specify a number of files to be installed, come across some kind of
error, and abort the whole process without modifying the user's system. the component registry mozilla maintains a file which is a registry of all the components that are currently installed. components include new chrome packages, skins and plugins. when a new component is installed, the registry gets updated. the registry also stores the set of files and version information about the installed compon...
Localization - Archive of obsolete content
can just put the dtd file in the same directory as the xul file. note: you should encode dtd files as utf-8 for non-ascii characters. that is, you should save them in utf-8 format (without bom). for more information, see mozilla language packs. once you have created a dtd file for your xul, you will need to add a line to the xul file which indicates that you want to use the dtd file. otherwise,
errors will occur as it won't be able to find the entities. to do this, add a line of the following form somewhere near the top of the xul file: <!doctype window system "chrome://findfile/locale/findfile.dtd"> this line specifies that the url indicated is to be used as a dtd for the file. in this case, we have declared that we want to use the findfile.dtd dtd file. this line is typically placed just...
Manifest Files - Archive of obsolete content
e sure that the url in the line you added to installed-chrome.txt ends with a slash and the file itself ends with a blank line. on windows, file urls are of the form file:///c:/files/app/, where c is the drive letter. make sure the contents.rdf file is in the right directory and is well-formed. open the contents.rdf file in mozilla to see if it parses as well-formed xml. if not, you will see an
error on a yellow background. if you are using a debug build of mozilla, some info will be printed to the terminal when starting up indicating what chrome applications are being checked. check if your application is listed. the
error message "xml parsing
error: undefined entity" in your xul file can be caused by an
error in the manifest or in the jar file referenced by the manifest. for example, in <...
Manipulating Lists - Archive of obsolete content
ection all of the selection related properties described above may also be assigned a new value to change the selection. in the next example, the selectedindex property of a radiogroup element is changed based on the value entered in a textbox. this code isn't foolproof though; for example it doesn't check if the value entered is out of range. you will want to make sure that you add this kind of
error checking. example 3 : source view <script> function doselect(){ var val = document.getelementbyid('number').value; val = number(val); if (val != null) document.getelementbyid('level').selectedindex = val - 1; } </script> <hbox align="center"> <label value="enter a number from 1 to 3:"/> <textbox id="number"/> <button label="select" oncommand="doselect();"/> </hbox> <radiogroup...
Modifying a XUL Interface - Archive of obsolete content
ild() does. the replacechild() function removes an existing child and adds a new one in its place at the same position in the list of its parent element. finally the removechild() function removes a child from the list of its parent element. note that for all these functions, the object referred to by the variable referencechild or the variables newchild and oldchild must already exist or an
error occurs. likewise the object referred to by the variable child which is to be removed must already exist or an
error occurs. moving nodes to a different place it is often the case that you want to remove an existing element and add it somewhere else. if so, you can just add the element without removing it first. since a node may only be in one place at a time, the insertion call will always remove...
XUL Structure - Archive of obsolete content
url always refers to local files, the 'chrome://' url always refers to installed packages and extensions. we'll look more at the syntax of a chrome url in the next section. it is important to note that when accessing content through a chrome url, it gains the enhanced privileges described above that other kinds of urls do not. for instance, an http url does not have any special privileges, and an
error will occur if a web page tries, for example, to read a local file. however, a file loaded via a chrome url will be able to read files with the same access privileges as the installed extension. this distinction is important. this means that there are certain things that content of web pages cannot do, such as read the user's bookmarks. this distinction is not based on the kind of content being d...
notificationbox - Archive of obsolete content
function to be called when the button is activated. this function is passed three arguments: the <notification> the button is associated with the button description as passed to appendnotification. the element which was the target of the button press event. if the return value from this function is not true, then the notification is closed. the notification is also not closed if an
error is thrown. label - the label to appear on the button popup - the id of a popup for the button. if null, the button is not a button popup (e.g. a menu). the type property must also be set to "menu", or "menu-button". isdefault - if true, this is the default button. there can be only one default button. if no button has this set, the first button in the array is the default. type - a strin...
stringbundle - Archive of obsolete content
les | attributes | properties | methods | related ] an element which can be used to load localized resources from property files. stringbundles should be placed inside a stringbundleset element. a property file is a list of property key-value pairs each on a separate line. the key and value is separated with an equals sign. for example, the following defines two properties: message.display
error=an
error occured trying to display this message message.namealreadyused=the name %s is already being used by another account. more information is available in the xul tutorial. the "src" attribute accepts only absolute chrome:// urls (see bugs 133698, 26291) attributes src properties applocale , src, stringbundle, strings methods getformattedstring, getstring examples (exampl...
titlebar - Archive of obsolete content
is.only.xul" width="300" height="200" style="background: transparent; -moz-appearance: none;"> <titlebar flex="1" oncommand="close()" style="background: rgba(30, 30, 30, 0.9); -moz-border-radius: 10px; -moz-box-shadow: 0 1px 8px rgba(0, 0, 0, 0.8); margin: 8px 12px 16px;"/> </window> it can be opened from the
error console like this: open("file:///users/markus/sites/hudwindow.xul", "", "chrome=1, titlebar=0") attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu...
Deploying XULRunner - Archive of obsolete content
d copy this file from /library/frameworks/xul.framework/versions/1.8/xulrunner.) libmozglue.dylib (the main xul library) ... other executables and libraries the core changes to xul and gecko that require this new file layout were implemented in gecko 34, except that the xulrunner application was not updated to know about the change, so it will report an
error: "unable to load xpcom." xulrunner was fixed in gecko 39. see this blog post for additional background about this change. xulrunner 38 and earlier in xulrunner 38 and earlier, xulrunner is provided in a mac os x framework bundle, which is placed in your application bundle's frameworks directory. the complete bundle structure is as follows: myapp.app/ contents/ info.plist ...
Getting started with XULRunner - Archive of obsolete content
this might also be simplified using a very simple shell script (i call mine "run.sh"): #!/bin/sh /library/frameworks/xul.framework/xulrunner-bin `pwd`/application.ini linux on ubuntu, you can run the application from a terminal. first change into the \myapp folder, then start the application by: xulrunner application.ini you sh...
calICalendarView - Archive of obsolete content
e to show other dates as well, although this should be kept to a minimum. (for instance, calendar-month-view will show all dates from the start of the week of astartdate to the end of the week of aenddate.) setdatelist void setdatelist(in unsigned long acount, [array,size_is(acount)] in calidatetime adates); this function can only be called if supportsdisjointdates is true and will throw an
error if it is not. if supported, the dates in the adates array will become the only dates shown in the view. getdatelist void getdatelist(out unsigned long acount, [array,size_is(acount),retval] out calidatetime adates); this function returns a list of all dates currently being shown in the view. history calicalendarview was introduced as part of the 'backend rewrite' that occurred prior to li...
mozilla.dev.platform FAQ - Archive of obsolete content
: when using xul elements <browser/> and <tabbrowser/> the javascript popup windows don't work out of the box, what needs to be implement? a: have the browser.chromeurl preference - this should be a xul document containing a <browser type="content-primary"> element in which the popup window's content should get loaded. visual studio express 2005 q: when i try to run xulrunner-stub.exe i get the
error "this application failed to start because msvcr80.dll was not found." a: see bug 350616 ...
reftest opportunities files - Archive of obsolete content
introduction these are files in the mozilla source that may be usable for reftest. it is not always clear why particular files were checked in, but one presumes that something needed to be checked. many of these were checked with the layout regression test tool, which has been described as difficult to use and it apparently reported a lot of regressions that were not
errors. if you can look at the html in one of these pages, and can see a way to get the same visual ouptut, then that is an obvious reftest opportunity. for example, if some html is in an unexpected place and is supposed to be ignored, then we can match against an html file that is missing that extra mark-up. in other cases, the design of the reference page may take more subtlety. for now, create a bug in the core product, ...
2006-10-13 - Archive of obsolete content
estion for a way to recover toolbars from a popup window that disables it. user suggests 3 ways, and suggests a default. (no responses as of yet) selected tab looks too close to unselected tab discussion about how to change the colour of a selected tab and an unselected tab. it's suggested that its a os problem in the desktop theme, as opposed to problem with firefox. nsapprunner.o compile
error: some_const not declared in scope compile
error while compiling first build. user was conservative on what libraries they used, but now they have a compile
error and can't make sense of it. no responses as of yet. firefox browser problem: width:30ex does not respect font discussion about a font rendering problem with firefox print on the firefox context menu user would like discussion ab...
2006-11-24 - Archive of obsolete content
ow script to run in a sandbox during the update of a microsummary. they would like to discuss the use of it in bug 361026 rich results for searches a proposal for a search tool that gives users a quicker path to specific information they are looking for. trunk builds + winxp update = broken? a user questions if there is something broken in a nightly build since the user keeps getting this
error from the trunk: "firefox.exe - application
error: the application failed to initialize properly." removal of false positives in firefox 2 phishing a user inquires how to remove false positives from the firefox phising filters. meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
2006-10-06 - Archive of obsolete content
summary: mozilla.dev.builds - september 30th to october 6th 2006 tb mozilla_1_8_branch build problem on mac os x (10.4.7, universal build) ludwig hügelschäfer stated that he has been encountering an
error when he executes a "make export" operation on thunderbird (part of the mozilla_1_8_branch) since september 15th. ../../dist/host/bin/host_xpidl -m header -w -i~mozilla/xpcom/base -i../../dist/idl -o _xpidlgen/nsiconsolelistener ~/mozilla/xpcom/base/nsiconsolelistener.idl gmake[2]: *** [_xpidlgen/nsiconsolelistener.h] bus
error gmake[2]: *** deleting file `_xpidlgen/nsiconsolelistener.h' gmake[1]: *** [export]
error 2 make: *** [all]
error 2:: on octorber 4th ludwig hügelschäfer responded to his original post with the solution to his own problem. he found out th...
2006-10-13 - Archive of obsolete content
summary: mozilla.dev.builds - october 7th to october 13th 2006 cannot build ff 1.5.0.7 on linux x86_64 werner flamme cannot build firefox 1.5.0.7 on his suse linux 10.0 x86_64 box. he gets an
error in the middle of his build. he has disabled xft and has tried looking at related postings by benjamin smedberg gcc-40-workarounds and gcc-and-visibility-one-step-forward-hit-a-brick-wall announcements please help us test the new tinderbox and bonsai server installations paul reed announced that they are setting up a new installation of the tinderbox and bonsai servers onto new, supported hardware. some testing and validation has been done, but they would like other people to look at the installations and complete the setup before they switch over. new tinderbox installation new bon...
2006-11-17 - Archive of obsolete content
summary: mozilla.dev.builds - november 10th to november 17th 2006 how to build in yellowdog linux 4.1? november 11th: bryan wellander is trying to build mozilla 1.7.13 using yellowdog linux 4.1. however he has been unsuccessful and gets the following
errors: checking for gtk - version >= 1.2.0... no could not run gtk test program, checking why... the test program failed to compile or link. see the file config.log for the exact
error that occured. this usually means gtk was incorrectly installed or that you have moved gtk since it was installed. in the latter case, you may want to edit the gtk-config script: /usr/bin/gtk-config configure:
error: test for gtk failed bryan is asking for help as he is confused and has no idea what is causing the build process to fail. announceme...
Extentsions FAQ - Archive of obsolete content
osing e-mails via autodetect. <https://bugzilla.mozilla.org/show_bug.cgi?id=312818> "thunderbird requires domain in addresses and doesn't always add default" there is an extension that allows what you want attached to one of the comments in this bug. how to get the value of a text box when a button is clicked? read http://developer.mozilla.org/en/docs/extension_faq and check if there are any
errors in js console. friday, september 29 - october 6, 2006 (↑ top) is there anyway, via plugin or extension, for firefox to mimic the functionality of ie in this respect? the ietab (opens ie in a firefox tab) should be able do this if you set it to always open "file://*" urls in an ie tab. the appearance with a firefox tab isn't quite the same as having a completely separate explorer window. h...
2006-09-29 - Archive of obsolete content
orm summary: mozilla.dev.platform - september 22 - 29, 2006 announcements firefox 2 release candidate 1 is now available for download announcing that firefox 2 rc 1 is available for download discussions xulrunner fails without feedback on osx intel 10.4.7 will morton is trying to port a xul application to osx. when he runs xulrunner from the command line, it fails silently without any
errors. this happens with all his xulrunner ports, with xulrunner 1.8.0.1, 1.8.0.4 and nightly 1.8. benjamin smedberg was able to point out one possible flaw. instead of using /path/to/xulrunner-bin.ini (which will was doing) applications on a mac must be in an application bundle (foo.app). then use xulrunner -install-app to "unpack" the xul app into the mac structure. meetings no meetings this wee...
2006-11-17 - Archive of obsolete content
mmary: mozilla.dev.tech.layout - november 11 - november 17, 2006 announcements none this week. discussions testing accesskey conflicts discussion about the complexity of access keys and how to detect conflicts there in the l10n community. bug #360589 describes this ongoing issue. site not loading with seamonkey a user built seamonkey in debug mode and is currently receiving a "bad request"
error on some websites. reflow branch testing wanted l. david baron would like users to test the reflow branch as it is coming close to being merged with the trunk. nightly builds, instructions and the current list of known regressions on the branch can be found at: http://wiki.mozilla.org/gecko:reflow...ng#quick_links. users are asked to file bugs on encountered problems that are not present on the c...
2006-12-08 - Archive of obsolete content
ummary: mozilla.dev.tech.xpcom - dec 02- dec 08, 2006 announcements none during this week. discussions xpcom cpp to js callback engaging discussion on a problem with trying to call back from c++ to a javascript object using an interface the developer created with an idl. however, the c++ call that's supposed to be invoking the method on the javascript object is returning with 0x80004005 (ns_
error_failure). saving binary data from nsixmlhttprequest a discussion on how to use nsixmlhttprequest object to query data from a url in an extension implemented in javascript meetings none during this week. ...
2006-11-17 - Archive of obsolete content
november 10 - november 17, 2006 announcements no meeting for this week. discussions itip and imip new designs for sending invitations available for comment discussion about the new interface designs for itip. view performance discussion about tests on view performance. webdav server a discussion related to remote calendar modifications. calendar xpcom component discussion about a debug
error of additem function from calicalendar. meetings no meetings were scheduled this week. authors mark paruzel yi (eric) shen [back to weekly summaries ] ...
NPClass - Archive of obsolete content
ction, or free(). any attempt to use an invalidated object will result in undefined behavior. hasmethod called by npn_hasmethod() to determine whether or not a specified method exists on a given npobject. returns true if the method exists, otherwise returns false. invoke called by npn_invoke() to invoke a specific method on a given npobject. returns true if invocation succeeded or false if an
error occurred. invokedefault called by npn_invokedefault() to invoke the default method (if available) on a given npobject. returns true if invocation succeeded or false if an
error occurred. hasproperty called by npn_hasproperty() to check whether a given property exists on a given npobject. returns true if the specified property exists, otherwise returns false. getproperty called by npn_getpro...
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_setexception(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. ...
NPP_Destroy - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary deletes a specific instance of a plug-in. syntax #include <npapi.h> np
error npp_destroy(npp instance, npsaveddata **save); parameters the function has the following parameters: instance pointer to the plug-in instance to delete. **save state or other information to save for reuse by a new instance of this plug-in at the same url. passed to npp_new. 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 npp_destroy releases the instance data and resources associated with a plug-in. the browser calls this function when a plug-in instance is delet...
NPP_GetValue - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary allows the browser to query the plug-in for information. syntax #include <npapi.h> np
error npp_getvalue(void *instance, nppvariable variable, void *value); parameters the function has the following parameters: instance pointer to the plugin instance from which the value should come. variable variable for which the browser (caller) would like a value. the full list is in the npapi headers. value value for the requested variable. returns if successful, the function returns nperr_no_
error. if unsuccessful, the function returns an
error code. for possible values, see
error codes. description npp_getvalue retrieves instance variables. see also npp_setvalue, np...
NPP_SetValue - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary implemented by plugins. this call is used to inform plugins of variable information controlled by the browser. syntax #include <npapi.h> np
error npp_setvalue(void *instance, npnvariable variable, void *value); parameters the function has the following parameters: instance pointer to plugin instance on which to set the variable. variable the variable being set. value value for the variable being set. returns if successful, the function should return nperr_no_
error. if unsuccessful, the function should return the most relevant npapi
error code. for possible values, see
error codes. description none see also npp_new, npp_getvalue, npn_setvalue, npn_ge...
NPP_SetWindow - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary tells the plug-in when a window is created, moved, sized, or destroyed. syntax #include <npapi.h> np
error npp_setwindow(npp instance, npwindow *window); parameters the function has the following parameters: instance pointer to the current plug-in instance. must be embedded or full-screen. window pointer to the window into which the instance draws. the window structure contains a window handle and values for top left corner, width, height, and clipping rectangle (see note on unix 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 the browser calls npp_setwi...
NPP_Write - Archive of obsolete content
ter returning from the function, so the plug-in should make a copy of the data it needs to keep. returns the plug-in should return the number of bytes written (consumed by the instance). if the return value is smaller than the size of the buffer, the browser sends the remaining data to the plug-in through subsequent calls to npp_writeready and npp_write. if unsuccessful, the function signals an
error by returning a negative value. the browser will destroy the stream by calling npp_destroystream. description the browser calls the npp_write function to deliver the data specified in a previous npp_writeready call to the plug-in. a plug-in must consume at least as many bytes as indicated in the npp_writeready call. after a stream is created by a call to npp_newstream, the browser calls npp_write ...
NPAPI plugin reference - Archive of obsolete content
fied 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_setexception 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 a url, in particular its cookies. (while the api theoretically allows the preferred proxy for a given url to...
Adobe Flash - Archive of obsolete content
mach-o browser, determine whether the version of the plugin // is greater than 12, a hypothetical version when flash will fix the plugin to be // scriptable on mach-o browsers also var flashversionosxscriptable = 12; if(navigator.useragent.indexof("mach-o")!=-1) { if(flashversion < flashversionosxscriptable) // flash version is less than version 12, thus not scriptable on os x } // 6. handle
errors (no flash installed, etc.) example 1 uses the regexp (regular expression) object exposed to javascript strings. the description string is broken into an array of constituent strings based on an invocation of the match method with a regular expression that assumes that the string format will be in the format flash major rminor where major can be a major revision such as "5" or "6" and minor is ...
Writing a plugin for Mac OS X - Archive of obsolete content
tentrypoints() np_shutdown() the sample plugin is written entirely in c, using a standard xcode build configuration, so by default all of its symbols are c-style and visible. if you want to implement your plugin in c++ or objective-c++, you need to tell the compiler to export them in c format by using extern "c" in the header, like this: #pragma gcc visibility push(default) extern "c" { np
error np_initialize(npnetscapefuncs *browserfuncs); np
error np_getentrypoints(nppluginfuncs *pluginfuncs); void np_shutdown(void); } #pragma gcc visibility pop you can check to be sure your symbols are visible and in standard c format by using the nm utility provided among the mac os x developer tools: [user@foo mymac] nm basicplugin ... 00000810 t _np_getentrypoints 000007fa t _np_initialize ...
Vulnerabilities - Archive of obsolete content
oited to negatively impact confidentiality, integrity, and/or availability. there are many ways in which vulnerabilities can be categorized. this article uses three high-level vulnerability categories: software flaws, security configuration issues, and software feature misuse. these categories are described below. vulnerability categories a software flaw vulnerability is caused by an unintended
error in the design or coding of software. an example is an input validation
error, such as user-provided input not being properly evaluated for malicious character strings and overly long values associated with known attacks. another example is a race condition
error that allows the attacker to perform a specific action with elevated privileges. a security configuration setting is an element of a sof...
Sunbird Theme Tutorial - Archive of obsolete content
in firefox 1.5, and examine its interface. the details are mostly the same as in sunbird. note: sunbird's views changed at the end of december 2005. so do not waste time styling the old views. work with a recent test build so that your theme will be compatible with the next release. testing further changes when you make further changes to your theme, test them by restarting sunbird. to detect
errors, choose tools – javascript console... the javascript console window displays css
errors, not just javascript
errors. making an icon and preview the themes window can display an icon and a preview graphic. you normally make these after you have designed the rest of your theme. make an image file 32 by 32 pixels, and save it as <tt>icon.png</tt> in your theme directory. make an image file abo...
Building a Theme - Archive of obsolete content
newer than the newest currently available version! in this case, "39.*" indicates that the extension works with firefox 39 and any subsequent 39.x release. themes are compatible by default, unless you set strict compatibility mode for your theme. if you get a message that the install.rdf is malformed, it is helpful to load it into firefox using the file->open file command and it will report xml
errors to you. see install manifests for a complete listing of the required and optional properties. save the file. styling the browser's ui with css firefox's user interface is written in xul and javascript. xul is an xml grammar that provides user interface widgets like buttons, menus, toolbars, trees, etc. user actions are bound to functionality using javascript. these xul elements are styled ...
Theme changes in Firefox 2 - Archive of obsolete content
the box that displays the feed icon. #content style information for the content area of the window. #sitelabel style information for the site label. feeds/subscribe.css this is a new file in firefox 2. it skins the window displayed to subscribe to an rss feed, which is at browser/feeds/subscribe.xhtml. ...
Processing XML with E4X - Archive of obsolete content
o>. in attribute substitution, quotation marks are escaped as " while apostrophes are handled normally. var b = 'he said "don\'t go there."'; var el = <foo a={b}/>; alert(el.toxmlstring()); // gives: <foo a="he said "don't go there.""/> less than and ampersand signs are escaped into their entity equivalents. since a greater than sign is not escaped, it is possible to get an xml
error if the cdata closing sequence (]]>) is included. it is not possible to directly interpolate variables amidst other literal (or variable) attribute content, however (e.g., bar="a{var1}{var2}"). one must instead either calculate the variable with a javascript expression (e.g., bar={'a'+var1+var2}), define a new variable before the element literal which includes the full interpolation and then incl...
ArrayBuffer.transfer() - Archive of obsolete content
ngth of the memory and only copies it to a new location as-needed as opposed to the following pollyfill which always copies the whole thing to a new space of memory, but this function transfers data from one arraybuffer to another arraybuffer. ...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of async operation. }, function (
error) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_
error); debug.mstraceasynccallbackstarting(opid); }); debug.mstraceasynccallbackcompleted(); } function dosomethingasync() { return winjs.promise.as(true); } asyncwrapperfunction(); requirements supported in the internet explorer 11 standards document mode. also supported in store apps (window...
Debug.msUpdateAsyncCallbackRelation - Archive of obsolete content
ion. this function may be called when an asynchronous operation is aborted, when a join operation is used, or in other scenarios. the possible values for relationtype include: debug.ms_async_callback_status_assign_delegate debug.ms_async_callback_status_join debug.ms_async_callback_status_chooseany debug.ms_async_callback_status_cancel debug.ms_async_callback_status_
error for more information, see debug constants. note: some debugging tools do not display the information sent to the debugger by this function. requirements supported in the internet explorer 11 standards document mode. also supported in store apps (windows 8.1 and windows phone 8.1). not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7...
VBArray.lbound - Archive of obsolete content
xtension and is only supported in internet explorer. the vbarray.lbound method returns the lowest index value used in the specified dimension of a vbarray. syntax safearray.lbound(dimension) remarks if the vbarray is empty, the lbound method returns undefined. if dimension is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range"
error. parameters safearray a vbarray object. dimension optional optional. the dimension of the vbarray for which the lower bound index is wanted. if omitted, lbound behaves as if a 1 was passed. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions...
VBArray.ubound - Archive of obsolete content
dimension) parameters safearray a vbarray object. dimension optional the dimension of the vbarray for which the higher bound index is wanted. if omitted, ubound behaves as if a 1 was passed. remarks if the vbarray is empty, the ubound method returns undefined. if dim is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range"
error. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to ru...
Microsoft JavaScript extensions - Archive of obsolete content
ternet explorer, and in a few cases, microsoft edge) support a number of special microsoft extensions to the otherwise standard javascript apis. objects activexobject debug enumerator vbarray functions getobject scriptengine scriptenginebuildversion scriptenginemajorversion scriptengineminorversion statements @cc-on @if @set other date.getvardate()
error.description
error.number
error.stacktracelimit ...
New in JavaScript 1.2 - Archive of obsolete content
ring.prototype.substr() new operators delete equality operators (== and !=) new statements labeled statements switch do...while import export other new features regular expressions signed scripts changed functionality in javascript 1.2 you can now nest functions within functions. number now converts a specified object to a number. number now produces nan rather than an
error if x is a string that does not contain a well-formed numeric literal. string now converts a specified object to a string. array.prototype.sort() now works on all platforms. it no longer converts undefined elements to null and sorts them to the high end of the array. string.prototype.split() it can take a regular expression argument, as well as a fixed string, by which to split the object...
New in JavaScript 1.5 - Archive of obsolete content
tandard is ecma-262 edition 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 ar...
Reflect.enumerate() - Archive of obsolete content
ethod 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 type
error, 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. ...
LiveConnect Reference - Archive of obsolete content
this section documents the java classes used for liveconnect, along with their constructors and methods. javascript-to-java these classes allow a java object to access javascript code. jsexception the public class jsexception extends runtimeexception, and is thrown when javascript returns an
error. jsobject the public class jsobject extends object. javascript objects are wrapped in an instance of the class jsobject and passed to java, allowing java to manipulate javascript objects. java-to-javascript global objects java packages netscape sun javaarray javaclass javaobject javapackage ...
Reference - Archive of obsolete content
t that has an internal [[call]] or [[construct]] property) are functions as well as objects (including the function object itself). the reason object instanceof function evaluates to true is because object can be used as a constructor function. a subset of the "object > (function, everything else)" chain could be object > function > (object, function, array, string, boolean, number, date, regexp,
error). array, for example, as a constructor function is an instance of the function object, which happens to be an instance of object; therefore, array is also an instance of object. this makes sense. the confusion sets in when you consider that object is also a constructor function, therefore an instance of function, and, furthermore, an instance of object; this is where the recursion is introduced, ...
forEach - Archive of obsolete content
ementation above while retaining the rest of the document. feel free to alter the text as english is not my mother tongue and i'm more concerned with the code quality that the english grammar ;-s dotnetcarpenter 30 june 2012 <hr> the compatibility section goes to extraordinary lengths in providing a foreach implementation. a much more sane approach would be to count on the implementation to throw
errors if wrong arguments are provided and implement this in fewer lines of code. i've removed the lengthy example, while still linking to it and provided a much simpler and leaner implementation. dotnetcarpenter 30 june 2012 <hr> i have released the write access restriction, but i will be watching changes closely. jswisher 01 october 2011 <hr> there is some mistype in array.prototype.foreach: kvalue =...
Writing JavaScript for XHTML - Archive of obsolete content
iv xmlns="http://www.w3.org/999/xhtml"><h1>hello world!</h1></div>'; var parser = new domparser(); var documentfragment = parser.parsefromstring(string, "text/xml"); body.appendchild(documentfragment); // assuming 'body' is the body element but be aware that if your string is not well-formed xml (e.g., you have an & where it should not be), then this method will crash, leaving you with a parser
error. problem: i want to remain forward compatible! given the direction away from formatting attributes and the possibility of xhtml becoming eventually more prominent (or at least the document author having the possibility of later wanting to make documents available in xhtml for browsers that support it), one may wish to avoid features which are not likely to stay compatible into the future. solu...
Developing Mozilla XForms - Archive of obsolete content
uilds. you should create a new, clean profile for debugging. then start firefox out of the build directory: cd obj-*/dist/firefox ./firefox -no-remote -jsconsole -p yourprofilename the xforms extension that was built together with firefox should be already installed. then open your form that causes problems and have a look on the console. often you'll find the first starting points here or in the
error console. schema validation problems the schema-validation extension contains a logging facility that can show some internals on the schema processing. to activate this logging output, set the nspr_log_modules environment variable: export nspr_log_modules=schemavalidation:5 this only works on a debug build as described above. ...
XForms Repeat Element - Archive of obsolete content
on setindex, its repeat attribute (which contains an idref) can point to any element carrying these repeat attributes. similarly, the index function can be used with the repeating structures created via these repeat-attributes. the id of the element that contains the repeat attributes can be used as the argument to index. note, we don't fully support attribute-based repeats. there are a number of
errors that may occur, especially when these attributes are used with html:table. be sure to test your form carefully. example <xforms:model id="i_model"> <xforms:instance xmlns=""> <data xmlns:html="http://www.w3.org/1999/xhtml" xmlns=""> <val id="1"> <nest>nest 1.1</nest> <nest>nest 1.2</nest> </val> <val id="2"> <nest>nest 2.1</nest> <nest>n...
XForms Config Variables - Archive of obsolete content
a description of the about:config preferences that xforms uses. preference default description xforms.disablepopup false disables xforms engine popup
error messages xforms.enableexperimentalfeatures false enable experimental features. for now it only enables the xforms 1.1 soap action feature, and only on trunk. ...
Using XForms and PHP - Archive of obsolete content
to be served as xml, for example application/xhtml+xml. to do that, you need to use the header() php function: <?php header("content-type: application/xhtml+xml; charset=utf-8"); ... ?> but remember this (quote from php documentation): remember that header() must be called before any actual output is sent, either by normal html tags, blank lines in a file, or from php. it is a very common
error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. the same problem exists when using a single php/html file. parsing submitted data depending on the submission type, you might get different data formats on the server side. to really use the power of xforms (/xml) you would probably s...
RDF in Mozilla FAQ - Archive of obsolete content
llows you to spy on a datasource's progress. the following code illustrates its usage: // this is the object that will observe the rdf/xml load's progress var observer = { onbeginload: function(asink) {}, oninterrupt: function(asink) {}, onresume: function(asink) {}, onendload: function(asink) { asink.removexmlsinkobserver(this); alert("done!"); }, on
error: function(asink, astatus, a
errormsg) { alert("
error! " + a
errormsg); } }; // get the rdf service var rdf = components .classes["@mozilla.org/rdf/rdf-service;1"] .getservice(components.interfaces.nsirdfservice); // get the datasource. var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // now see if it's loaded or not... var remote = ds.queryinterface(components.int...
The Business Benefits of Web Standards - Archive of obsolete content
ave a known benchmark to measure the known deviations of legacy user agents. nearly all of those deviations are now well documented and the fixes are well published and well known. conversely fixing tag soup is a black hole of time and money. well-formed code significantly reduces rendering differences in various browsers. using validation tools such as the w3c validator helps by spotting coding
errors and making sure html code is well-formed, which eliminates ambiguity in parsing by browsers. standards embrace new browsers more and more browsers, other than internet explorer for windows, are used to surf the web: windows: msie, browsers using mozilla's gecko rendering engine, opera mac: ms-tasman (ie/mac's rendering engine), gecko-based browsers, safari, opera linux: gecko-based browse...
XUL Parser in Python - Archive of obsolete content
n modules made available as xpcom objects. extending on the approach in this script, then, you could imagine a kind of introspective xul chrome that could modify and replicate itself by calling services from the xulparser and xulwriter xpcom objects. please feel free to suggest changes, change the format of the results output, or adapt this script in any way you want. i have probably made some
errors and undoubtedly written some strange, graceless python. most of all, please feel free to experiment with the mozilla development platform in this way or in any other way you can imagine. original document information author: ian oeschger ...
Async scripts for asm.js - Game development
d(script); both are counted as 'inline' scripts and get compiled and then run immediately. what if your code is in a js string? instead of using eval or innerhtml, both of which trigger synchronous compilation, you should use a blob with an object url: var blob = new blob([codestring]); var script = document.createelement('script'); var url = url.createobjecturl(blob); script.onload = script.on
error = function() { url.revokeobjecturl(url); }; script.src = url; document.body.appendchild(script); the setting of src rather than innerhtml is what makes this script async. ...
502 - MDN Web Docs Glossary: Definitions of Web-related terms
a server can act as a gateway or proxy (go-between) between a client (like your web browser) and another, upstream server. when you request to access a url, the gateway server can relay your request to the upstream server. "502" means that the upstream server has returned an invalid response. normally the upstream server is not down (i.e. furnishes no response to the gateway/proxy), but simply does not understand the same data-exchange protocol as the gateway/proxy. internet protocols are quite explicit, and so a 502 usually means that one or both machines were incorrectly or incompletely programmed. ...
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
tarts carrying out the function. any functions that are called by that function are added to the call stack further up, and run where their calls are reached. when the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. if the stack takes up more space than it had assigned to it, it results in a "stack overflow"
error. example function greeting() { // [1] some codes here sayhi(); // [2] some codes here } function sayhi() { return "hi!"; } // invoke the `greeting` function greeting(); // [3] some codes here the code above would be executed like this: ignore all functions, until it reaches the greeting() function invocation. add the greeting() function to the call stack list. call sta...
Function - MDN Web Docs Glossary: Definitions of Web-related terms
loop = x => { if (x >= 10) return; loop(x + 1); }; an immediately invoked function expressions (iife) is a function that is called directly after the function is loaded into the browser’s compiler. the way to identify an iife is by locating the extra left and right parenthesis at the end of the function’s definition. ...
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
itializations. 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 reference
error exception. console.log(num); // throws reference
error 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 ho...
IIFE - MDN Web Docs Glossary: Definitions of Web-related terms
ked function expression () through which the javascript engine will directly interpret the function. examples the function becomes a function expression which is immediately executed. the variable within the expression can not be accessed from outside it. (function () { var aname = "barry"; })(); // variable aname is not accessible from the outside scope aname // throws "uncaught reference
error: aname is not defined" assigning the iife to a variable stores the function's return value, not the function definition itself. var result = (function () { var name = "barry"; return name; })(); // immediately creates the output: result; // "barry" ...
NaN - MDN Web Docs Glossary: Definitions of Web-related terms
square root of a negative (which is imaginary, whereas a floating-point number is real). practically speaking, if i divide two variables in a javascript program, the result may be nan, which is predefined in javascript as "undefined". hence this division may break the program. now, if this computation was a small part of a much larger algorithm, it would be really painful to figure out where the
error actually occurs. fortunately, since the result will be nan and i know my divisor may turn out to be 0, i can set up testing conditions that prevent any such computations in the first place or notify me of where they happen. learn more general knowledge nan on wikipedia technical information nan in javascript ...
QUIC - MDN Web Docs Glossary: Definitions of Web-related terms
remely slow process. the creation of quic allows developers to conduct experiments and try new things faster. quic was designed to support the semantics of http/2. it provides multiplexing, flow control, security and congestion control. key features of quic include: reduction in connection establishment time. improved congestion control. multiplexing without head-of-line blocking. forward
error correction. connection migration. there is limited browser and server support for quic today. resources chromium projects documentation ietf draft see also http/2 ...
SMTP - MDN Web Docs Glossary: Definitions of Web-related terms
smtp (simple mail transfer protocol) is a protocol used to send a new email. like pop3 and nntp, it is a state machine-driven protocol. the protocol is relatively straightforward. primary complications include supporting various authentication mechanisms (gssapi, cram-md5, ntlm, msn, auth login, auth plain, etc.), handling
error responses, and falling back when authentication mechanisms fail (e.g., the server claims to support a mechanism, but doesn't). ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
no ecmascript 5 equivalent for symbol. in some programming languages, the symbol data type is referred to as an "atom." symbols don't "auto-convert" to strings most values in javascript support implicit conversion to a string. for instance, we can alert almost any value, and it will work. symbols are special. they don’t auto-convert. for example: let sym = symbol("sym") alert(sym) // type
error: cannot convert a symbol value to a string that’s a "language guard" against messing up, because strings and symbols are fundamentally different, and should not occasionally convert one into another. if you really want to show a symbol, we need to call .tostring() on it. let sym = symbol("sym") alert(sym.tostring()) // symbol(sym), now it works or you can use the symbol.description proper...
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
es not mean the two langauges share similarities with syntax. syntax applies both to programming languages (commands to the computer) and markup languages (document structure information) alike. syntax only governs ordering and structure; the instructions must also be meaningful, which is the province of semantics. code must have correct syntax in order to compile correctly, otherwise a syntax
error occurs. even small
errors, like a missing parenthesis, can stop source code from compiling successfully. frameworks are said to have a "clean" syntax if they produce simple, readable, concise results. if a codebase uses "a lot of syntax", it requires more characters to achieve the same functionality. learn more general knowledge syntax (programming languages) on wikipedia ...
TCP - MDN Web Docs Glossary: Definitions of Web-related terms
tcp (transmission control protocol) is an important network protocol that lets two hosts connect and exchange data streams. tcp guarantees the delivery of data and packets in the same order as they were sent. vint cerf and bob kahn, who were darpa scientists at the time, designed tcp in the 1970s. tcp role is to ensure the packets are reliably delivered,
error free. tcp has concurrence control, which means the initial requests start small, increasing in size to the levels of bandwidth the computers, servers, and network can support. ...
Transport Layer Security (TLS) - MDN Web Docs Glossary: Definitions of Web-related terms
onnection. it is possible for both the client and server to mutually authenticate each other, if both parties provide their own individual digital certificates. note: tls 1.0 and 1.1 support will be removed from all major browsers in early 2020; you'll need to make sure your web server supports tls 1.2 or 1.3 going forward. from version 74 onwards, firefox will return a secure connection failed
error when connecting to servers using the older tls versions (bug 1606734). ...
Unicode - MDN Web Docs Glossary: Definitions of Web-related terms
unicode is a standard character set that numbers and defines characters from the world's different languages, writing systems, and symbols. by assigning each character a number, programmers can create character encodings, to let computers store, process, and transmit any combination of languages in the same file or program. before unicode, it was difficult and
error-prone to mix languages in the same data. for example, one character set would store japanese characters, and another would store the arabic alphabet. if it was not clearly marked which parts of the data were in which character set, other programs and computers would display the text incorrectly, or damage it during processing. if you've ever seen text where characters like curly quotes (“”) were replaced with gibberish ...
beacon - MDN Web Docs Glossary: Definitions of Web-related terms
a web beacon is a small object, such as a 1 pixel gif, embedded in markup, used to communicate information back to the web server or to 3rd party servers. beacons are generally included to provide information about the user for statistical purposes. beacons are often included within third party scripts for collecting user data, performance metrics and
error reporting. there is a w3c draft beacon specification to standardize the beacon as an interface to asynchronously transfer http data from user agent to a web server prior to page load without negative performance impact. see also real user monitoring (rum) ...
MDN Web Docs Glossary: Definitions of Web-related terms
speed index sql sql injection sri stacking context state machine statement static method static typing strict mode string stun style origin stylesheet svg svn symbol symmetric-key cryptography synchronous syntax syntax
error synthetic monitoring t tag tcp tcp handshake tcp slow start telnet texel thread three js time to first byte time to interactive tld tofu transmission control protocol (tcp) transport layer security (tls) tree shaking trident ...
HTML: A good basis for accessibility - Learn web development
between all those state colors and the background color. onclick events anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. these values cause unexpected behavior when copying or dragging links, opening links in a new tab or window, bookmarking, and when javascript is still downloading,
errors out, or is disabled. this also conveys incorrect semantics to assistive technologies (e.g., screen readers). in these cases, it is recommended to use a <button> instead. in general you should only use an anchor for navigation using a proper url. external links and linking to non-html resources links that open in a new tab or window via the target="_blank" declaration and links to whose href va...
HTML: A good basis for accessibility - Learn web development
between all those state colors and the background color. onclick events anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. these values cause unexpected behavior when copying or dragging links, opening links in a new tab or window, bookmarking, and when javascript is still downloading,
errors out, or is disabled. this also conveys incorrect semantics to assistive technologies (e.g., screen readers). in these cases, it is recommended to use a <button> instead. in general you should only use an anchor for navigation using a proper url. external links and linking to non-html resources links that open in a new tab or window via the target="_blank" declaration and links to whose href va...
Fundamental CSS comprehension - Learn web development
us rounded corners that fit in with the rounded corners set on the main card container. float the image to the right so that it sticks to the right hand side of the main business card contents, and give it a max-height of 100% (a clever trick that ensures that it will grow/shrink to stay the same height as its parent container, regardless of what height it becomes.) beware! there are two
errors in the provided rulesets. using any technique that you know, track these down and fix them before moving on. new rulesets you need to write: write a ruleset that targets both the card header, and card footer, giving them both a computed total height of 50px (including a content height of 30px and padding of 10px on all sides.) but express it in ems. the default margin applied to the <h2> a...
Images, media, and form elements - Learn web development
elements, such as <textarea> for multiline text input, and also elements used to contain and label parts of forms such as <fieldset> and <legend>. html5 also contains attributes that enable web developers to indicate which fields are required, and even the type of content that needs to be entered. if the user enters something unexpected, or leaves a required field blank, the browser can show an
error message. different browsers are inconsistent in how much styling and customization they allow for such items. styling text input elements elements that allow for text input, such as <input type="text">, specific types such as <input type="email">, and the <textarea> element are quite easy to style and tend to behave just like other boxes on your page. the default styling of these elements will ...
Attribute selectors - Learn web development
e value. it selects the second list item. li[class~="a"] will match a class of a but also a value that contains the class of a as part of a whitespace-separated list. it selects the second and third list items. substring matching selectors these selectors allow for more advanced matching of substrings inside the value of your attribute. for example, if you had classes of box-warning and box-
error and wanted to match everything that started with the string "box-", you could use [class^="box-"] to select them both (or [class|="box"] as described in section above). selector example description [attr^=value] li[class^="box-"] matches elements with an attr attribute (whose name is the value in square brackets), whose value begins with value. [attr$=v...
Pseudo-classes and pseudo-elements - Learn web development
lector description ::after matches a stylable element appearing after the originating element's actual content. ::before matches a stylable element appearing before the originating element's actual content. ::first-letter matches the first letter of the element. ::first-line matches the first line of the containing element. ::grammar-
error matches a portion of the document containing a grammar
error as flagged by the browser. ::marker matches the marker box of a list item, which typically contains a bullet or number. ::selection matches the portion of the document that has been selected. ::spelling-
error matches a portion of the document containing a spelling
error as flagged by the browser. ...
How CSS is structured - Learn web development
ng to personal preference. for team projects, you may find that a team or project has its own style guide. important: though white space separates values in css declarations, property names never have white space. for example, these declarations are valid css: margin: 0 auto; padding-left: 10px; but these declarations are invalid: margin: 0auto; padding- left: 10px; do you see the spacing
errors? first, 0auto is not recognized as a valid value for the margin property. the entry 0auto is meant to be two separate values: 0 and auto. second, the browser does not recognize padding- as a valid property. the correct property name (padding-left) is separated by an errant space. you should always make sure to separate distinct values from one another by at least one space. keep property name...
CSS FAQ - Learn web development
last definition is used. #stockticker { font-weight: bold; } .stocksymbol { color: red; } /* other rules */ /* other rules */ /* other rules */ .stocksymbol { font-weight: normal; } <!-- most text is in bold, except "ge", which is red and not bold --> <div id="stockticker"> nys: <span class="stocksymbol">ge</span> +1.0 ... </div> to avoid this kind of
error, try to define rules only once for a certain selector, and group all rules belonging to that selector. use of a shorthand property using shorthand properties for defining style rules is good because it uses a very compact syntax. using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values...
Styling links - Learn web development
simply enlarging and centering the text to make it stand out more.) <p><a href="#">a simple link</a></p> p { font-size: 2rem; text-align: center; } note: all the links in the examples in this page are fake links — a # (hash, or pound sign) is put in place of the real url. this is because if the real links were included, clicking on them would break the examples (you'd end up with an
error, or a page loaded in the embedded example that you couldn't get back from.) # just links to the current page. you'll notice a few things as you explore the default styles: links are underlined. unvisited links are blue. visited links are purple. hovering a link makes the mouse pointer change to a little hand icon. focused links have an outline around them — you should be able to focus ...
How do you upload your files to a web server? - Learn web development
file synchronizing tool, which is generally available on most unix-based systems (like macos and linux), but windows versions exist too. it is seen as a more advanced tool than sftp, beause by default it is used on the command line. a basic command looks like so: rsync [-options] source user@x.x.x.x:destination -options is a dash followed by a one or more letters, for example -v for verbose
error messages, and -b to make backups. you can see the full list at the rsync man page (search for "options summary"). source is the path to the local file or directory that you want to copy files over from. user@ is the credentials of the user on the remote server you want to copy files over to. x.x.x.x is the ip address of the remote server. destination is the path to the location you want to co...
UI pseudo-classes - Learn web development
ired and :optional pseudo-classes. for example, if we apply the following css to the above html: input:required { border: 1px solid black; } input:optional { border: 1px solid silver; } the required controls would have a black border, and the optional control will have a silver border, like so: you can also try submitting the form without filling it in, to see the client-side validation
error messages browsers give you by default. the above form isn't bad, but it isn't great either. for a start, we are signalling required versus optional status using color alone, which isn't great for colorblind people. second, the standard convention on the web for required status is an asterisk (*), or the word "required" being associated with the controls in question. in the next section, we'll l...
What’s in the head? Metadata in HTML - Learn web development
lesheet" href="my-css-file.css"> the <script> element should also go into the head, and should include a src attribute containing the path to the javascript you want to load, and defer, which basically instructs the browser to load the javascript at the same time as the page's html. this is useful as it makes sure that the html is all loaded before the javascript runs, so that you don't get
errors resulting from javascript trying to access an html element that doesn't exist on the page yet. there are actually a number of ways to handle loading javascript on your page, but this is the most foolproof one to use for modern browsers (for others, read script loading strategies). <script src="my-js-file.js" defer></script> note: the <script> element may look like an empty element, but...
Introduction to HTML - Learn web development
your page (such as "a paragraph" or "an image"), html is also used to define areas of your website (such as "the header," "the navigation menu," or "the main content column.") this article looks into how to plan a basic website structure and how to write the html to represent this structure. debugging html writing html is fine, but what if something goes wrong, and you can't work out where the
error in the code is? this article will introduce you to some tools that can help. assessments the following assessments will test your understanding of the html basics covered in the guides above. marking up a letter we all learn to write a letter sooner or later; it is also a useful example to test out text formatting skills. in this assessment, you'll be given a letter to mark up. structurin...
HTML table advanced features and accessibility - Learn web development
thead> <tbody> <tr> <th id="haircut">haircut</th> <td headers="location haircut">hairdresser</td> <td headers="date haircut">12/09</td> <td headers="evaluation haircut">great idea</td> <td headers="cost haircut">30</td> </tr> ... </tbody> note: this method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for
errors. the scope approach is usually enough for most tables. active learning: playing with scope and headers for this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory. now try adding in the appropriate scope attributes to make this table more appropriate. finally, try making another copy of the starter files, and this time ma...
Build your own function - Learn web development
veloper tools on the example page, go to the javascript console and type the line again there, you'll see it appear again! so this is fun — we now have a reusable function that we can call any time we like. but we probably want it to appear in response to user and system actions. in a real application, such a message box would probably be called in response to new data being available, or an
error having occurred, or the user trying to delete their profile ("are you sure about this?"), or the user adding a new contact and the operation completing successfully, etc. in this demo, we'll get the message box to appear when the user clicks the button. delete the previous line you added. next, we'll select the button and store a reference to it in a constant. add the following line to you...
Test your skills: Events - Learn web development
od our introduction to events article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to ...
Test your skills: Functions - Learn web development
, and function return values articles. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to ...
Introduction to web APIs - Learn web development
te a new instance of a request object using the xmlhttprequest() constructor, open an http get request to retrieve the specified resource, specify that the response should be sent in json format, then send the request. the onload handler function then specifies what we do with the response. we know the response will be successfully returned and available after the load event has fired (unless an
error occurred), so we save the response containing the returned json in the superheroes variable, then pass it to two different functions for further processing. they have additional security mechanisms where appropriate webapi features are subject to the same security considerations as javascript and other web technologies (for example same-origin policy), but they sometimes have additional securit...
Arrays - Learn web development
red in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom. if we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. this would be much longer to write out, less efficient, and more
error-prone. if we had 10 items to add to the invoice it would already be annoying, but what about 100 items, or 1000? we'll return to this example later on in the article. as in previous articles, let's learn about the real basics of arrays by entering some examples into browser developer console. creating arrays arrays consist of square brackets and elements that are separated by commas. suppo...
Test your skills: Arrays - Learn web development
you've understood our arrays article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). arrays 1 let's start off with some basic array practice. in this task we'd like you to create an array of three items, stored inside a variable called myarray. the items can be anything you want — h...
Test your skills: Math - Learn web development
ipt — numbers and operators article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). math 1 let's start out by testing your knowledge of basic math operators. you will have to create four numeric values, then add the first two together, then subtract the fourth from the third, then mu...
JavaScript First Steps - Learn web development
practical tutorial. here you'll build up a simple "guess the number" game, step by step. what went wrong? troubleshooting javascript when you built up the "guess the number" game in the previous article, you may have found that it didn't work. never fear — this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix
errors in javascript programs. storing the information you need — variables after reading the last couple of articles you should now know what javascript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. in this article we will get down to the real basics, looking at how to work with the most basic building blocks of...
Working with JSON - Learn web development
json is purely a data format — it contains only properties, no methods. json requires double quotes to be used around strings and property names. single quotes are not valid. even a single misplaced comma or colon can cause a json file to go wrong, and not work. you should be careful to validate any data you are attempting to use (although computer-generated json is less likely to include
errors, as long as the generator program is working correctly). you can validate json using an application like jsonlint. json can actually take the form of any data type that is valid for inclusion inside json, not just arrays or objects. so for example, a single string or number would be a valid json object. unlike in javascript code in which object properties may be unquoted, in json only quoted s...
Test your skills: JSON - Learn web development
this aim of this skill test is to assess whether you've understood our working with json article. note: you can try out the solution in the interactive editor below. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the example below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). json 1 the one and only task in this article concerns accessing json data and using it in your page. json data about some mother cats and their kittens is available in sample.json. the json is loaded into the page as a text string and made available in the catstring para...
Test your skills: Object-oriented JavaScript - Learn web development
nd inheritance in javascript articles. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). oojs 1 in this task we provide you with a constructor. we want you to: add a new method to the shape class's prototype, calcperimeter(), which calculates its perimeter (the length of the shape's ou...
Test your skills: Object basics - Learn web development
our javascript object basics article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an
error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). object basics 1 in this task you are provided with an object literal, and your tasks are to store the value of the name property inside the catname variable, using bracket notation. run the greeti...
Aprender y obtener ayuda - Learn web development
ords as modifiers, for example "<video> element autoplay attribute", or "date.settime parameters". if you want to search for something that has less obvious buzzwords, you need to think about what is most likely to return what you want. run code after several promises are fulfilled play a video stream from a webcam in the browser create a linear gradient in the background of your element
error messages if you are having a problem with some code and a specific
error message is coming up, it is often a good idea to just copy the
error message into your search engine and use it as the search term. if other people have had the same problem, there'll likely be some articles or blog posts about it in places like mdn or stack overflow. note: stack overflow is a really useful website — it...
Properly configuring server MIME types - Learn web development
specification, of knowing that the author actually intended the content to be processed and displayed in a way different from that implied by the reported mime type. some other web browsers, such as microsoft® internet explorer, try to allow for misconfigured web servers and applications by guessing what the correct mime type should be. this has sheltered many web administrators from their own
errors, since internet explorer will continue to process content as expected even though the web server is misconfigured, e.g. displays an image which is reported to be plain text. serving content using the correct mime type can also be important for security reasons; it's possible for malicious content to affect the user's computer by pretending to be a safe type of document when it is in fact not. ...
Introduction to the server side - Learn web development
he same hard-coded content from the server whenever a particular resource is requested). when a user wants to navigate to a page, the browser sends an http "get" request specifying its url. the server retrieves the requested document from its file system and returns an http response containing the document and a success status (usually 200 ok). if the file cannot be retrieved for some reason, an
error status is returned (see client
error responses and server
error responses). dynamic sites a dynamic website is one where some of the response content is generated dynamically, only when needed. on a dynamic website html pages are normally created by inserting data from a database into placeholders in html templates (this is a much more efficient way of storing large amounts of content than us...
Website security - Learn web development
l injection vulnerabilities enable malicious users to execute arbitrary sql code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. a successful injection attack might spoof identities, create new identities with administration rights, access all data on the server, or destroy/modify the data to make it unusable. sql injection types include
error-based sql injection, sql injection based on boolean
errors, and time-based sql injection. this vulnerability is present if user input that is passed to an underlying sql statement can change the meaning of the statement. for example, the following code is intended to list all users with a particular name (username) that has been supplied from an html form: statement = "select * from users wher...
Ember interactivity: Events, classes and state - Learn web development
pening export... line: @service('todo-data') todos; now the placeholder alert(text); line can be replaced with a call to our new add() function. replace it with the following: this.todos.add(text); if we try this out in the todo app in our browser (npm start, go to localhost:4200), it will look like nothing happens after hitting the enter key (although the fact that the app builds without any
errors is a good sign). using the ember inspector however, we can see that our todo was added: displaying our todos now that we know that we can create todos, there needs to be a way to swap out our static "buy movie tickets" todos with the todos we're actually creating. in the todolist component, we'll want to get the todos out of the service, and render a todo component for each todo. in order t...
Routing in Ember - Learn web development
rooturl = config.rooturl; } router.map(function() { this.route('completed'); this.route('active'); }); the highlighted lines were added when the 2nd and 3rd commands above were run. router.js behaves as a "sitemap" for developers to be able to quickly see how the entire app is structured. it also tells ember how to interact with your route, such as when loading arbitrary data, handling
errors while loading that data, or interpreting dynamic segments of the url. since our data is static, we won't get to any of those fancy features, but we'll still make sure that the route provides the minimally required data to view a page. creating the "index" route did not add a route definition line to router.js, because like with url navigation and javascript module loading, "index" is a special ...
Introduction to client-side frameworks - Learn web development
takes away all of the cognitive load of having to solve these problems yourself. tooling because each of the frameworks in this module have a large, active community, each framework's ecosystem provides tooling that improves the developer experience. these tools make it easy to add things like testing (to ensure that your application behaves as it should) or linting (to ensure that your code is
error-free and stylistically consistent). note: if you want to find out more details about web tooling concepts, have a read of our client-side tooling overview. compartmentalization most major frameworks encourage developers to abstract the different parts of their user interfaces into components — maintainable, reusable chunks of code that can communicate with one another. all the code related...
Framework main features - Learn web development
might not give you the result you'd expect. what if we wanted to only allow numbers to be passed into this function? typescript makes that possible: function add(a: number, b: number) { return a + b; } the : number written after each parameter here tells typescript that both a and b must be numbers. if we were to use this function and pass '2' into it as an argument, typescript would raise an
error during compilation, and we would be forced to fix our mistake. we could write our own javascript that raises these
errors for us, but it would make our source code significantly more verbose. it probably makes more sense to let typescript handle such checks for us. writing components as mentioned in the previous chapter, most frameworks have some kind of component model. react components can be...
Componentizing our React app - Learn web development
edit <span classname="visually-hidden">eat</span> </button> <button type="button" classname="btn btn__danger"> delete <span classname="visually-hidden">eat</span> </button> </div> </li> ); } note: components must always return something. if at any point in the future you try to render a component that does not return anything, react will display an
error in your 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-lar...
React resources - Learn web development
o limit the amount of irrelevant code that's sent to your user. you'll likely have app-wide styles and specific component styles that built on top of those. you can read more about component stylesheets in the create-react-app docs. react devtools we used console.log() to check on the state and props of our application in this tutorial, and you'll also have seen some of the useful warnings and
error message that react gives you both in the cli and your browser's javascript console. but there's more we can do here. the react devtools utility allows you to inspect the internals of your react application directly in the browser. it adds a new panel to your browser's developer tools, and with it you can inspect the state and props of various components, and even edit state and props to make im...
Componentizing our Svelte app - Learn web development
ed information as a parameter, and the handler will modify the parent's state. in our case, the filterbutton component will receive an onclick handler from its parent. whenever the user clicks on any filter button, the child will call the onclick handler, passing the selected filter as a parameter, back up to its parent. we will just declare the onclick prop assigning a dummy handler to prevent
errors, like this: export let onclick = (clicked) => {} and we'll declare the following reactive statement — $: onclick(filter) — to call the onclick handler whenever the filter variable is updated. the <script> section of our filterbutton component should end up looking like this — update it now: <script> export let filter = 'all' export let onclick = (clicked) => {} $: onclick(...
Dynamic behavior in Svelte: working with variables and props - Learn web development
ice. update your addtodo() function like so: function addtodo() { todos = [...todos, { id: 999, name: newtodoname, completed: false }] newtodoname = '' } giving each todo a unique id if you try to add new todos in your app now, you'll be able to add a new todo and have it appear in the ui! once. if you try it a second time, it won't work, and you'll get a console message saying "
error: cannot have duplicate keys in a keyed each". we need unique ids for our todos! let's declare a newtodoid variable calculated from the number of todos plus 1, and make it reactive. add the following snippet to the <script> section: let newtodoid $: { if (totaltodos === 0) { newtodoid = 1; } else { newtodoid = math.max(...todos.map(t => t.id)) + 1; } } no...
Creating our first Vue component - Learn web development
="true"></to-do-item> </li> </ul> </div> </template> try changing true to false and back again, reloading your app in between to see how the state changes. giving todos a unique id great! we now have a working checkbox where we can set the state programmatically. however, we can currently only add one todolist component to the page because the id is hardcoded. this would result in
errors with assistive technology since the id is needed to correctly map labels to their checkboxes. to fix this, we can programmatically set the id in the component data. we can use the lodash package's uniqueid() method to help keep the index unique. this package exports a function that takes in a string and appends a unique integer to the end of the prefix. this will be sufficient for keeping compo...
Focus management with Vue refs - Learn web development
hods: itemedited(newitemname) { this.$emit("item-edited", newitemname); this.isediting = false; this.focusoneditbutton(); }, editcancelled() { this.isediting = false; this.focusoneditbutton(); }, try editing and then saving/cancelling a to-do item via your keyboard. you'll notice that focus isn’t being set, so we still have a problem to solve. if you open your console, you'll see an
error raised along the lines of "can't access property "focus", editbuttonref is undefined". this seems weird. your button ref was defined when you activated the "edit" button, but now it’s not. what is going on? well, remember that when we change isediting to true, we no longer render the section of the component featuring the "edit" button. this means there's no element to bind the ref to, so it b...
Rendering a list of Vue components - Learn web development
us to manage since we already need to create a unique id for each todo item anyway. add a new prop to your todoitem component — id. make it required, and make its type a string. to prevent name collisions, remove the id field from your data attribute. you are no longer using uniqueid, so you need to remove the import uniqueid from 'lodash.uniqueid'; line, otherwise your app will throw an
error. the <script> contents in your todoitem component should now look something like this: export default { props: { label: {required: true, type: string}, done: {default: false, type: boolean}, id: {required: true, type: string} }, data() { return { isdone : this.done, } }, } now, over in your app.vue component, pass item.id as a...
Cross browser testing - Learn web development
ommon problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues. implementing feature detection feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/
erroring in some browsers. this article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports. introduction to automated testing manually running tests on several browsers and devices, several times per day, can get tedious and time-consuming. to handle this efficiently, you should become fa...
Git and GitHub - Learn web development
e to back up the code in a central place, so it is not lost if your computer breaks. you will also want to be able to roll back to earlier versions if a problem is later discovered. you might have started doing this in your own work by creating different versions of the same file, e.g. mycode.js, mycode_v2.js, mycode_v3.js, mycode_final.js, mycode_really_really_final.js, etc., but this is really
error-prone and unreliable. different team members will commonly want to create their own separate versions of the code (called branches in git), work on a new feature in that version, and then get it merged in a controlled manner (in github we use pull requests) with the master version when they are done with it. vcses provide tools to meet the above needs. git is an example of a vcs, and github is...
Deploying our app - Learn web development
reat tutorials and books available, and our git and github page is a good place to start. we initialized our working directory as a git working directory earlier on. a quick way to verify this is to run the following command: git status you should get a status report of what files are being tracked, what files are staged, and so on — all terms that are part of the git grammar. if you get the
error fatal: not a git repository returned, then the working directory is not a git working directory and you’ll need to initialise git using git init. now we have three tasks ahead of us: add any changes we’ve made to the stage (a special name for the place that git will commit files from). commit the changes to the repository. push the changes to github. to add changes, run the follo...
Chrome Worker Modules
e("resource://gre/modules/mymodule.js") foo(module.key); // module.key == "this is public"; // however, secretkey is not exported 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); } ...
Accessibility information for UI designers and developers
ak the interface. forms in forms, provide labels for all controls. this includes form elements like inputs and select boxes, but also buttons. for form elements, it should be clear what kind of input is expected. placeholders are best avoided for this, as they are often too low in contrast. it is more helpful to describe what an input element is for in text just above or underneath the input.
error recovery when you detect users provide unexpected input, explain what is wrong and, if possible, how to correct it. this is specifically important in these cases: the user input is about legal commitments or financial transactions it updates or removes the user's data in a system when recording tests responses in those cases, ensure users can change submissions, automatically check for er...
Multiprocess on Windows
given the generic accessible myaccessible, we first obtain the native (i.e. com) interface for that accessible, and store it in acctowrap. we use stauniqueptr, because mainthreadhandoff::wrapinterface requires one in its input. integrating interceptors into the a11y tree now that we have solved the apartment proble...
Accessible Toolkit Checklist
g the basic msaa states on every item: unavailable, focused, readonly, offscreen, focusable to avoid extra work, utilize implementing an msaa server mnemonics ability to define in xml for any widget with a text label (via attribute or a preceding char in label) automatically define mnemonics for all standard common dialogs (like yes/no confirmations and retry/exit
error dialogs) support mnemonics in dialogs created via method calls layout engine - drawing underline under correct letter events - making keystrokes do the right thing msaa support, via iaccessible's get_acckeyboardshortcut support for ms windows settings when high contrast checkbox is set (in accessibility control panel, spi_gethighcontrast), or when user...
Adding a new event
ace in dom/interfaces/events/. however, in these days, this is not necessary. if all information of the event is stored by its internal event, c++ event handlers can access them with following code: ns_imethodimp aneventlistener::handleevent(nsidomevent* aevent) { internalfooevent* internalevent = aevent->getinternalnsevent()->asfooevent(); if (ns_warn_if(!internalevent)) { return ns_
error_unexpected; } dosomethingwith(internalevent->mbar); aevent->preventdefault(); return ns_ok; } implement dom event class generate dom event implementation if it's possible if you're creating simple dom event class, it might be generated automatically. if it's possible, you just need to add an entry to generated_events_webidl_files in dom/webidl/moz.build. define and create dom event c...
Adding a new CSS property
that any successful parse sets all of the subproperties of the shorthand (since that's the way shorthands work in css). some common mistakes to watch out for when writing custom parsing code (which might go away if we redesign the parser along the lines described in css3-syntax): make sure to call skipuntil() to look for the matching close parentheses, braces, or brackets whenever you hit an
error inside of them. make sure to call ungettoken() if you have called gettoken() but the result is unexpected. this is particularly important in case the unexpected token is a parenthesis or something else that requires matching the other half of a pair. if you're adding a preference-controlled property to a non-preference-controlled shorthand, you need to call appendvalue for that property if and...
Adding phishing protection data providers
rovider.idnum.updateurl an url used to request an updated list of phishing sites. the server either provides a full list or incremental updates in order to bring the client's tables up to date. browser.safebrowsing.provider.idnum.reportgenericurl not currently used; intended for use in reporting other issues with the phishing protection service. browser.safebrowsing.provider.idnum.report
errorurl an url to which the user is directed in order to report a safe page that is incorrectly being reported as a phishing site. browser.safebrowsing.provider.idnum.reportphishurl an url to which the user is directed in order to report a phishing site that isn't detected by the phishing protection system. determining the currently-selected data provider if you need to determine the id numbe...
Building SpiderMonkey with UBSan
idermonkey 4. when you hit a bug and want a stack trace, run under gdb with a breakpoint at the end of __ubsan::diag::~diag(). the stack trace should show a function such as __ubsan_handle_load_invalid_value or __ubsan_handle_type_mismatch being called by the buggy c++ code. (for automated testing outside of gdb, you can instead build with -fsanitize=undefined-trap -fsanitize-undefined-trap-on-
error, but then you lose ubsan's diagnostics and the ability to continue past
errors.) known bugs. please file new bugs with e.g. [-fsanitize=float-cast-overflow] in the status whiteboard. ...
Debugging on Mac OS X
o add the argument "-no-remote". also in the "arguments" panel, you may want to add an environment variable moz_debug_child_process set to the value 1 to help with debugging e10s. select "build" from the left of the scheme editor window, and check that there is nothing listed under targets (otherwise it may cause problems when you try to run the executable for debugging since you will get build
errors). click "close" to close the scheme editor. at this point you can run the application from xcode, and when you pause or hit breakpoints it should show open the correct source file at the correct line. setting up lldb lldb is the debugger xcode provides/uses. one important issue that the mozilla .lldbinit file fixes is that by default some breakpoints will be listed as "pending", and xcode...
Debugging
ion. debugging a hang on os x collecting "samples" to attach to a bug. remote debugging core dumps and examples of remote debugging. useful if a developer can't reproduce your crash. http logging how to log http network traffic for debugging purposes. debugging tools tools assorted tools that will help you debug your code or web site. ns
error lookup useful for when your code gets a complicated numeric
error code and you can't figure out what it means. download a debug build recent automatically compiled debug builds are available. note that these are replaced frequently by our tinderboxes. the debug builds have "-debug" at the end of their file names. related topics performance and profiling tr...
Simple SeaMonkey build
y using the commands below. for complete information, see the build documentation. build prerequisites hardware requirements: the seamonkey build process is both i/o- and cpu-intensive, and can take a long time to build even on modern hardware. minimum and recommended hardware requirements for mozilla development are: recommended: 8gb of ram (having only 4gb ram and 4gb swap may give memory
errors during compile) 35 gb free disk space. this will accomodate visual studio 2013 community edition, the required sdks, the mozillabuild package, the mercurial source repository and enough free disk space to compile. a fast ssd is recommended; the firefox build process is i/o-intensive. high speed internet installing build tools if your system is not listed below, see the build prerequisites p...
Simple Sunbird build
instead it is suggested to build thunderbird with lightning. please refer to the simple thunderbird build guide. you can build a bleeding-edge, development version of sunbird using the commands below. for complete information, see the build documentation. installing build tools if your system is not listed below, see the build prerequisites page. ...
Updating NSPR or NSS in mozilla-central
update the minimum required system nss version in old-configure.in. this is for builds with --with-system-nss. for example, in the following, "3.16.1" would be replaced with the new nss version. moz_arg_with_bool(system-nss, [ --with-system-nss use system installed nss], _use_system_nss=1 ) if test -n "$_use_system_nss"; then am_path_nss(3.16.1, [moz_native_nss=1], [ac_msg_
error([you don't have nss installed or your version is too old])]) fi commit the update: $ hg commit -a in order to eliminate any problems related to how nss and nspr are built differently in firefox than they are standalone, you should push your commit to try first. if your update fails linking because of missing nss or nspr symbols, add the missing symbols to config/external/nss/nspr-dummy.
Windows SDK versions
s 7 jump lists you can download the sdk (v7.0 [web setup or iso image] or unsupported v7.1 [web setup or iso image]) from the microsoft download center. note that if you're running a 64 bit version of windows you may require the "amd" version of the sdk even if you have an intel processor, and you may need to deselect the documentation component in the installer in order to avoid an installation
error. (this was certainly the case for 64 bit windows 7 on a late 2008 macbook pro.) warning: due to a bug in windows 7 sdk, if you get "sdksetup encountered an
error: expecting path %systemroot% to represent a valid system volume"
error you may require to set environmental variable %windir% to something like "c:\windows" instead of "%systemroot%". older sdks these are no longer supported, further i...
The Firefox codebase: CSS Guidelines
of the value and it is usually good practice to do so. in general, it's good to first think of how some css could be written cleanly without the css variable(s) and then think of how the css variable could improve that css. using variables use the variable according to its naming do this: xul|tab:hover { background-color: var(--in-content-box-background-hover); } not this: #certificate
errordebuginformation { background-color: var(--in-content-box-background-hover); } localization text direction for margins, padding and borders, use inline-start/inline-end rather than left/right. example: use margin-inline-start: 3px; instead of margin-left: 3px. for rtl-aware positioning (left/right), use inset-inline-start/inset-inline-end. for rtl-aware float layouts, float: inline-sta...
Creating Custom Events That Can Pass Data
you can find the prototypes for the function in nsiprivatedomevent. your event in order for your event to work you must do the following: create a scriptable interface called nsidom{youreventname} inheriting from nsidomevent. a good place to...
Eclipse CDT Manual Setup
ress tab), sanity check that everything went as it should have by right-clicking the project in the project explorer tab and selecting "index > search for unresolved includes". if you get many more than 2000 unresolved includes (as of may 2012), then things have gone pretty wrong. you should be able to use the list of unresolved includes to help figure out what the problem is (see also the parser
errors section for more troubleshooting tips). assuming everything went as expected, you should now find that eclipse's code assistance works a whole lot better. :-) to test out the code assistance, see the code assistance subsection of the usage tips section below. to improve code assistance even more, see the headers are only parsed once subsection of the known issues section. ...
Obsolete Build Caveats and Tips
st it. starting with gecko 12.0, this sdk is necessary. note: while this configuration will probably build on mozilla-1.9.1 and mozilla-1.9.0, it is not supported. warning: due to a bug in old versions of mozillabuild (prior to 1.6), if you download version 7.1 of the windows 7 sdk (which is the current version available), your build will fail, often while building cairo with "ocidl.h"
errors. in order to fix this issue, you need to use the latest version of mozillabuild. windows vista sdk obsolete since gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9)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. this is the sdk that mozilla-1.9.1 (firefox 3.5) builds used...
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 di...
Firefox and the "about" protocol
irector.cpp within the kredirmap array. the array maps most of the urls, like config to urls in the chrome: pseudo protocol, such as chrome://global/content/config.xul. the about location information is duplicated in docshell/build/nsdocshellmodule.cpp. note: you must access about: protocol pages by typing them into the address bar. attempts to navigate through window.location will throw —
error: access to 'about:addons' from script denied. ...
Using the Browser API
prev.disabled = true; next.disabled = true; searchbar.value = ''; } } }); note that whenever one of the search-related methods is invoked, a mozbrowserfindchange event is fired to allow you to react to search changes in a more precise way if desired: //browser.addeventlistener('mozbrowserfindchange', function(e) { // can react to find changes if required //}) reporting
errors we've got one more piece of code to mention from our source: browser.addeventlistener('mozbrowser
error', function (e) { console.log("loading
error: " + e.detail); }); this simple listener logs an
error message to the console when an
error with the browser iframe is encountered. note that this doesn't include simple
errors due to incorrect urls being entered. see the mozbrowser
error page for...
HTMLIFrameElement.executeScript()
f the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax var mydomrequest = instanceofhtmliframeelement.executescript(script, options); return value a domrequest object that returns an onsuccess handler if the script is successfully executed against the loaded content, or an on
error handler if not. parameters script the script to be executed. options optional optionally, you can provide an origin or url for the script to be executed against. it's recommended that you include an origin or url, in order to ensure that the script is being executed in the expected context: origin: an origin, e.g. http://example.com url: a url, e.g. http://example.com/index.html ...
HTMLIFrameElement.getMuted()
owser <iframe> is currently muted. syntax there are two versions of this method, a callback version: var request = instanceofhtmliframeelement.getmuted(); and a promise version: instanceofhtmliframeelement.getmuted().then(function(muted) { ... }); returns callback version: a domrequest that represents the get muted request. it has an onsuccess handler to handle the success case, and an on
error handler to handle the failure case. the muted value is available in the request.result property, and is a boolean value — true means muted, and false means unmuted. promise version: a promise that resolves with the muted value — a boolean where true means muted, and false means unmuted. parameters none. example callback version: var browser = document.queryselector('iframe'); var requ...
HTMLIFrameElement.getScreenshot()
(this delay is defined by the gecko dom.browserelement.maxscreenshotdelayms preference). syntax var instanceofdomrequest = instanceofhtmliframeelement.getscreenshot(maxwidth, maxheight, mimetype); returns a domrequest for handling the screenshot request. its request.onsuccess handler handles the success case (the screenshot is contained in request.result as a blob object), and its request.on
error handler handles the failure case. parameters maxwidth a number representing the maximum width of the screenshot in device pixels. maxheight a number representing the maximum height of the screenshot in device pixels. mimetype optional a mime type specifying the format of the image to be returned; if not specified, the default used is image/jpeg. use image/png to capture the alpha channel...
HTMLIFrameElement.getStructuredData()
uture. the getstructureddata() method of the htmliframeelement interface retrieves any structured microdata (and hcard and hcalendar microformat data) contained in the html loaded in the browser <iframe> and returns it as json. syntax var instanceofdomrequest = instanceofhtmliframeelement.getstructureddata(); returns a domrequest to handle the getstructureddata() request's success and
error cases. if the request is successful, the request.result is a json object representation of all microdata contained on the page loaded in the browser. parameters none. examples var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getstructureddata(); request.onsuccess = function() { console.log(request.result); ...
Overview of Mozilla embedding APIs
ch support both unicode and ascii strings. these classes provide a variety of string operations as well as dealing with the memory management issues of storing the underlying data. see the string guide for more details. nsweakptr this is an nscomptr which encapsulates xpcom weak reference support. see the nsiweakreference document for more information. public return codes ns_succeeded ns_
error_failure ns_
error_not_implemented public functions the following functions are available from the xpcom dll. ns_initembedding this function initializes the gecko embedding support. this must be the first function call made into gecko. ns_termembedding this function shuts down gecko and cleans up any remaining resources... currently, once gecko has been shutdown, it cannot be restarted i...
Embedding Tips
_contractid)); if (wwatch) { wwatch->setwindowcreator(mywindowcreator); } i need the javascript inside the browser window to talk to my embedding client. how do i do it? at startup use the category manager to register properties of the global object in javascript like this: nscomptr<nsicategorymanager> catman = do_getservice(ns_categorymanager_contractid); if (!catman) return ns_
error_failure; nsxpidlcstring previous; catman->addcategoryentry(javascript_global_property_category, "my_prop_name", "my_prop_contract_id", pr_true, pr_true, getter_copies(previous)); this will cause a component with the contract id my_prop_contract_id to be lazily created when the my_prop_name is resolved in any javascript window scope. if you...
Gecko SDK
y released for other platforms; if you need it, you will probably need to build it yourself. note: you can subscribe to a calendar of the firefox release schedule. also, you can view the schedule on the web. unpack the sdk tarball to some suitable location. issues with the os x sdk if you need to use the xpidl utility to compile idl files on os x, it's likely that you will receive a strange
error when running the tool that looks something along the lines of this: dyld: library not loaded: /opt/local/lib/libintl.3.dylib referenced from: /users/varmaa/xulrunner-sdk/bin/./xpidl reason: image not found trace/bpt trap unfortunately, this is caused by a problem with the sdk build process which cannot currently be resolved (see bugzilla bug #430274). to get around it, you'll need to first...
How to get a stacktrace with WinDbg
opening the debug menu and clicking go. while firefox is running, you will not be able to type any commands into the debugger. after it starts, try to reproduce the crash or hanging issue that you are seeing. if firefox fails to start, and you see lines of text followed by a command prompt in the debugger, a "breakpoint" may have been triggered. if you are prompted for a command but don't see an
error about a crash, go back to the debug menu and press go. once the browser crashes, you will see an
error (such as "access violation") in the windbg command window. if firefox hangs and there is no command prompt available in the debugger, open the debug menu and choose break. once the browser has crashed or been stopped, continue with the steps below. after the crash or hang you need to capture ...
How to investigate Disconnect failures
ata\roaming\mozilla\firefox\crash reports ubuntu: [user/home]/.mozilla/firefox/crash reports and there we can check by timestamp if firefox crashed when we had the disconnect. check the event viewer to check if an os event interfered with the test run. the event viewer can be found on windows: computer management > event viewer > windows logs > application and here we look for
errors that overlapped with the test run; we cannot see the freezes (the main thread is blocked). crashes (not freezes) if we have a crash we always should submit it. under about:crashes we have links to all the crashes submitted by firefox to crash-stats. from there use “signature” as summary for bugzilla bug. in “extensions” check installed addons and check if they might be responsib...
How to Report a Hung Firefox
s intended for developers and technically-knowledgeable users. if that's not you, or you just want to fix a firefox hang without reporting it, see firefox hangs or is not responding - how to fix. is your firefox not responding? or are you regularly seeing the "firefox is running but is not responding..." dialog? this usually means that something in firefox is hung. this may be because of a code
error within firefox itself, such as a deadlock or infinite loop, or it may be caused by 3rd-party software such as a firefox extension, antivirus software, or even malware or a virus on your computer. what information to include in a bug report as usual, following bug writing guidelines will make your report much more likely to lead to a fix in firefox. check the cpu usage of the firefox process(...
Creating a New Protocol
rotocol for plugins is ppluginmodule. the toplevel protocol for tabs is pcontent. you should know what protocol will manage the new protocol and what lifetime issues that creates. if there is any doubt, ask on irc in the #content channel. building the new protocol to build the new protocol declaration and generate headers, make in ipc/ipdl: make -c objdir/ipc/ipdl if there are any protocol-level
errors, the ipdl compiler will print the relevant
error messages and stop. to view the generated headers, look in objdir/ipc/ipdl/_ipdlheaders . creating the implementation the c++ implementation inherits from the abstract ipdl-generated classes pnewprotocolparent and pnewprotocolchild. it must implement abstract methods for receiving the appropriate messages on each side. the method signatures can be ...
AddonInstall
the name of the add-on being installed. version string the version of the add-on being installed. iconurl string the icon of the add-on being installed. releasenotesuri nsiuri the uri of release notes for this install. type string the type of the add-on being installed. state integer the state of the installation.
error integer if an
error has been encountered during the download or install this will hold the
error code. sourceuri nsiuri the uri that the add-on is being installed from. file nsifile the file that the add-on is being installed from. this may be null if the add-on is coming from the internet and has yet to be downloaded. progress integer the progre...
AddonUpdateChecker
ing version, in boolean ignorecompatibility, in string appversion, in string platformversion) updateinfo getnewestcompatibleupdate(in updateinfo updates[], in string appversion, in string platformversion) void checkforupdates(in string id, in string type, in string updatekey, string url, in updatechecklistener listener) constants constant description
error_timeout the update check timed out.
error_download_
error there was an
error while downloading the update information.
error_parse_
error the update information was malformed in some way.
error_unknown_format the update information was not in any known format.
error_security_
error the update information was not signed by the update key used for ret...
InstallListener
void ondownloadended( in addoninstall install ) parameters install the addoninstall representing the install ondownloadcancelled() called when downloading is cancelled. only called for add-ons that need to be downloaded. void ondownloadcancelled( in addoninstall install ) parameters install the addoninstall representing the install ondownloadfailed() called if there is some
error downloading the add-on. only called for add-ons that need to be downloaded. void ondownloadfailed( in addoninstall install ) parameters install the addoninstall representing the install oninstallstarted() called when installation of an add-on begins. a listener may return false to cancel the install. void oninstallstarted( in addoninstall install ) parameters install the addoni...
UpdateCheckListener
updatechecklisteners are passed the results of update checks performed by the addonupdatechecker. method overview void onupdatecheckcomplete(in updateinfo results[]) void onupdatecheck
error(in integer status) methods onupdatecheckcomplete() called when the update check completed successfully. void onupdatecheckcomplete( in updateinfo results[] ) parameters results an array of updateinfo objects representing the available add-on versions onupdatecheck
error() called when the update check fails. void onupdatecheck
error( in integer status ) parameters status a value representing the type of failure; see the range of possible values. ...
Http.jsm
postdata this can be: a string: send it as is an array of parameters: encode as form values null/undefined: no post data. method get, post or put (this is automatically set if postdata exists). onload a function handle to call when the load is complete, it takes two parameters: the responsetext and the xhr object. on
error a function handle to call when an
error occurs, it takes three parameters: the
error, the responsetext and the xhr object. logger an object that implements the debug and log methods (e.g. log.jsm). headers or post data are given as an array of arrays, for each inner array the first value is the key and the second is the value. for example: [["key1", "value1"], ["key2", "val...
JavaScript OS
the javascript os module contains tools that allow chrome content (i.e. platform and add-ons) to interact with the host operating system. at the time of this writing, some of the features of this module are available only to chrome workers. os.constants os-related constants, including
errors, file opening modes, system configuration, etc. os.file access to the native file system. os.shared utilities for defining functions that interact with the operating system. ...
OS.File.Info
promise = os.file.stat(somepath); promise.then( function onsuccess(info) { // |info| is an instance of |os.file.info| if (info.isdir) { // |somepath| represents a directory } else if (info.issymlink) { // |somepath| represents a symbolic link } else { // |somepath| represents a regular file } }, function onfailure(reason) { if (reason instanceof os.file.
error && reason.becausenosuchfile) { // |somepath| does not represent anything } else { // some other
error } } ) example: determining the owner of a file let promise = os.file.stat() promise.then( function onsuccess(info) { if ("unixowner" in info) { // info.unixowner holds the owner of the file } else { // information is not available on this platform ...
Deferred
mise has already been 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. ...
Services.jsm
ppinfo nsixulruntime application information service appshell nsiappshellservice application shell service blocklist nsiblocklistservice blocklist service cache nsicacheservice cache service cache2 nsicachestorageservice cache storage service clipboard nsiclipboard clipboard console nsiconsoleservice
error console service contentprefs nsicontentprefservice content preferences service cookies nsicookiemanager2 cookie manager 2 service cpmm nsimessagesender child process message manager4 crashmanager crashmanager.jsm dirsvc nsidirectoryservice nsiproperties directory service domstoragemanager nsidomstorageman...
WebRequest.jsm
name string header name, for example "content-type" value string header value, for example "image/png" chrome incompatibilities although this api is modeled on chrome's webrequest extension api, there are some differences. we're working on addressing them, though. filtering by windowid and tabid is not supported. the onauthrequired, onbeforeredirect, and on
erroroccurred events are not supported. the "requestbody" instruction in opt_extrainfospec is not supported. redirection is not allowed in onbeforerequest or onheadersreceived, but is allowed in onbeforesendheaders. see bug 1176092. handlerbehaviorchanged() is not supported. requestid is not included in the argument passed to the listener. examples basic examples this example just logs the url ...
JavaScript code modules
velopers can use in their code. standard code modules addonmanager.jsm an interface to install, manage, and uninstall add-ons. addonrepository.jsm provides a search of add-ons in the repository. assert.jsm implements the commonjs unit testing specification version 1.1, which provides a basic standardized interface for performing in-code logical assertions with optional, customizable
error reporting. bookmarkhtmlutils.jsm provides utility functions for importing and exporting bookmarks from the old-school "bookmarks.html" style bookmark files. ctypes.jsm provides an interface that allows javascript code to call native libraries without requiring the development of an xpcom component. customizableui.jsm allows you to interact with customizable buttons and items in firefox's ma...
Application Translation with Mercurial
uide achieves this with the firefox extension scrapbook. you installed scrapbook earlier, now open it in firefox either by calling it from the firefox menu bar (press the alt key to show it if necessary) using "view" > "sidebar" > "scrapbook" or by clicking its toolbar button which you likely have to add by toolbar customization if you didn't do this before. drag the tab with the localization
error showing missing and obsolete strings to the sidebar. after scrapbook has saved the web page to your local disk, click with the right mouse button on the page in the sidebar and choose "properties" from the context menu which gets opened. rename it something meaningful, e.g. "firefox <version number> translation". after you saved the dialog, click with the left mouse button on the page in the si...
Localizing XLIFF files for iOS
bookmarks"> <source>add to bookmarks</source> <target>agregar a marcadores</target> <note>no comment provided by engineer.</note> </trans-unit> save your translations along the way. once you've completed translation, it's important to make sure the xml in your xliff file is valid (e.g., no broken tag sets). open the file in firefox to have it run a validity check and correct any
errors it might yell about. commiting your xliff file using this command, commit your translated xliff file into your locale's directory: git commit -m "commit message here" . push your commit into the github repo: git push kick up your feet, pop open a cold beer (or soda), and pat yourself on the back for doing something new, different, and exciting! ...
Localizing with Koala
ou have translated 3 strings in the following 2 files: searchbar.dtd: cmd_enginemanager.label searchendcap.label search.properties: cmd_addfoundengine it's time to put these files under mercurial's version control system. this will allow you to track changes, export them to remote repositories (first on bitbucket, later on hg.mozilla.org) and revert files to earlier versions in case of
errors. version control systems add a lot of transparency to your work and allow others to get involved easily, so it's best to commit often (e.g. after you finish translating every file, or even more frequently). koala supports mercurial and allows you to add and commit files automatically from komodo. for the purposes of this tutorial, we will switch to the command line every now and then to see what...
Localizing with Mozilla Translator
. all this means is that the strings have yet to be translated. you can save your work in progress and reopen it to continue working by selecting view fuzzy from the edit menu. after translating those strings (if using the edit phrase dialog, you can get translation suggestions for strings having an original text equal to existing translations), you can run some automated tests to detect typical
errors. after that, you export either the whole product or indvididual files. finally, you commit your changes outside of mt, using your favorite repository tools. recipes introduction we aim to put here some recipes that may be useful at a certain moment for mt users, but that, due to its temporary nature, don't fit in the user manual. migrating contents when the directory structure changes ...
SVN for Localizers
ur working directory and execute this command: svn revert * this is a really helpful command because it reverts all of your changes to your working directory's last updated state. this is a huge blessing if you have been updating frequently. it's a nightmare if you haven't because it throws away all of your recent hard work. keep this in mind because if you did a lot of work and you made some
errors in just one file, maybe it would be wiser to simply correct those
errors instead of reverting your working directory and losing all your work. note: sometimes you'll find references to commands in abbreviated form (svn ci = svn commit, svn up = svn update, svn co = svn checkout, etc.) commit doesn't work, what's wrong? make you sure you're checking out the repository with https:// make s...
Localization technical reviews
to release. here is some of the criteria we use to perform technical reviews: revision attachment contains only relevant files we run into exports that contain .xpi langpacks and other random files. make sure the top-level directory doesn't contain garbage. compare-locale we run the compare-locales tool on the new locale to get the statistics on translation of strings and report basic
errors. defines.inc the file for each app (like browser/defines.inc) contains the names of all contributors that a localization team would like to credit the work to. localizers can specify the team responsible for the work by listing the name just after the moz_langpack_creator. the team can also wrap contributors with <em:contributor> tags just after the moz_langpack_contributors section. make su...
Creating localizable web applications
ng it impossible for localizers to accidentally change them. you can learn more about the choice of the format for your project at file formats. text messages don't hardcode english content allow localizers to localize english content, such as: text messages, number formats, date formats, word order and sentence structure. note that some strings might be hidden in libraries' code (e.g.
error messages), or in javascript libraries and scripts. if you are using pure html instead of gettext to localize your webapp, consider using an additional gettext-like format such as .lang to streamline localizers' work with repeating content. this is useful for strings occurring in the webapp multiple times, like "return to top", "comments", "click to see larger image" etc. might be also helpful fo...
Mozilla MathML Status
ms implemented. general layout schemata element notes mrow implemented. mfrac implemented. msqrt implemented. mroot implemented. mstyle implemented. we are only interested in supporting attributes "inherited from the surrounding context", which are those effectively used in practice. see bug 838509. m
error implemented. mpadded implemented. mphantom implemented. mfenced implemented. menclose implemented. script and limit schemata element [- attribute] notes msub implemented. msup implemented. msubsup implemented. munder implemented. mover implemented. munderover ...
Various MathML Tests
: abcd un abcd ov abcd under over . testing mathml <msubsup>: a p q a b + c x . testing mathml <mrow>: d ( a b ) x 2 + 4 * x + p q = 0 , with this <mfrac> hanging here d * t ( i + j n ) + p y * q p x * b x + a + c d in the middle of a lot of running text to try to explain what this means to those who care to read. testing mathml <m
error>, <mtext>: this is a text in mtext this is a text in m
error testing <maction>: click to toggle between expressions, and watch the status line onmouseover/onmouseout: statusline#first expression first expression statusline#second expression second expression statusline#and so on... and so on.. click the expression below to see several definitions of pi: π = 3.14159...
MathML Demo: <mtable> - tables and matrices
ow doesn't have at least one cell with "rowalign=baseline" where to anchor the baseline (in which case mozilla will behave as if it was align="center#rownumber"). these may sound like gimmicks until you want to get a damping effect such as this ---... ab ab ab ab ab ab , or perhaps the reverse ---... ab ab ab ab ab ab , modulo pixel roundoff
errors. here 'a' and 'b' can be other combinations of possibly irregular boxes. and making floating elements do a multiplication such as the following one which is anchored at a baseline is made simple by using align="baseline1" on both tables [ a b c d ] [ a b c d ] to multiply a matrix a by a vector x, each row of the matrix has to be multiplied to the vector...
Mozilla Web Services Security Model
access web services. for example, to determine what web sites can access a web service at http://www.example.com/dir1/dir2/service, mozilla would load the file http://www.example.com/web-scripts-access.xml, which may choose to delegate the decision to http://www.example.com/dir1/dir2/web...pts-access.xml. web-scripts-access.xml file format the web-scripts-access.xml file is an xml document. any
errors in xml syntax, as well as many failures to follow the format, will cause the document to be ignored. the webscriptaccess element its root element must be a webscriptaccess element in the http://www.mozilla.org/2002/soap/security namespace. this element must have either one delegate element child or any number (0 or more) of allow element children. all of these children elements must be in the ...
GC and CC logs
appdata\temp\ on windows, and somewhere in /var/folders/ on mac (whatever the directory service returns for tmpd/ns_os_temp_dir). note that just moz_cc_log_directory=. won't work - you need to specify a full path. on firefox for android you can use the cc-dump extension to save the files to /sdcard. by default, the file is created in some temp directory, and the path to the file is printed to the
error console. to log every cycle collection, set the moz_cc_log_all environment variable. to log only shutdown collections, set moz_cc_log_shutdown. to make all ccs verbose, set moz_cc_all_traces to "all", or to "shutdown" to make only shutdown ccs verbose. live gc logging can be enabled with the pref javascript.options.mem.log. output to a file can be controlled with the moz_gctimer environment var...
Profiling with Xperf
o when the symbol path is edited. if you change it within the program, you'll have to close all summary tables and reopen them for it to pick up the new symbol path data. you'll have to agree to a eula for the microsoft symbols -- if you're not prompted for this, then something isn't configured right in your symbol path. (again, make sure that the directories exist; if they don't, it's a silent
error.) quick start all these tools will live, by default, in c:\program files\microsoft windows performance toolkit. either run these commands from there, or add the directory to your path. you will need to use an elevated command prompt to start or stop profiling. start recording data: xperf -on latency -stackwalk profile "latency" is a special provider name that turns on a few predefined kernel prov...
Profiling with the Firefox Profiler
en enter one or more thread names into the textbox beside it. thread names are the strings passed to the base::thread class at initialization. at present there is no central list of these thread names, but you can find them by grepping the source. examples: 1 2 if the filter you entered is invalid, no threads will be profiled. you can identify this by hitting analyze (cleopatra will show you an
error message). if the filter is left empty, only the main thread is captured (as if you had not enabled multi-thread.) profiler features the profiler supports several features. these are options to gather additional data in your profiles. each option will increase the performance overhead of profiling so it's important to activate only options that will provide useful information for your particular...
tools/power/rapl
n linux, rapl can be run as root, as follows. sudo $objdir/dist/bin/rapl alternatively, it can be run without root privileges by setting the contents of /proc/sys/kernel/perf_event_paranoid to 0. note that if you do change this file, its contents may reset when the machine is next rebooted. you must be running linux kernel version 3.14 or later for rapl to work. otherwise, it will fail with an
error message explaining this requirement. windows unfortunately, rapl does not work on windows, and porting it would be difficult because windows does not have apis that allow easy access to the relevant model-specific registers. output the following is 10 seconds of output from a default invocation of rapl. total w = _pkg_ (cores + _gpu_ + other) + _ram_ w #01 5.17 w = 1.78 ( 0.12 + 0.10 ...
turbostat
at is a linux command-line utility that prints various measurements, including numerous per-cpu measurements. this article provides an introduction to using it. note: the power profiling overview is worth reading at this point if you haven't already. it may make parts of this document easier to understand. ...
A brief guide to Mozilla preferences
ences loading and resolution on application launch, the application loads preferences in the following order: load all default pref files. optionally load the config file. load user pref files, first prefs.js, then user.js . preference conflicts are resolved in favor of the last entry; for example, user.js takes precedence over prefs.js . if the application encounters any
error during loading of a default pref file, the application will issue a warning that a configuration file has failed to load and then quit. this allows system administrators to know quickly if there is a configuration
error in the installation. if the application encounters an
error when loading user pref files, the application will issue a warning but will continue running. preferences saving us...
javascript.options.showInConsole
the preference javascript.options.showinconsole controls whether
errors or warnings in chrome code are shown in the
error console. type:boolean default value: false (true in debug builds) exists by default: yes application support:firefox 1.0 status: active introduction:2002-02-26 bugs: bug 125181 bug 337875 values false only
errors and warnings from content code are shown. true (default)
errors and warnings from both chrome and content are shown in the
error console. note: since the web console was introduced in firefox 4 specifically for debugging content, the default value for this preference has changed to true as of gecko 2.0. ...
javascript.options.strict
javascript warnings are generated when code is executed that doesn't cause a run-time
error, but is non-standard, poorly written, or prone to cause logic
errors. this preference controls whether javascript warnings are logged to the javascript console. example : <html> <head> <title>sample</title> </head> <body> <label id="name">enter you first name</label> <p id ="sample"></p> <script> "use strict" name1= "john" ; // this will cause and an
error as variable not declared . var name2= "peter"; document.getelementbyid("sample").innerhtml = name1; </script> </body> </html> possible values and their effects: true: show javascript
errors and warnings. false: show javascript
errors only. (default) see also: http://kb.mozillazine.org/javascript.options.strict ...
Preference reference
oardevents.enableddom.event.clipboardevents.enabled lets websites get notifications if the user copies, pastes, or cuts something from a web page, and it lets them know which part of the page had been selected. the emitting of the oncopy, oncut and onpaste events are controlled by this preference. javascript.options.showinconsolethe preference javascript.options.showinconsole controls whether
errors or warnings in chrome code are shown in the
error console.javascript.options.stricttechnical review completed.mail.tabs.drawintitlebarstarting in thunderbird 17.0, the tabs are drawn in the title bar. the old behavior can be restored by setting the preference mail.tabs.drawintitlebar to false.nglayout.debug.disable xul fastloadthe preference nglayout.debug.disable_xul_fastload controls whether o...
Profile Manager
automatically add the -no-remote argument for you, regardless of whether this launch option was checked. locked profiles some profiles may be shown as locked in the main window. such profiles are currently being used by an instance of firefox. if you attempt to perform any operation on a locked profile, you'll get a warning; if you choose to continue despite the warning, you may encounter
errors or corrupt a profile. it's strongly recommended to avoid operations on locked profiles. if you need to do something with a locked profile, close the instance of firefox which is using the profile first. backing up and restoring profiles profile manager offers two different mechanisms for backing up and restoring profiles. backup folder profile manager has a local backup folder where ...
Debugging out-of-memory problems
by the time about:memory is loaded in a new tab and you have clicked the "measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose. 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. ...
Emscripten techniques
this page contains specific emscripten-related techniques. debugging out-of-memory problems a common bug to diagnose 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. ...
AsyncTestUtils extended framework
s (without moving them to the trash folder) yield async_delete_messages(asynmessageset); implementation details the following files make up the framework: asynctestutils.js: core async testing logic. dependent on loghelper.js so it can log what test it is on, etc. loghelper.js: this allows rich logging via logsploder. if you aren't using logsploder, then this just makes your tests fail if
errors get logged to the
error console (like you see if you go to the "tools |
error console" menu). messagegenerator.js: provides the syntheticmessage abstraction and messagegenerator class that can generate one or more syntheticmessages at a time. the messagescenariofactory produces specific pre-configured message threading configurations using fresh messages (important in avoiding duplicate message...
NSPR's Position On Abrupt Thread Termination
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 that the corruption, like the state, is shared, and their only resource is for the process to terminate. to make this solution work requires that a function that encounters an
error be designed such that it first repairs its immediate state, and then reports that
error to its caller. if the caller cannot deal with the failure, it must do the same. this process continues until the thread either recovers from the malady or returns from the root function. this is not all that difficult (though having done it a number of times to already existing code, i will admit it isn't much...
I/O Functions
m an existing stack of layers. the file descriptor of the top layer can be passed to nspr i/o functions, which invoke the appropriate version of the i/o methods polymorphically. nspr defines three identities: #define pr_invalid_io_layer (prdescidentity)-1 #define pr_top_io_layer (prdescidentity)-2 #define pr_nspr_io_layer (prdescidentity)0 pr_invalid_io_layer: an invalid layer identify (for
error return). pr_top_io_layer: the identity of the top of the stack. pr_nspr_io_layer: the identity for the layer implemented by nspr. pr_top_io_layer may be used as a shorthand for identifying the topmost layer of an existing stack. for example, the following lines of code are equivalent: rv = pr_pushiolayer(stack, pr_top_io_layer, my_layer); rv = pr_pushiolayer(stack, pr_getlayersidentity(stac...
NSPR LOG MODULES
hich log modules have logging enabled. syntax modulename:level[, modulename:level]* modulename is the name specified in a pr_newlogmodule call or one of the handy magic names listed below. level is a numeric value between 0 and 5, with the values having the following meanings: 0 = pr_log_none: nothing should be logged 1 = pr_log_always: important; intended to always be logged 2 = pr_log_
error:
errors 3 = pr_log_warning: warnings 4 = pr_log_debug: debug messages, notices 5: everything! description specify a modulename that is associated with the name argument in a call to pr_newlogmodule and a non-zero level value to enable logging for the named modulename. special log module names are provided for controlling nspr's log service at execution time. these controls should be set i...
PRDescIdentity
ch layer has it own identity. identities are allocated by the runtime and are to be associated (by the layer implementor) with all file descriptors of that layer. it is then possible to scan the chain of layers and find a layer that one recognizes, then predict that it will implement a desired protocol. there are three well-known identities: pr_invalid_io_layer, an invalid layer identity, for
error return pr_top_io_layer, the identity of the top of the stack pr_nspr_io_layer, the identity used by nspr proper layers are created by pr_getuniqueidentity. a string may be associated with a layer when the layer is created. the string is copied by the runtime, and pr_getnameforidentity returns a reference to that copy. there is no way to delete a layer's identity after the layer is created. ...
PRJobIoDesc
syntax #include <prtpool.h> typedef struct prjobiodesc { prfiledesc *socket; pr
errorcode
error; printervaltime timeout; } prjobiodesc; ...
PRLogModuleLevel
the enumerated type prlogmodulelevel defines levels of logging available to application programs. ...
PR_AcceptRead
from the peer. timeout the timeout interval only applies to the read portion of the operation. pr_acceptread blocks indefinitely until the connection is accepted; the read will time out after the timeout interval elapses. returns a positive number indicates the number of bytes read from the peer. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_get
error. description pr_acceptread accepts a new connection and retrieves the newly created socket's descriptor and the connecting peer's address. also, as its name suggests, pr_acceptread receives the first block of data sent by the peer. ...
PR_Available
function has the following parameter: fd pointer to a prfiledesc object representing a file or socket. returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading. for a normal file, these are the bytes beyond the current file pointer. if the function fails, it returns the value -1. the
error code can then be retrieved via pr_get
error. description pr_available works on normal files and sockets. pr_available does not work with pipes on win32 platforms. see also if the number of bytes available for reading is out of the range of a 32-bit integer, use pr_available64. ...
PR_Available64
function has the following parameter: fd pointer to a prfiledesc object representing a file or socket. returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading. for a normal file, these are the bytes beyond the current file pointer. if the function fails, it returns the value -1. the
error code can then be retrieved via pr_get
error. description pr_available64 works on normal files and sockets. pr_available does not work with pipes on win32 platforms. see also if the number of bytes available for reading is within the range of a 32-bit integer, use pr_available. ...
PR_Bind
s the following parameters: fd a pointer to a prfiledesc object representing a socket. addr a pointer to a prnetaddr object representing the address to which the socket will be bound. returns the function returns one of the following values: upon successful binding of an address to a socket, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_get
error. description when a new socket is created, it has no address bound to it. pr_bind assigns the specified address (also known as name) to the socket. if you do not care about the exact ip address assigned to the socket, set the inet.ip field of prnetaddr to pr_htonl(pr_inaddr_any). if you do not care about the tcp/udp port assigned to the socket, set the inet.port field of prnetaddr to 0. note ...
PR_Calloc
allocates zeroed memory from the heap for a number of objects of a given size. syntax #include <prmem.h> void *pr_calloc ( pruint32 nelem, pruint32 elsize); parameters nelem the number of elements of size elsize to be allocated. elsize the size of an individual element. returns an untyped pointer to the allocated memory, or if the allocation attempt fails, null. call pr_get
error() to retrieve the
error returned by the libc function malloc(). description this function allocates memory on the heap for the specified number of objects of the specified size. all bytes in the allocated memory are cleared. ...
PR_CloseDir
closes the specified directory. syntax #include <prio.h> prstatus pr_closedir(prdir *dir); parameter the function has the following parameter: dir a pointer to a prdir structure representing the directory to be closed. returns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_get
error. description when a prdir object is no longer needed, it must be closed and freed with a call to pr_closedir call. note that after a pr_closedir call, any prdirentry object returned by a previous pr_readdir call on the same prdir object becomes invalid. see also pr_opendir ...
PR_CloseFileMap
closes a file mapping. syntax #include <prio.h> prstatus pr_closefilemap(prfilemap *fmap); parameter the function has the following parameter: fmap the file mapping to be closed. returns the function returns one of the following values: if the memory region is successfully unmapped, pr_success. if the memory region is not successfully unmapped, pr_failure. the
error code can be retrieved via pr_get
error. description when a file mapping created with a call to pr_createfilemap is no longer needed, it should be closed with a call to pr_closefilemap. ...
PR_Connect
addr a pointer to the address of the peer to which the socket is to be connected. timeout a value of type printervaltime specifying the time limit for completion of the connect operation. returns the function returns one of the following values: upon successful completion of connection setup, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_get
error. description pr_connect is usually invoked on a tcp socket, but it may also be invoked on a udp socket. both cases are discussed here. if the socket is a tcp socket, pr_connect establishes a tcp connection to the peer. if the socket is not bound, it will be bound to an arbitrary local address. pr_connect blocks until either the connection is successfully established or an
error occurs. the f...
PR_CreatePipe
rfiledesc pointer. on return, this parameter contains the file descriptor for the read end of the pipe. writepipe a pointer to a prfiledesc pointer. on return, this parameter contains the file descriptor for the write end of the pipe. returns the function returns one of these values: if the pipe is successfully created, pr_success. if the pipe is not successfully created, pr_failure. the
error code can be retrieved via pr_get
error. description pr_createpipe creates an anonymous pipe. data written into the write end of the pipe can be read from the read end of the pipe. pipes are useful for interprocess communication between a parent and a child process. when the pipe is no longer needed, both ends should be closed with calls to pr_close. pr_createpipe is currently implemented on un...
PR_ImportFileMapFromString
creates a prfilemap from an identifying string. syntax #include <prshma.h> nspr_api( prfilemap * ) pr_importfilemapfromstring( const char *fmstring ); parameter the function has the following parameter: fmstring a pointer to string created by pr_exportfilemapasstring. returns prfilemap pointer or null on
error. description pr_importfilemapfromstring creates a prfilemap object from a string previously created by pr_exportfilemapasstring. ...
PR_InitializeNetAddr
structure. the value is specified in host byte order. addr a pointer to the prnetaddr structure to be manipulated. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may occur, for example, if the value of val is not within the ranges defined by prnetaddrvalue. you can retrieve the reason for the failure by calling pr_get
error. description pr_initializenetaddr allows the assignment of special network address values and the port number, while also setting the state that indicates the version of the address being used. the special network address values are identified by the enum prnetaddrvalue: typedef enum prnetaddrvalue{ pr_ipaddrnull, pr_ipaddrany, pr_ipaddrloopback } prnetaddrvalue; the enum has the fol...
PR_JoinThread
om its root function. pr_jointhread must not be called until after pr_createthread has returned. if pr_jointhread is not called on the same thread as pr_createthread, then it is the caller's responsibility to ensure that pr_createthread has completed. several threads cannot wait for the same thread to complete. one of the calling threads operates successfully, and the others terminate with the
error pr_failure. the calling thread is not blocked if the target thread has already terminated. pr_jointhread is interruptable. ...
PR_LOG
writes an entry to the log. syntax #include <prlog.h> void pr_log ( prlogmoduleinfo *_module, prlogmodulelevel _level ... _args); parameters the macro has these parameters: _module a pointer to a log module structure. _level a level value. possible values are: pr_log_none = 0 pr_log_always = 1 pr_log_
error = 2 pr_log_warning = 3 pr_log_debug = 4 pr_log_notice = pr_log_debug pr_log_warn = pr_log_warning pr_log_min = pr_log_debug pr_log_max = pr_log_debug _args a variable length argument list, as if to printf. returns nothing description this macro formats the specified arguments and writes the output to the log file, if logging is enabled...
PR_LOG_TEST
is enabled for a module and level. syntax #include <prlog.h> prbool pr_log_test ( prlogmoduleinfo *_module, prlogmodulelevel _level); parameters the macro has these parameters: _module a pointer to a log module structure. _level a level value. possible values are: pr_log_none = 0 pr_log_always = 1 pr_log_
error = 2 pr_log_warning = 3 pr_log_debug = 4 pr_log_notice = pr_log_debug pr_log_warn = pr_log_warning pr_log_min = pr_log_debug pr_log_max = pr_log_debug returns pr_true when logging is enabled for the given module and level, otherwise pr_false. description this macro tests whether logging is enabled for the specified module and level. use it as an expres...
PR_Listen
owing parameters: fd a pointer to a prfiledesc object representing a socket that will be used to listen for new connections. backlog the maximum length of the queue of pending connections. returns the function returns one of the following values: upon successful completion of listen request, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_get
error. description pr_listen turns the specified socket into a rendezvous socket. it creates a queue for pending connections and starts to listen for connection requests on the socket. the maximum size of the queue for pending connections is specified by the backlog parameter. pending connections may be accepted by calling pr_accept. ...
PR_LoadLibrary
loads a referenced library. syntax #include <prlink.h> prlibrary* pr_loadlibrary(const char *name); parameters the function has this parameter: name a platform-dependent character array that names the library to be loaded, as returned by pr_getlibraryname. returns if successful, returns a reference to an opaque prlibrary object. if the operation fails, returns null. use pr_get
error to find the reason for the failure. description this function loads and returns a reference to the specified library. the returned reference becomes the library's identity. the function suppresses duplicate loading if the library is already known by the runtime. each call to pr_loadlibrary must be paired with a corresponding call to pr_unloadlibrary in order to return the runtime to its original sta...
PR_MALLOC
allocates memory of a specified size from the heap. syntax #include <prmem.h> void * pr_malloc(_bytes); parameter _bytes size of the requested memory block. returns an untyped pointer to the allocated memory, or if the allocation attempt fails, null. call pr_get
error() to retrieve the
error returned by the libc function malloc(). description this macro allocates memory of the requested size from the heap. ...
PR_MemMap
function has the following parameters: fmap a pointer to the file-mapping object representing the file to be memory-mapped. offset the starting offset of the section of file to be mapped. the offset must be aligned to whole pages. len length of the section of the file to be mapped. returns the starting address of the memory region to which the section of file is mapped. returns null on
error. description pr_memmap maps a section of the file represented by the file mapping fmap to memory. the section of the file starts at offset and has the length len. when the file-mapping memory region is no longer needed, it should be unmapped with a call to pr_memunmap. ...
PR_MkDir
orms in the future. possible values include the following: 00400. read by owner. 00200. write by owner. 00100. search by owner. 00040. read by group. 00020. write by group. 00010. search by group. 00004. read by others. 00002. write by others. 00001. search by others. returns if successful, pr_success. if unsuccessful, pr_failure. the actual reason can be retrieved via pr_get
error. description pr_mkdir creates a new directory with the pathname name. all the path components up to but not including the leaf component must already exist. for example, if the pathname of the directory to be created is a/b/c/d, the directory a/b/c must already exist. see also pr_rmdir ...
PR_NEW
allocates memory of a specified size from the heap. syntax #include <prmem.h> _type * pr_new(_struct); parameter _struct the name of a type. returns an pointer to a buffer sized to contain the type _struct, or if the allocation attempt fails, null. call pr_get
error() to retrieve the
error returned by the libc function. description this macro allocates memory whose size is sizeof(_struct) and returns a pointer to that memory. ...
PR_NEWZAP
allocates and clears memory from the heap for an instance of a given type. syntax #include <prmem.h> _type * pr_newzap(_struct); parameter _struct the name of a type. returns an pointer to a buffer sized to contain the type _struct, or if the allocation attempt fails, null. the bytes in the buffer are all initialized to 0. call pr_get
error() to retrieve the
error returned by the libc function. description this macro allocates an instance of the specified type from the heap and sets the content of that memory to zero. ...
PR_NetAddrToString
rs the function has the following parameters: addr a pointer to the network address to be converted. string a buffer that will hold the converted string on output. size the size of the result buffer (string). returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_get
error. description the network address to be converted (addr) may be either an ipv4 or ipv6 address structure, assuming that the nspr library and the host system are both configured to utilize ipv6 addressing. if addr is an ipv4 address, size needs to be at least 16. if addr is an ipv6 address, size needs to be at least 46. ...
PR NewProcessAttr
he function has no parameters. returns a pointer to the new process attributes structure. description this function creates a new prprocessattr structure that specifies the attributes of a new process, then returns a pointer to the structure. the new prprocessattr structure is initialized with these default attributes: the standard i/o streams (standard input, standard output, and standard
error) are not redirected. no file descriptors are inherited by the new process. ...
PR_OpenAnonFileMap
ame syntax #include <prshma.h> nspr_api( prfilemap *) pr_openanonfilemap( const char *dirname, prsize size, prfilemapprotect prot ); parameters the function has the following parameters: dirname a pointer to a directory name that will contain the anonymous file. size the size of the shared memory. prot how the shared memory is mapped. returns pointer to prfilemap or null on
error. description if the shared memory already exists, a handle is returned to that shared memory object. on unix platforms, pr_openanonfilemap uses dirname as a directory name, without the trailing '/', to contain the anonymous file. a filename is generated for the name. on windows platforms, dirname is ignored. ...
PR_OpenSemaphore
e( const char *name, printn flags, printn mode, pruintn value ); parameters the function has the following parameters: name the name to be given the semaphore. flags how to create or open the semaphore. mode unix style file mode to be used when creating the semaphore. value the initial value assigned to the semaphore. returns a pointer to a prsem structure or null/code> on
error. description if the named semaphore doesn't exist and the pr_sem_create flag is specified, the named semaphore is created. the created semaphore needs to be removed from the system with a pr_deletesemaphore call. if pr_sem_create is specified, the third argument is the access permission bits of the new semaphore (same interpretation as the mode argument to pr_open) and the fourth argument is ...
PR_PopIOLayer
ng the stack from which the specified layer is to be removed. id identity of the layer to be removed from the stack. returns the function returns one of the following values: if the layer is successfully removed from the stack, a pointer to the removed layer. if the layer is not found in the stack or cannot be popped (for example, the bottommost layer), the function returns null with the
error code pr_invalid_argument_
error. description pr_popiolayer pops the specified layer from the stack. if the object to be removed is found, pr_popiolayer returns a pointer to the removed object the object then becomes the responsibility of the caller. even if the identity indicates the top layer of the stack, the reference returned is not the file descriptor for the stack and that file descripto...
PR_PushIOLayer
id a prdescidentity object for the layer on the stack above which the new layer is to be added. layer a pointer to a prfiledesc object representing the new layer to be added to the stack. returns the function returns one of the following values: if the layer is successfully pushed onto the stack, pr_success. if the layer is not successfully pushed onto the stack, pr_failure. use pr_get
error to get additional information regarding the reason for the failure. description a file descriptor for a layer (possibly allocated using pr_createiolayerstub) may be pushed onto an existing stack of file descriptors at any time. the new layer is inserted into the stack just above the layer with the identity specified by id. even if the id parameter indicates the topmost layer of the stack, the...
PR_QueueJob_Timer
pr_createthreadpool. iod a pointer to a prjobiodesc structure. timeout a value, expressed as a printervaltime, to wait before queuing the job. fn the function to be executed when the job is executed. arg a pointer to an argument passed to fn. joinable if pr_true, the job is joinable. if pr_false, the job is not joinable. see pr_joinjob. returns pointer to a prjob structure or null on
error. ...
PR_Realloc
resizes allocated memory on the heap. syntax #include <prmem.h> void *pr_realloc ( void *ptr, pruint32 size); parameters ptr a pointer to the existing memory block being resized. size the size of the new memory block. returns an untyped pointer to the allocated memory, or if the allocation attempt fails, null. call pr_get
error() to retrieve the
error returned by the libc function realloc(). description this function attempts to enlarge or shrink the memory block addressed by ptr to a new size. the contents of the specified memory remains the same up to the smaller of its old size and new size, although the new memory block's address can be different from the original address. ...
PR_Read
buf a pointer to a buffer to hold the data read in. on output, the buffer contains the data. amount the size of buf (in bytes). returns one of the following values: a positive number indicates the number of bytes actually read in. the value 0 means end of file is reached or the network connection is closed. the value -1 indicates a failure. to get the reason for the failure, call pr_get
error. description the thread invoking pr_read blocks until it encounters an end-of-stream indication, some positive number of bytes (but no more than amount bytes) are read in, or an
error occurs. ...
PR_Recv
pr_msg_peek. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes actually received. the value 0 means the network connection is closed. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_get
error. description pr_recv blocks until some positive number of bytes are transferred, a timeout occurs, or an
error occurs. no more than amount bytes will be transferred. ...
PR_RecvFrom
r on return. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes actually received. the value 0 means the network connection is closed. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_get
error. description pr_recvfrom receives up to a specified number of bytes from socket, which may or may not be connected. the operation blocks until one or more bytes are transferred, a timeout has occurred, or there is an
error. no more than amount bytes will be transferred. pr_recvfrom is usually used with a udp socket. ...
PR_Rename
s the following parameters: from the old name of the file to be renamed. to the new name of the file. returns one of the following values: if file is successfully renamed, pr_success. if file is not successfully renamed, pr_failure. description pr_rename renames a file from its old name (from) to a new name (to). if a file with the new name already exists, pr_rename fails with the
error code pr_file_exists_
error. in this case, pr_rename does not overwrite the existing filename. ...
PR_RmDir
removes a directory with a specified name. syntax #include <prio.h> prstatus pr_rmdir(const char *name); parameter the function has the following parameter: name the name of the directory to be removed. returns if successful, pr_success. if unsuccessful, pr_failure. the actual reason can be retrieved via pr_get
error. description pr_rmdir removes the directory specified by the pathname name. the directory must be empty. if the directory is not empty, pr_rmdir fails and pr_get
error returns the
error code pr_directory_not_empty_
error. see also pr_mkdir ...
PR_STATIC_ASSERT
prevents code from compiling when an expression has the value false at compile time. syntax #include <prlog.h> pr_static_assert ( expression ); parameters the macro has this parameter: expression any valid expression which evaluates at compile-time to true or false. an expression which cannot be evaluated at compile time will cause a compiler
error; see pr_assert for a runtime alternative. returns nothing description this macro evaluates the specified expression. when the result is zero (false) program compilation will fail with a compiler
error; otherwise compilation completes successfully. the compiler
error will include the number of the line for which the compile-time assertion failed. this macro may only be used in locations where an extern function declaration may be used...
PR_Seek
pr_seek_end. sets the file pointer to the size of the file plus the value of the offset parameter. returns the function returns one of the following values: if the function completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file. if the function fails, the file pointer remains unchanged and the function returns -1. the
error code can then be retrieved with pr_get
error. description here's an idiom for obtaining the current location of the file pointer for the file descriptor fd: pr_seek(fd, 0, pr_seek_cur) see also if you need to move the file pointer by a large offset that's out of the range of a 32-bit integer, use pr_seek64. new code should use pr_seek64 so that it can handle files larger than 2 gb. ...
PR_Send
lue of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent. if the parameter fd is a blocking socket, this number must always equal amount. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_get
error. description pr_send blocks until all bytes are sent, a timeout occurs, or an
error occurs. ...
PR_SendTo
ways be zero. addr a pointer to the address of the destination. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_get
error. description pr_sendto sends a specified number of bytes from a socket to the specified destination address. the calling thread blocks until all bytes are sent, a timeout has occurred, or there is an
error. ...
PR_SetPollableEvent
nt. syntax nspr_api(prstatus) pr_setpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_get
error. ...
PR_SetSocketOption
description on input, the caller must set both the option and value fields of the prsocketoptiondata object pointed to by the data parameter. ...
PR_Shutdown
ollowing: pr_shutdown_rcv. further receives will be disallowed. pr_shutdown_send. further sends will be disallowed. pr_shutdown_both. further sends and receives will be disallowed. returns the function returns one of the following values: upon successful completion of shutdown request, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_get
error. description the prshutdownhow enumeration is defined as follows: typedef enum prshutdownhow{ pr_shutdown_rcv = 0, pr_shutdown_send = 1, pr_shutdown_both = 2 } prshutdownhow; ...
PR_Sleep
causes the current thread to yield for a specified amount of time. syntax #include <prthread.h> prstatus pr_sleep(printervaltime ticks); parameter pr_sleep has the following parameter: ticks the number of ticks you want the thread to sleep for (see printervaltime). returns calling pr_sleep with a parameter equivalent to pr_interval_no_timeout is an
error and results in a pr_failure
error. description pr_sleep simply waits on a condition for the amount of time specified. if you set ticks to pr_interval_no_wait, the thread yields. if ticks is not pr_interval_no_wait, pr_sleep uses an existing lock, but has to create a new condition for this purpose. if you have already created such structures, it is more efficient to use them directly. calling pr_sleep with the value of ticks se...
PR_TransmitFile
ill be kept open after the data is sent. pr_transmitfile_close_socket indicates that the connection should be closed immediately after successful transfer of the file. timeout time limit for completion of the transmit operation. returns a positive number indicates the number of bytes successfully written, including both the headers and the file. the value -1 indicates a failure. if an
error occurs while sending the file, the pr_transmitfile_close_socket flag is ignored. the reason for the failure can be obtained by calling pr_get
error. description the pr_transmitfile function sends a complete file (sourcefile) across a connected socket (networksocket). if headers is non-null, pr_transmitfile sends the headers across the socket before sending the file. the enumeration prtransmitf...
PR_UnloadLibrary
unloads a library loaded with pr_loadlibrary. syntax #include <prlink.h> prstatus pr_unloadlibrary(prlibrary *lib); parameters the function has this parameter: lib a reference previously returned from pr_loadlibrary. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. use pr_get
error to find the reason for the failure. description this function undoes the effect of a pr_loadlibrary. after calling this function, future references to the library using its identity as returned by pr_loadlibrary will be invalid. ...
PR_Unlock
attempting to release a lock that was locked by a different thread causes undefined behavior. syntax #include <prlock.h> prstatus pr_unlock(prlock *lock); parameter pr_unlock has one parameter: lock a pointer to a lock object to be released. returns the function returns one of the following values: if successful, pr_success. ...
PR_Unmap
ap( void *addr, pruint32 len); parameters the function has the following parameters: addr the starting address of the memory region to be unmapped. len the length, in bytes, of the memory region. returns the function returns one of the following values: if the memory region is successfully unmapped, pr_success. if the memory region is not successfully unmapped, pr_failure. the
error code can be retrieved via pr_get
error. description pr_memunmap removes the file mapping for the memory region (addr, addr + len). the parameter addr is the return value of an earlier call to pr_memmap. ...
PR_Wait
n printervaltime units) that the thread is willing to wait for an explicit notification before being rescheduled. returns the function returns one of the following values: pr_success means the thread is being resumed from the pr_wait call either because it was explicitly notified or because the time specified by the parameter ticks has expired. pr_failure means pr_wait encountered a system
error (such as an invalid monitor reference) or the thread was interrupted by another thread. description a call to pr_wait causes the thread to release the monitor's lock, just as if it had called pr_exitmonitor as many times as it had called pr_entermonitor. this has the effect of making the monitor available to other threads. when the wait is over, the thread regains control of the monitor's lock...
PR_WaitCondVar
ing a rescheduling within the runtime, then immediately attempt to reacquire the lock and resume. returns the function returns one of the following values: if successful, pr_success. if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable or the thread was interrupted with pr_interrupt), pr_failure. the details can be determined with pr_get
error. description before the call to pr_waitcondvar, the lock associated with the condition variable must be held by the calling thread. after a call to pr_waitcondvar, the lock is released and the thread is blocked in a "waiting on condition" state until another thread notifies the condition or a caller-specified amount of time expires. when the condition variable is notified, a thread waiting on...
PR_Write
to the prfiledesc object for a file or socket. buf a pointer to the buffer holding the data to be written. amount the amount of data, in bytes, to be written from the buffer. returns one of the following values: a positive number indicates the number of bytes successfully written. the value -1 indicates that the operation failed. the reason for the failure is obtained by calling pr_get
error. description the thread invoking pr_write blocks until all the data is written or the write operation fails. therefore, the return value is equal to either amount (success) or -1 (failure). note that if pr_write returns -1, some data (less than amount bytes) may have been written before an
error occurred. ...
PR_strtod
int number. ties are broken by the ieee round-even rule. the string is scanned up to the first unrecognized character. if the value of se is not (char **) null, pr_strtod stores a pointer to the character terminating the scan in *se. if the answer would overflow, a properly signed huge_val (infinity) is returned. if the answer would underflow, a properly signed 0 is returned. in both cases, pr_get
error() returns the
error code pr_range_
error. if no number can be formed, se is set to s00, and 0 is returned. ...
NSPR API Reference
red memory shared memory protocol named shared memory functions anonymous shared memory anonymous memory protocol anonymous shared memory functions ipc semaphores ipc semaphore functions thread pools thread pool types thread pool functions random number generator random number generator function hash tables hash tables and type constants hash table functions nspr
error handling
error type
error functions
error codes ...
CERT_FindCertByIssuerAndSN
count on the certificate instance. example certissuerandsn issuersn; issuersn.derissuer.data = caname->data; issuersn.derissuer.len = caname->len; issuersn.serialnumber.data = authoritykeyid->authcertserialnumber.data; issuersn.serialnumber.len = authoritykeyid->authcertserialnumber.len; issuercert = cert_findcertbyissuerandsn(cert->dbhandle, &issuersn); if ( issuercert == null ) { port_set
error (sec_
error_unknown_issuer); } see also occurrences of cert_findcertbyissuerandsn in the current nss source code (generated by lxr). ...
NSS Certificate Download Specification
ocol responses. there are several mime content types that are used to indicate to the browser what type of certificate is being imported. these mime types are: application/x-x509-user-cert the certificate being downloaded is a user certificate belonging to the user operating the browser. if the private key associated with the certificate does not exist in the user's local key database, then an
error dialog is generated and the certificate is not imported. if a certificate chain is being imported then the first certificate in the chain must be the user certificate, and any subsequent certificates will be added as untrusted ca certificates to the local database. application/x-x509-ca-cert the certificate being downloaded represents a certificate authority. when it is downloaded the user will ...
NSS 3.12.5 release_notes
ssl_renegotiate_never: never renegotiate at all (default). ssl_renegotiate_unrestricted: renegotiate without restriction, whether or not the peer's client hello bears the renegotiation info extension (as we always did in the past). unsafe. tls compression enable tls compression with: ssl_enable_deflate: enable tls compression with deflate. off by default. (see ssl.h)
error codes: ssl_
error_decompression_failure (see sslerr.h) ssl_
error_renegotiation_not_allowed (see sslerr.h) new context initialization and shutdown functions see nss.h for details. the 2 new functions are: nss_initcontext nss_shutdowncontext parameters for these functions are used to initialize softoken. these are mostly strings used to internationalize softoken.
NSS 3.14.1 release notes
responses. the ability to create signed ocsp responses has been added in nss 3.14.1. note that this code is used primarily for purposes of testing. new functions in ocspt.h cert_createocspsingleresponsegood cert_createocspsingleresponseunknown cert_createocspsingleresponserevoked cert_createencodedocspsuccessresponse cert_createencodedocsp
errorresponse new types in ocspt.h certocspresponderidtype notable changes in nss 3.14.1 windows ce support has been removed from the code base. bug 812399 - in nss 3.14, a regression caused bug 641052 / cve-2011-3640 to be re-introduced under certain situations. this regression only affected applications that initialize nss via the nss_nodb_init function. nss 3.
NSS 3.15.1 release notes
_1_2 - the protocol version of tls 1.2 on the wire, value 0x0303. tls_dhe_rsa_with_aes_256_cbc_sha256, tls_rsa_with_aes_256_cbc_sha256, tls_ecdhe_ecdsa_with_aes_128_cbc_sha256, tls_ecdhe_rsa_with_aes_128_cbc_sha256, tls_dhe_rsa_with_aes_128_cbc_sha256, tls_rsa_with_aes_128_cbc_sha256, tls_rsa_with_null_sha256 - new tls 1.2 only hmac-sha256 cipher suites. in sslerr.h ssl_
error_unsupported_hash_algorithm, ssl_
error_digest_failure, ssl_
error_incorrect_signature_algorithm - new
error codes for tls 1.2. in sslt.h ssl_hmac_sha256 - a new value in the sslmacalgorithm enum type. ssl_signature_algorithms_xtn - a new value in the sslextensiontype enum type. new pkcs #11 mechanisms none. notable changes in nss 3.15.1 bug 856060 - enforce na...
NSS 3.16.2.3 release notes
ontains a backport of the tls_fallback_scsv feature, which was originally made available in nss 3.17.1. new functionality tls_fallback_scsv is a signaling cipher suite value that indicates a handshake is the result of tls version fallback. new macros in ssl.h ssl_enable_fallback_scsv - an ssl socket option that enables tls_fallback_scsv. off by default. in sslerr.h ssl_
error_inappropriate_fallback_alert - a new ssl
error code. in sslproto.h tls_fallback_scsv - a a signaling cipher suite value that indicates a handshake is the result of tls version fallback. notable changes in nss 3.16.2.3 bug 1057161: check that an imported elliptic curve public key is valid. previously nss would only validate the peer's public key before performing ecdh key agr...
NSS 3.16.2 release notes
sion to a certificate. it is the same as cert_addextension except that the oid is represented by a secitem instead of a secoidtag. in pk11pub.h pk11_privdecrypt - decrypts with a private key. the algorithm is specified with a ck_mechanism_type. pk11_pubencrypt - encrypts with a public key. the algorithm is specified with a ck_mechanism_type. new macros in sslerr.h ssl_
error_next_protocol_no_callback - an ssl
error code that means the next protcol negotiation extension was enabled, but the callback was cleared prior to being needed. ssl_
error_next_protocol_no_protocol - an ssl
error code that means the server supports no protocols that the client advertises in the alpn extension. notable changes in nss 3.16.2 the btoa command has a new command-line option ...
NSS 3.17.1 release notes
s use only. applications that use or depend on these symbols can and will break in future nss releases. new functionality tls_fallback_scsv is a signaling cipher suite value that indicates a handshake is the result of tls version fallback. new macros in ssl.h ssl_enable_fallback_scsv - an ssl socket option that enables tls_fallback_scsv. off by default. in sslerr.h ssl_
error_inappropriate_fallback_alert - a new ssl
error code. in sslproto.h tls_fallback_scsv - a a signaling cipher suite value that indicates a handshake is the result of tls version fallback. notable changes in nss 3.17.1 signature algorithms now use sha-256 instead of sha-1 by default. added support for linux on little-endian powerpc64. bugs fixed in nss 3.17.1 this bugzilla ...
NSS 3.17.4 release notes
s://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_4_rtm/src/ new in nss 3.17.4 new functionality no new functionality is introduced in this release. this is a patch release to fix multiple bugs. notable changes in nss 3.17.4 bug 1084986: if an ssl/tls connection fails, because client and server don't have any common protocol version enabled, nss has been changed to report
error code ssl_
error_unsupported_version (instead of reporting ssl_
error_no_cypher_overlap). bug 1112461: libpkix was fixed to prefer the newest certificate, if multiple certificates match. bug 1094492: fixed a memory corruption issue during failure of keypair generation. bug 1113632: fixed a failure to reload a pkcs#11 module in fips mode. bug 1119983: fixed interoperability of nss server code wit...
NSS 3.18.1 release notes
ficates. notable changes in nss 3.18.1 the following ca certificate had the websites and code signing trust bits restored to their original state to allow more time to develop a better transition strategy for affected sites. the websites and code signing trust bits were turned off in nss 3.18. but when firefox 38 went into beta, there was a huge spike in the number of certificate verification
errors attributed to this change. so, to give website administrators more time to update their web servers, we reverted the trust bits back to being enabled. ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a the following ca certificate was removed after discussion about it in the mozilla.dev.security.
NSS 3.19.2.4 release notes
unctionality no new functionality has been introduced in this release. security fixes in nss 3.19.2.4 the following security fixes from nss 3.21 have been backported to nss 3.19.2.4: bug 1185033 / cve-2016-1979 - use-after-free during processing of der encoded keys in nss bug 1209546 / cve-2016-1978 - use-after-free in nss during ssl connections in low memory bug 1190248 / cve-2016-1938 -
errors in mp_div and mp_exptmod cryptographic functions in nss compatibility nss 3.19.2.4 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.19.2.4 shared libraries without recompiling or relinking. furthermore, applications that restrict the use of nss apis to the functions listed in nss public ...
NSS 3.27.2 Release Notes
ion is used to set the distinguished names that an nss server includes in its tls certificaterequest message. if this function is not used, nss will include the distinguished names for all trust anchors installed in the database. this can be a lengthy list. previous versions of nss leaked the memory used to store distinguished names when ssl_settrustanchors() was used. this release fixes that
error. bugs fixed in nss 3.27.2 the following bug has been fixed in nss 3.27.2: bug 1318561 - ssl_settrustanchors leaks compatibility nss 3.27.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.27.2 shared libraries without recompiling or relinking. furthermore, applications that restrict t...
NSS 3.28.1 release notes
:b5:8a:d5:6d:de:33:1a:30:45:6b:c6:5c:60:1a:4e:9b:18:de:dc:ea:08:e7:da:aa:07:81:5f:f0 the version number of the updated root ca list has been set to 2.11 a misleading assertion/alert has been removed, when nss tries to flush data to the peer but the connection was already reset. bugs fixed in nss 3.28.1 bug 1296697 - december 2016 batch of root ca changes bug 1322496 - internal
error assert when the other side closes connection before reading eoed compatibility nss 3.28.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.28.1 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in nss pu...
NSS 3.35 release notes
in this section are experimental. any of these apis may be removed from future nss versions. applications must not rely on these apis to be present. if an application is linked at runtime to a later version of nss, which no longer provides any of these apis, the application must handle the scenario gracefully. in order to ease transitions, experimental functions return secfailure and set the ssl_
error_unsupported_experimental_api code if the selected api is not available. experimental functions will always return this result if they are disabled or removed from a later nss release. if these experimental functions are made permanent in a later nss release, no change to code is necessary. (only apis exported in *.def files are stable apis.) new experimental functionality provided below are de...
NSS 3.36.2 release notes
ps download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_36_2_rtm/src/ new in nss 3.36.2 new functionality no new functionality is introduced in this release. this is a patch release to fix regression bugs. bugs fixed in nss 3.36.2 bug 1462303 - connecting to a server that was recently upgraded to tls 1.3 would result in a ssl_rx_malformed_server_hello
error. bug 1460673 - fix a rare bug with pkcs#12 files. this bugzilla query returns all the bugs fixed in nss 3.36.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.36.2 compatibility nss 3.36.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with old...
NSS 3.37.1 release notes
ps download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_37_1_rtm/src/ new in nss 3.37.1 new functionality no new functionality is introduced in this release. this is a patch release to fix regression bugs. bugs fixed in nss 3.37.1 bug 1462303 - connecting to a server that was recently upgraded to tls 1.3 would result in a ssl_rx_malformed_server_hello
error. bug 1460673 - fix a rare bug with pkcs#12 files. this bugzilla query returns all the bugs fixed in nss 3.37.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.37.1 compatibility nss 3.37.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with old...
NSS 3.47 release notes
bugs found by clang scanners. bug 1542207 - limit policy check on signature algorithms to known algorithms bug 1560329 - drbg: add continuous self-test on entropy source bug 1579290 - asan builds should disable lsan while building bug 1385061 - build nspr tests with nss make; add gyp parameters to build/run nspr tests bug 1577359 - build atob and btoa for thunderbird bug 1579036 - confusing
error when trying to export non-existent cert with pk12util bug 1578626 - [cid 1453375] ub: decrement nullptr. bug 1578751 - ensure a consistent style for pk11_find_certs_unittest.cc bug 1570501 - add cmac to freebl and pkcs #11 libraries bug 657379 - nss uses the wrong oid for signaturealgorithm field of signerinfo in cms for dsa and ecdsa bug 1576664 - remove -mms-bitfields from mingw nss build.
NSS 3.49 release notes
se uses 3des instead of aes to encrypt db entries bug 1603257 - fix ubsan issue in softoken ckm_nss_chacha20_ctr initialization bug 1590001 - additional hrr tests (cve-2019-17023) bug 1600144 - treat clienthello with message_seq of 1 as a second clienthello bug 1603027 - test that esni is regenerated after helloretryrequest bug 1593167 - intermittent mis-reporting potential security risk sec_
error_unknown_issuer bug 1535787 - fix automation/release/nss-release-helper.py on macos bug 1594933 - disable building dbm by default bug 1562548 - improve gcm perfomance on aarch32 this bugzilla query returns all the bugs fixed in nss 3.49: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.49 compatibility ...
NSS 3.53 release notes
graceful phase-out for certificate authorities than complete removal from the root certificate builtin store. bugs fixed in nss 3.53 bug 1640260 - initialize pbe params (asan fix) bug 1618404 - set cka_nss_server_distrust_after for symantec root certs bug 1621159 - set cka_nss_server_distrust_after for consorci aoc, grca, and sk id root certs bug 1629414 - ppc64: correct compilation
error between vmx vs. vsx vector instructions bug 1639033 - fix various compile warnings in nss bug 1640041 - fix a null pointer in security/nss/lib/ssl/sslencode.c:67 bug 1640042 - fix a null pointer in security/nss/lib/ssl/sslsock.c:4460 bug 1638289 - avoid multiple definitions of sha{256,384,512}_* symbols when linking libfreeblpriv3.so in firefox on ppc64le bug 1636389 - relocate deprecated se...
NSS 3.55 release notes
k race in nsc_gettokeninfo. bug 1647752 - update dtls 1.3 implementation to draft-38. bug 1649190 - run cipher, sdr, and ocsp tests under standard test cycle in ci. bug 1649226 - add wycheproof ecdsa tests. bug 1637222 - consistently enforce iv requirements for des and 3des. bug 1067214 - enforce minimum pkcs#1 v1.5 padding length in rsa_checksignrecover. bug 1643528 - fix compilation
error with -w
error=strict-prototypes. bug 1646324 - advertise pkcs#1 schemes for certificates in the signature_algorithms extension. bug 1652331 - update nss 3.55 nspr version to 4.27. this bugzilla query returns all the bugs fixed in nss 3.55: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.55 compatibili...
NSS Sample Code Sample_1_Hashing
= hashnametooidtag(hashname); if (hashoidtag == sec_oid_unknown) { fprintf(stderr, "%s: invalid digest type - %s\n", progname, hashname); usage(progname); } /* digest it and print the result */ rv = digestfile(pr_stdout, pr_stdin, hashoidtag); if (rv != secsuccess) { fprintf(stderr, "%s: problem digesting data (%d)\n", progname, port_get
error()); } rv = nss_shutdown(); if (rv != secsuccess) { exit(-1); } return 0; } </sechash.h></secmodt.h></secoid.h></prio.h></plgetopt.h></prtypes.h></prprf.h> ...
Hashing - sample 1
= hashnametooidtag(hashname); if (hashoidtag == sec_oid_unknown) { fprintf(stderr, "%s: invalid digest type - %s\n", progname, hashname); usage(progname); } /* digest it and print the result */ rv = digestfile(pr_stdout, pr_stdin, hashoidtag); if (rv != secsuccess) { fprintf(stderr, "%s: problem digesting data (%d)\n", progname, port_get
error()); } rv = nss_shutdown(); if (rv != secsuccess) { exit(-1); } return 0; } ...
sample1
oidtag = hashnametooidtag(hashname); if (hashoidtag == sec_oid_unknown) { fprintf(stderr, "%s: invalid digest type - %s\n", progname, hashname); usage(progname); } /* digest it and print the result */ rv = digestfile(pr_stdout, pr_stdin, hashoidtag); if (rv != secsuccess) { fprintf(stderr, "%s: problem digesting data (%d)\n", progname, port_get
error()); } rv = nss_shutdown(); if (rv != secsuccess) { exit(-1); } return 0; } ...
NSS sources building testing
ment variables to tell the nss suite which hostname to use. as a test, it must be possible to successfully use the command "ping $host.$domsuf" on your computer (ping reports receiving replies). on many computers the variables host=localhost domsuf=localdomain works. in case you built nss in 64 bits, you need to set the use_64 environment variable to 1 to run the tests. if you get name resolution
errors, try to disable ipv6 on the loopback device. after you have set the required environment variables, use "cd nss/tests" and start the tests using "./all.sh". the tests will take a while to complete; on a slow computer it could take a couple of hours. once the test suite has completed, a summary will be printed that shows the number of failures. you can find the test suite results in directory n...
nss tech note7
you have the modulus and public exponent, you need to first encode them into an rsa public key and then import the public key into nss. pkcs #1 defines an rsa public key as a sequence of modulus and public exponent, both of which are integers. here is the asn.1 type definition: rsapublickey ::= sequence { modulus integer, -- n publicexponent integer -- e } the following sample code (
error handling omitted for brevity) encodes a rsapublickey from a modulus and a public exponent and imports the public key into nss. struct myrsapublickey { secitem m_modulus; secitem m_exponent; } inpubkey; secitem derpubkey; seckeypublickey *pubkey; const sec_asn1template myrsapublickeytemplate[] = { { sec_asn1_sequence, 0, null, sizeof(myrsapublickey) }, { sec_asn1_integer, offs...
PKCS11 FAQ
ins will a password change ever be done on the token? yes, nss attempts to change the password in user mode only. (it goes to sso mode only if your token identifies itself as ckf_login_required, but not ckf_user_initialized). it's perfectly valid to reject the password change request with a return value such as ckr_function_not_supported. if you do this, nss applications display an appropriate
error message for the user. if i have my smart card which has initial pin set at '9999', i insert it into my reader and download with my certificate (keygen completed), can i issue 'change password' from the firefox to set a new pin to the smart card? any scenario that you can give me similar to this process (a way to issue a certificate on an initialized new card)? yes. first open the tools/options/...
FC_GetSessionInfo
ioninfo( ck_session_handle hsession, ck_session_info_ptr pinfo ); parameters hsession [in] the open session handle. pinfo [out] pointer to the ck_session_info structure to be returned. description fc_getsessioninfo obtains information about a session. a user may call fc_getsessioninfo without logging into the token (to assume the nss user role). if the nss cryptographic module is in the
error state, fc_getsessioninfo returns ckr_device_
error. otherwise, it fills in the ck_session_info structure with the following information: state: the state of the session, i.e., no role is assumed, the user role is assumed, or the crypto officer role is assumed flags: bit flags that define the type of session ckf_rw_session (0x00000002): true if the session is read/write; false if the session is...
FC_InitPIN
returns the following return codes. ckr_ok: normal user's pin initialization succeeded. ckr_session_handle_invalid: the session handle is invalid. ckr_user_not_logged_in: the session is not in the "r/w so functions" state. ckr_pin_invalid: the pin has an invalid utf-8 character. ckr_pin_len_range: the pin is too short, too long, or too weak (doesn't have enough character types). ckr_device_
error: normal user's pin is already initialized. see also nsc_initpin, fc_setpin ...
FC_InitToken
string, i.e., ulpinlen argument should be 0. fc_inittoken() ignores the plabel argument. return value fc_inittoken() returns the following return codes. ckr_ok: token initialization succeeded. ckr_slot_id_invalid: slot id is invalid. ckr_token_write_protected we don't have a reference to the key database (we failed to open the key database or we have released our reference). ckr_device_
error: failed to reset the key database. application usage fc_inittoken() is used to reset the password for the key database when the user forgets the password. the "reset password" button of the mozilla application suite and seamonkey (in preferences->privacy & security->master passwords) calls fc_inittoken(). the "-t" (token reset) command of certutil calls fc_inittoken(). note: resetting the ...
FC_Initialize
pinitargs->libraryparameters is null. only some of the lock functions were provided by the application. ckr_cant_lock: the ckf_os_locking_ok flag is not set in pinitargs->flags. the nss cryptographic module always uses os locking and doesn't know how to use the lock functions provided by the application. ckr_cryptoki_already_initialized: the library is already initialized. ckr_device_
error we failed to create the oid tables, random number generator, or internal locks. (note: we probably should return ckr_host_memory instead.) the software integrity test or power-up self-tests failed. the nss cryptographic module is in a fatal
error state. ckr_host_memory: we ran out of memory. examples #include <assert.h> ck_function_list_ptr pfunctionlist; ck_rv crv; ck_c_initiali...
FC_Login
the pin description fc_login() logs a user into a token. the security officer (cku_so) only logs in to initialize the normal user's pin. the so pin is the empty string. the nss cryptographic module doesn't allow the so to log in if the normal user's pin is already initialized. return value fc_login() returns the following return codes. ckr_ok: the user logged in successfully. ckr_device_
error: the token is in the
error state. ckr_host_memory: memory allocation failed. ckr_pin_incorrect: the pin is incorrect. ckr_pin_len_range: the pin is too long (ulpinlen is greater than 255). the function should return ckr_pin_incorrect in this case. ckr_session_handle_invalid: the session handle is invalid. ckr_user_already_logged_in: the user is already logged in. ckr_user_type_invalid ...
NSC_InitToken
ns the following return codes. ckr_ok: token initialization succeeded. ckr_slot_id_invalid: slot id is invalid. ckr_token_write_protected slot id is 1. (the non-fips mode has two slots: 1 and 2. the key database is in slot 2. slot 1 doesn't have a key database.) we don't have a reference to the key database (we failed to open the key database or we have released our reference). ckr_device_
error: failed to reset the key database. examples application usage nsc_inittoken() is used to reset the password for the key database when the user forgets the password. the "reset password" button of the mozilla application suite and seamonkey (in preferences->privacy & security->master passwords) calls nsc_inittoken(). the "-t" (token reset) command of certutil calls nsc_inittoken(). note: ...
NSC_Login
he pin description nsc_login() logs a user into a token. the security officer (cku_so) only logs in to initialize the normal user's pin. the so pin is the empty string. the nss cryptographic module doesn't allow the so to log in if the normal user's pin is already initialized. return value nsc_login() returns the following return codes. ckr_ok: the user logged in successfully. ckr_device_
error: the token is in the
error state. ckr_host_memory: memory allocation failed. ckr_pin_incorrect: the pin is incorrect. ckr_pin_len_range: the pin is too long (ulpinlen is greater than 255).the function should return ckr_pin_incorrect in this case. ckr_session_handle_invalid: the session handle is invalid. ckr_user_already_logged_in: the user is already logged in. ckr_user_type_invalid the t...
NSS_Initialize
i.e., that support locking - either os locking or nss-provided locks . if a pkcs#11 module isn't thread-safe, don't serialize its calls; just don't load it instead. this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, the java sunpkcs11 provider. nss_init_pk11reload - ignore the ckr_cryptoki_already_initialized
error when loading pkcs#11 modules. this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, java sunpkcs11 provider. nss_init_nopk11finalize - never call c_finalize on any pkcs#11 module. this may be necessary in order to ensure continuous operation and proper shutdown sequence if another piece of code is using the same ...
NSS functions
later port_arenarelease mxr 3.2 and later port_arenastrdup mxr 3.2 and later port_arenaunmark mxr 3.2 and later port_arenazalloc mxr 3.2 and later port_free mxr 3.2 and later port_freearena mxr 3.2 and later port_get
error mxr 3.2 and later port_newarena mxr 3.2 and later port_realloc mxr 3.2 and later port_set
error mxr 3.2 and later port_setucs2_asciiconversionfunction mxr 3.2 and later port_setucs2_utf8conversionfunction mxr 3.2 and later port_setu...
NSS tools : modutil
(pin). -chkfips verify whether the module is in the given fips mode. true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode. -create create new certificate, key, and module databases. use the -dbdir directory argument to specify a directory. if any of these databases already exist in a specified directory, modutil returns an
error message. -default modulename specify the security mechanisms for which the named module will be a default provider. the security mechanisms are specified with the -mechanisms argument. -delete modulename delete the named module. the default nss pkcs #11 module cannot be deleted. -disable modulename disable all slots on the named module. use the -slot argument to disable a specific slot.
troubleshoot.html
having /usr/ucb/bin in the path before /usr/ccs/bin breaks the build on 64-bit solaris. the solaris compiler needs to be workshop-5.0 or greater. the 64-bit builds don't support gcc. if the build fails early on the gmakein coreconf try updating your cvs tree with -p: cd mozilla cvs update -p building a 32-bit version on a 64-bit may fail with: /usr/include/features.h:324:26: fatal
error: bits/predefs.h: no such file or directory in this case remember to set use_64=1 testing nss the ssl stress test opens 2,048 tcp connections in quick succession. kernel data structures may remain allocated for these connections for up to two minutes. some systems may not be configured to allow this many simultaneous connections by default; if the stress tests fail, try increasing the ...
sslintro.html
already connected. for an ssl socket that is configured before it is connected, ssl figures this out when the application calls pr_connect or pr_accept. if the socket is already connected before ssl gets involved, you must provide this extra hint. functions that can be used by both clients and servers during communication include the following: pr_send or pr_write pr_read or pr_recv pr_get
error pr_getpeername pr_sleep pr_malloc pr_free pr_poll pr_now pr_intervaltomilliseconds pr_millisecondstointerval pr_shutdown pr_close ssl_invalidatesession after establishing a connection, an application first calls pr_send, pr_recv, pr_read, pr_write, or ssl_forcehandshake to initiate the handshake. the application's protocol (for example, http) determines which end has respon...
Utility functions
later port_arenarelease mxr 3.2 and later port_arenastrdup mxr 3.2 and later port_arenaunmark mxr 3.2 and later port_arenazalloc mxr 3.2 and later port_free mxr 3.2 and later port_freearena mxr 3.2 and later port_get
error mxr 3.2 and later port_newarena mxr 3.2 and later port_realloc mxr 3.2 and later port_set
error mxr 3.2 and later port_setucs2_asciiconversionfunction mxr 3.2 and later port_setucs2_utf8conversionfunction mxr 3.2 and later port_setu...
NSS Tools certutil-tasks
mistakes with command-line options just print a usage message. improve certificate listings. allow for sorting by name and trust. sorting by trust will return ca certs first. allow listing and lookup of keys by index and nickname. improve coherence of key and certificate nicknames. remove keys "stranded" without a certificate (except for the imminent (????) encryption key for password files). support importing keys from a file. improve hardware token support. ...
NSS Tools modutil
ions and arguments options specify an action. option arguments modify an action. the options and arguments for the modutil command are defined as follows: options -create create new secmod.db, key3.db, and cert8.db files. use the -dbdir directory argument to specify a directory. if any of these databases already exist in a specified directory, the security module database tool displays an
error message. -list [modulename] display basic information about the contents of the secmod.db file. use modulename to display detailed information about a particular module and its slots and tokens. -add modulename add the named pkcs #11 module to the database. use this option with the -libfile, -ciphers, and -mechanisms arguments. -jar jar-file add a new pkcs #11 module to the database using t...
NSS tools : modutil
s mode. true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode. -create create new certificate, key, and module databases. use the -dbdir directory argument to specify a directory. if any of these databases already exist in a specified directory, modutil returns an
error message. -default modulename specify the security mechanisms for which the named module will be a default provider. the security mechanisms are specified with the -mechanisms argument. -delete modulename delete the named module. the default nss pkcs #11 module cannot be deleted. -disable modulename disable all slots ...
Network Security Services
security services provides an overview of the nss libraries and what you need to know to use them. nss ssl public functions summarizes the ssl apis exported by the nss shared libraries. nss ssl reference api used to invoke ssl operations. nss api guidelines explains how the libraries and code are organized, and guidelines for developing code (naming conventions,
error handling, thread safety, etc.) nss technical notes links to nss technical notes, which provide latest information about new nss features and supplementary documentation for advanced topics in programming with nss. tools, testing, and other technical details build instructions for nss describe how to check out and build nss releases. nss develope...
Necko Interfaces Overview
nstance via newchannel method nsistreamlistener : nsirequestobserver implemented by the consumer of a nsichannel instance passed to nsichannel::asyncopen method nsirequestobserver::onstartrequest - notifies start of async download nsistreamlistener::ondataavailable - notifies presence of downloaded data nsirequestobserver::onstoprequest - notifies completion of async download, possibly w/
error nsiloadgroup : nsirequest attribute of a nsirequest channel impl adds itself to its load group during invocation of asyncopen channel impl removes itself from its load group when download completes load groups in gecko own all channels used to load a particular page (until the channels complete) all channels owned by a load group can be canceled at once via the load group's nsirequest::ca...
Tutorial: Embedding Rhino
ments this code is standard java and not specific to rhino. it just collects all the arguments and concatenates them together. string s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } evaluating a script the code object result = cx.evaluatestring(scope, s, "<cmd>", 1, null); uses the context cx to evaluate a string. evaluation of the script looks up variables in scope, and
errors will be reported with the filename <cmd> and line number 1. printing the result the code system.out.println(cx.tostring(result)); prints the result of evaluating the script (contained in the variable result). result could be a string, javascript object, or other values. the tostring method converts any javascript value to a string. exiting the context the code } finally { context.exi...
Rhino overview
ine and influence aspects of the way it is evaluated. these features are generally not broadly useful, yet they impose significant constraints on implementations that hamper or prevent optimization. the deprecated features are the __proto__ and __parent__ properties, and the constructors with, closure, and call. attempts to invoke these constructors with the language version 1.4 will result in an
error. for other versions, a warning will be generated. internationalization the messages reported by the javascript engine are by default retrieved from the property file org/mozilla/javascript/resources/messages.properties. if other properties files with extensions corresponding to the current locale exist, they will be used instead. javascript language versions some behavior in the javascript en...
Rhino shell
converted to string and sent to the process as its input. if not specified, no input is provided to the process. output - the process output instead of java.lang.system.out. if it is not instance of java.io.outputstream, the process output is read, converted to a string, appended to the output property value converted to string and put as the new value of the output property. 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) s...
Creating JavaScript jstest reftests
-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 allow you to distinguish th...
How to embed the JavaScript engine
target = findeventtargetat(cx, global, x, y); event = neweventobject(cx, "click", x, y); argv[0].setobjectornull(event); /* to emulate the dom, you might want to try "onclick" too. */ ok = js_callfunctionname(cx, target, "onclick", argv, &rval); /* now test rval to see whether we should cancel the event. */ if (rval.isboolean() && !rval.toboolean()) cancelevent(event); again, i've elided
error checking (such as testing for !ok after the call), and i've faked up some c event management routines that emulate the dom's convention of canceling an event if its handler returns false. original document information author: brendan eich ...
Self-hosted builtins in SpiderMonkey
set of c++-implemented builtins is installed via the intrinsic_functions array in selfhosting.cpp, as described below. using the same mechanism, c++-implemented helper functions are made available to self-hosted code. some general-purpose functions provided in this way are: the abstract operations toobject, tointeger, and iscallable specified in the ecmascript language specification. throwtype
error, throwrange
error, throwsyntax
error, which self-hosted code should use instead of throw so that the
error message is specified in js.msg and can be localized. the makeconstructible function described above. the file utilities.js provides some additional, js-implemented helper functions. of note, it provides implementations of list and record, types defined in the ecmascript specifications that ...
BOOLEAN_TO_JSVAL
please use js::booleanvalue/js::truevalue/js::falsevalue instead in spidermonkey 45 or later. syntax jsval boolean_to_jsval(bool b); name type description b bool c integer value to be converted to a boolean jsval. ...
JS::Add*Root
rce location of the call to js::addnamed*root for debugging purposes. needs the example for typical usage of the name parameter. all the js::add*root methods are idempotent: multiple calls for the same address will add only one root. correspondingly, only a single js::remove*root is required to unroot the location. on success, these functions return true. otherwise they report an out of memory
error and return false. see also mxr id search for js::addvalueroot mxr id search for js::addstringroot mxr id search for js::addobjectroot mxr id search for js::addnamedvalueroot mxr id search for js::addnamedvaluerootrt mxr id search for js::addnamedstringroot mxr id search for js::addnamedobjectroot mxr id search for js::addnamedscriptroot bug 912581 bug 1107639 ...
JS::CallArgs
signed number of argument. (2nd argument of jsnative) vp js::value * a pointer to the argument value array. (3nd argument of jsnative) methods methods of js::callargs method description bool requireatleast(jscontext *cx, const char *fnname, unsigned required) returns true if there are at least required arguments passed in. if false, it reports an
error message on the context. methods inherited from js::callargsbase method description unsigned length() const returns the number of arguments.. js::mutablehandlevalue operator[](unsigned i) const returns the i-th zero-indexed argument. js::handlevalue get(unsigned i) const returns the i-th zero-indexed argument, or undefined if there's no such ...
JS::GetFirstArgumentAsTypeHint
nction call. behavior jstype * receives the result of conversion. see below. description js::getfirstargumentastypehint converts first argument of @@toprimitive method to jstype. if args.get(0) is one of the strings "string", "number", or "default", set *result to jstype_string, jstype_number, or jstype_void accordingly and return true. otherwise, return false with a type
error pending. see also mxr id search for js::getfirstargumentastypehint bug 1054756 - added ...
JS::GetSelfHostedFunction
andle<jsid> a pointer to jsid of the name to assign to the new function. nargs unsigned number of arguments the function expects. description js::getselfhostedfunction creates a new javascript function implemented in self-hosted javascript. on success, js::getselfhostedfunction returns a pointer to the newly created function. otherwise, it reports an out-of-memory
error and returns null. see also mxr id search for js::getselfhostedfunction bug 1140573 ...
JS::Handle
a js::rooted<t>. functions which take gc things or values as arguments and need to root those arguments should generally use handles for those arguments and avoid any explicit rooting. this has two benefits. first, when several such functions call each other then redundant rooting of multiple copies of the gc thing can be avoided. second, if the caller does not pass a rooted value a compile
error will be generated, which is quicker and easier to fix than when relying on a separate rooting analysis. if you want to add additional methods to js::handle for a specific specialization, define a js::handlebase<t> specialization containing them. there are typedefs available for the main types: namespace js { typedef handle<jsfunction*> handlefunction; typedef handle<jsid> handleid; type...
JS::NewFunctionFromSpec
ntid(cx, fs->name, &id). description js::newfunctionfromspec creates a new function based on the given jsfunctionspec, *fs. id is the result of a successful call to propertyspecnametopermanentid(cx, fs->name, &id). unlike js_definefunctions, this does not treat fs as an array. *fs must not be js_fs_end. on success, js::newfunctionfromspec returns a pointer to newly created function. on
error, it returns nullptr. see also mxr id search for js::newfunctionfromspec js_definefunctions bug 1054756 - added ...
JS::OrdinaryToPrimitive
6 draft rev 28 (2014 oct 14) 7.1.1, second algorithm. most users should not call this -- use js::tonumber, js::toboolean, or js::tostring instead. this should only be called from custom convert hooks. it implements the default conversion behavior shared by most objects in js, so it's useful as a fallback. on success, js::ordinarytoprimitive stores the converted value in *vp and returns true. on
error or exception, it returns false, and the value left in *vp is undefined. see also mxr id search for js::ordinarytoprimitive js::tonumber js::toboolean js::tostring bug 1103152 ...
JS::ToInt32
ext. 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
s_threadsafe build, the caller must be in a request on this jscontext. v js::handlevalue the value to convert. out int64_t * out parameter. on success, *out receives the converted floating-point value. description js::toint64 converts a javascript value to a signed 64bit integer. on success, js::toint64 stores the converted value in *out and returns true. on
error or exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::toint64 bug 742188 ...
JS::ToNumber
this jscontext. v js::handlevalue the value to convert. out double * out parameter. on success, *out receives the converted floating-point value. description js::tonumber converts a javascript value to a number. it implements the tonumber operator described in ecma 262-3 §9.3. on success, js::tonumber stores the converted value in *out and returns true. on
error or exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::tonumber bug 739541 ...
JS::ToPrimitive
orresponding 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
onversion. 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
v js::handlevalue the value to convert. out int32_t * out parameter. on success, *out receives the converted floating-point value. description js::touint32 converts a javascript value to an unsigned 32bit integer. it implements the touint32 operator described in ecma 262-3 §9.5. on success, js::touint32 stores the converted value in *out and returns true. on
error or exception, it returns false, and the value left in *out is undefined. see also mxr id search for js::touint32 bug 739541 ...
JS::ToUint64
readsafe 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
returns true if the value is a primitive value -- that is, not an object. it is equivalent to !val.isobject(). val.isnullorundefined() returns true if the value is either null or undefined. val.isgcthing() returns true if a js value has a type that is subject to garbage collection. the are two major issues to be aware of when using js::value. js::value is not inherently type-safe it is an
error to call any accessor method on a value of a non-matching type: val.toint32() must only be called if val.isint32(), val.tostring() must only be called if val.isstring(), and so on. in particular, note that it is an
error to call val.toobject() when val.isnull(). the now-deprecated jsval methods allowed jsval_to_object(val) when jsval_is_null(val), but this was a source of constant bugs. val.toobj...
JSBool
s feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. every instance of jsbool has been replaced by bool. js_true has been replaced by just true and in the same way js_false by false. jsbool is the return type of many jsapi functions and callbacks. js_true indicates success; js_false indicates an
error or exception occurred. jsbool is an integer type. js_true is (jsbool) 1 and js_false is (jsbool) 0. these values must not be used as jsvals. instead, use jsval_true and jsval_false, and use boolean_to_jsval and jsval_to_boolean to convert. ...
JSCheckAccessOp
* the 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 secu...
JSHasInstanceOp
ext in which 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 ...
JSIteratorOp
creation should take place. obj jsobject * pointer to the object to iterate over. keysonly jsbool if true, the iterator should yield keys only, not [key, value] pairs. description the javascript engine calls the jsextendedclass.iteratorobject callback to create an iterator object for a given object. the callback should return an iterator object or null if an
error or exception occurred on cx. see also bug 909178 ...
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
ltvalue]] 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.val...
JSObjectOps.getAttributes
ributes are 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
me type 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 reflect...
JSObjectOps.getRequiredSlot
object whose slot we access. slot uint32 the index of the slot to access. see note below. v jsval the value to store in the slot, for jssetrequiredslotop. description get and set a required slot, one that should already have been allocated. these operations are infallible, so required slots must be pre-allocated, or implementations must suppress out-of-memory
errors. the native ops (js_objectops, see js/src/jsobj.cpp) access slots reserved by including a call to the jsclass_has_reserved_slots(n) macro in the jsclass.flags initializer. note: the slot parameter is a zero-based index into obj slots, unlike the index parameter to the js_getreservedslot and js_setreservedslot api entry points, which is a zero-based index into the jsclass_reserved_slots(clasp) r...
JSObjectOps.lookupProperty
to look up. 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 jsat...
JSObjectOps.newObjectMap
by including the non-public header jsobj.h, or obtain the default newobjectmapop by calling the jsclass.getobjectops callback of a standard jsclass. create a new instance of (a concrete subclass of) jsobjectmap (see jsobj.h), with the nrefs and ops members initialized from the same-named parameters, and with the nslots and freeslot members initialized according to ops and clasp. return null on
error, non-null on success. jsobjectmaps are reference-counted by generic code in the engine. usually, the nrefs parameter to jsobjectops.newobjectmap will be 1, to count the ref returned to the caller on success. after a successful construction, some number of js_holdobjectmap and js_dropobjectmap calls ensue. when nrefs reaches 0 due to a js_dropobjectmap call, jsobjectops.destroyobjectmap will be c...
JSObjectPrincipalsFinder
jsclass.checkaccess hooks to call these functions, the object principals 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 ...
JSPrincipalsTranscoder
jsprincipalstranscoder if it intends to serialize or deserialize principals. the callback xdr-encodes or -decodes a principals instance, based on whether xdr->mode is jsxdr_encode, in which case *principalsp should be encoded; or jsxdr_decode, in which case implementations must return a held (via jsprincipals_hold), non-null *principalsp out parameter. return js_true on success, js_false on any
error, which the implementation must have reported. mxr id search for jsprincipalstranscoder ...
JSPropertyOp
getter or setter; or it may be installed on a jsclass to hook property gets, sets, or adds. these different cases are described in more detail in the sections below. if a jspropertyop or jsstrictpropertyop does nothing and returns true, then property get, set, or add is unaffected. it proceeds as normal. each of these callbacks may veto the ongoing property operation by optionally reporting an
error or raising an exception and then returning false. the operation then fails, and the
error is propagated to the caller. otherwise the callback must return true, and the property operation proceeds. getters and setters when a jsapi 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 proper...
JSResolveOp
by defining it directly in obj. lazy properties are those reflected from some peer native property space (e.g., the dom attributes for a given node reflected as obj) on demand. the callback must set *resolvedp to true and return true if the property is resolved, or set *resolvedp to false and return true if the object has no lazy property with the given id; or return false to indicate any other
error. obsolete since jsapi 36 the callback must return true if the property is resolved, or if the object has no lazy property with the given id; or false to indicate any other
error. note: jsnewresolveop provides a cheaper way to resolve lazy properties. jsclass hooks jsclass offers the following hook: jsclass.resolve callback is called when a property is not found on an object. it can be u...
JSRuntime
ript 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 object and the cont...
JSVAL_TO_BOOLEAN
syntax jsbool jsval_to_boolean(jsval v); description jsval_to_boolean casts the value v to a c integer, either 0 or 1. as a precondition, jsval_is_boolean(v) must be true. ...
JSVAL_TO_DOUBLE
syntax jsdouble jsval_to_double(jsval v); description jsval_to_double casts a specified js value, v, to a c floating-point number of type jsdouble. ...
JSVAL_TO_INT
syntax jsval_to_int(v) description jsval_to_int converts a specified integer jsval, v, to the corresponding c integer value. if v is any other type of value, the result is unspecified. ...
JS_AddArgumentFormatter
e if the conversion function should convert from c values to jsval values. vpp jsval ** in-out parameter. a pointer into an array of jsval values. app va_list * in-out parameter. a pointer to an argument pointer, used to retrieve pointers to c values. callback description the conversion function should return true on success, and return false after reporting an
error or detecting an already-reported
error. for a given format string, for example "aa", the formatter is called from js_convertargumentsva like so: formatter(cx, "aa...", js_true, &sp, &ap); sp points into the arguments array on the js stack, while ap points into the stdarg.h va_list on the c stack. the js_true passed for fromjs tells the formatter to convert zero or more jsvals at sp to zero or mo...
JS_Add*Root
of the call to js_addnamedroot for debugging purposes. js_dumpnamedroots can be used to access this information from a debugger. all the js_add*root methods are idempotent: multiple calls for the same address will add only one root. correspondingly, only a single js_removeroot is required to unroot the location. on success, these functions return js_true. otherwise they report an out of memory
error and return js_false. see also mxr id search for js_addvalueroot mxr id search for js_addstringroot mxr id search for js_addobjectroot mxr id search for js_addnamedvalueroot mxr id search for js_addnamedstringroot mxr id search for js_addnamedobjectroot bug 912581 ...
JS_AliasElement
r support this function. an alias does not replace an element's current index number; it supplements it, providing a second way to reference the element. if the alias is successfully created and associated with the property, js_aliaselement returns js_true. adding an alias element does not change the element array length. if the property name you specify does not exist, js_aliaselement reports an
error, and returns js_false. if the element is currently out of scope, already exists, or the alias itself cannot be assigned to the element, js_aliaselement does not report an
error, but returns js_false. once you create an alias, you can reassign it to other elements as needed. aliases can also be deleted. deleting an alias does not delete the element to which it refers. see also js_defineelement...
JS_AliasProperty
notes this feature has been removed. an alias does not replace a property's name; it supplements it, providing a second way to reference a property. if the alias is successfully created and associated with the property, js_aliasproperty returns js_true. creating an alias does not change the length of the property array. if the property name you specify does not exist, js_aliasproperty reports an
error, and returns js_false. if the property is currently out of scope, already exists, or the alias itself cannot be assigned to the property, js_aliasproperty does not report an
error, but returns js_false. once you create an alias, you can reassign it to other properties as needed. aliases can also be deleted. deleting an alias does not delete the property to which it refers. see also js_definepro...
JS_CheckAccess
callback, then it is called to perform the check. otherwise, if a runtime-wide check-object-access callback has been installed by calling js_setcheckobjectaccesscallback, then that is called to perform the check. otherwise, access is granted. on success, js_checkaccess returns js_true, *vp is set to the current value of the specified property, and *attrsp is set to the property's attributes. on
error or exception, including if access is denied, js_checkaccess returns js_false, and the values left in *vp and *attrsp are undefined. mxr id search for js_checkaccess ...
JS_ClearPendingException
on if the most recently thrown exception in cx has not yet been caught or cleared.) when any jsapi call fails with an exception, the caller must either use js_clearpendingexception to catch the exception; or return false to allow the exception to propagate to the caller. 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_isexceptionpending or js_getpendingexception to check for a pending exception. see examples in the jsapi phrasebook. see also mxr id search for js_clearpendingexception js_getpendingexception js_isexceptionpending js_reportpendingexception js_setpendingexception ...
JS_CompareStrings
result int32_t * the out parameter. see description for value of *result. description js_comparestrings compares two js strings, str1 and str2. if the strings are identical in content and length, js_comparestrings stores 0 in *result. if str1 is less than str2, *result is less than 0. if str1 is greater than str2, *result is greater than 0. on success the function returns js_true. on
error, it returns js_false and the value in result is unchanged. this function imposes a total order on all javascript strings, the same order imposed by the javascript string comparison operators (<, <=, >, >=), as described in ecma 262-3 § 11.8.5. as the standard says: the comparison of strings uses a simple lexicographic ordering on sequences of code point value values. there is no attempt to use...
JS_CompileScript
for execution. js_compileucscript is the unicode version of the function. the script is associated with a js object. ascii and chars are the string containing the text of the script. length indicates the size of the text version of the script in characters. on success, js_compilescript and js_compileucscript stores the newly compiled script to *script and returns true. otherwise, they report an
error, stores null to *script, and return false. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compilescript mxr id search for js_compileucscript js::evaluate js::compileoffthread js::compilefunction js_executescript js_decompilescript bug 1143793 -- removed obj parameter ...
JS_DecompileScript
t be in a request on this jscontext. script js::handle<jsscript*> script or function to decompile. description js_decompilescript returns the source code of script. if script is a function, it calls js_decompilefunction. otherwise, it returns the original source code of the script. if the script is not cached, it tries to load the source from file, and returns nullptr if an
error happened while loading. if successful, js_decompilescript returns a string containing the source code of the script. otherwise, it returns a string containing "[no source]". from spidermonkey 17, this does not actually decompile the script, but returns the original source code (bug 761723). see also mxr id search for js_decompilescript js::compile js_compilescript js_decompilefunction ...
JS_DefaultValue
date objects). objects with a custom jsclass specified by the embedder will invoke that class's convert hook, which must convert the object to a primitive value, to determine the primitive result of conversion. behavior when the convert hook is js_convertstub is identical to that for objects defined by ecmascript. on success, js_defaultvalue stores the converted value in *vp and returns true. on
error or exception, it returns false, and the value left in *vp is undefined. see also mxr id search for js_defaultvalue js::toprimitive bug 1054756 - renamed to js::toprimitive ...
JS_DefineFunction
hat is to 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
must contain 0 values. (the macro js_fs_end can be used for the last element.) js_definefunctions creates one function for each non-zero element in the array. propertydefinitionbehavior is used to select if properties with jsprop_define_late flag should be defined on the object. normal jsapi consumers probably always want defineallproperties here. on success, js_definefunctions returns true. on
error or exception, it stops defining functions and returns false. see also mxr id search for js_definefunctions js_callfunctionname js_defineobject js_defineproperties js_newfunction bug 959787 - make fs type to const bug 825199 - added propertydefinitionbehavior ...
JS_DefineObject
a new property 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. us...
JS_DefineProperty
callback from obj's class. if attrs contains the jsprop_getter (or jsprop_setter) flag, then getter (or setter) must point to a javascript function, not a c/c++ function. that is, it must be a jsobject * that points to a javascript function, cast to type jspropertyop. for more about javascript getters and setters, see defining getters and setters. on success, js_defineproperty returns true. on
error or exception, it returns false. see also mxr id search for js_defineproperty mxr id search for js_defineucproperty mxr id search for js_definepropertybyid js_defineelement bug 461163 bug 1113369 -- added desc and result parameters ...
JS_DeleteElement
n object, obj. if an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. if deletion is successful, js_deleteelement returns true. otherwise it returns false. for javascript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, js_deleteelement reports the
error before returning false. for javascript 1.3 and later, the attempt is silently ignored. to truncate an array, use js_setarraylength. to remove all elements and properties from an object, call js_clearscope. see also mxr id search for js_deleteelement bug 1113369 -- added result parameter ...
JS_DeleteElement2
tion is successful, js_deleteelement2 stores true to *succeeded and returns true. otherwise it returns false and the value of *succeeded is undefined. notes per the ecma standard, js_deleteelement2 removes read-only properties from objects as long as they are not also permanent. for javascript 1.2 and earlier, if deletion fails because the property is permanent, js_deleteelement2 reports the
error and returns false. for javascript 1.3, the attempt is silently ignored. in both these cases, *succeeded will receive the stored value of the property that was not deleted. to remove all properties from an object, call js_clearscope. see also mxr id search for js_deleteelement2 bug 1113369 -- added result parameter ...
JS_Enumerate
t is not 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 unre...
JS_FlattenString
ax jsflatstring * js_flattenstring(jscontext *cx, jsstring *str); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * the string to flatten. description js_flattenstring flattens a string str and returns a pointer to jsflatstring. to catch
errors, an opaque jsflatstring type is returned. note: the input and output of js_flattenstring() are the same actual gc-thing so only one needs to be rooted. if a jsstring is known to be flat, you can use js_assert_string_is_flat to make a debug-checked cast. example: // in a fallible situation jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) return false; js_assert(fstr == js_assert_st...
JS_ForwardGetPropertyTo
iption js_forwardgetpropertyto is the base implementation of js_getproperty, js_getucproperty, js_getpropertybyid etc, where onbehalfof is same to obj. onbehalfof is receiver in [[get]] internal method of proxy, defined in es2015 draft spec (rev 29, 9.5.8). on success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and return true. on an
error or exception, these functions return false, and the value left in *vp is undefined. see also mxr id search for js_forwardgetpropertyto js_getproperty bug 698551 ...
JS_GetArrayLength
arraylength gets the .length property of obj as though by calling js_getproperty and converts it to a 32-bit unsigned integer. if obj is an array (see js_isarrayobject), this is guaranteed to succeed, because the .length property of an array is always a number and can't be deleted or redefined. on success, js_getarraylength stores the length in *lengthp and returns true. on failure, it reports an
error and returns false, and the value left in *lengthp is undefined. see also mxr id search for js_getarraylength js_getelement js_setarraylength ...
JS_GetArrayPrototype
ext * pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose array.prototype is being retrieved. description js_getarrayprototype() retrieves the original array.prototype of a specified object, obj. if an
error occurs, it returns null. note: this expression might have different values over time if the global array property is modified, but this method returns only the original value. see also mxr id search for js_getarrayprototype bug 872043 ...
JS_GetConstructor
. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle<jsobject*> the object whose constructor is to be returned. description js_getconstructor retrieves the constructor property of a given object, obj. if the result is a function object, js_getconstructor returns a pointer to that object. otherwise, it reports an
error and returns null. to get an object's prototype, use js_getprototype. to get an object's parent, use js_getparent. see also mxr id search for js_getconstructor ...
JS_GetElement
t parameter. on success, *vp receives the current value of the element, if it exists, and undefined otherwise. description js_getelement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_getelement sets *vp to the element's current value. if not, it sets *vp to undefined and returns true (to indicate no
error occurred). if the search fails with an
error or exception, js_getelement returns false, and the value left in *vp is undefined. see also mxr id search for js_getelement js_defineelement js_deleteelement js_getarraylength js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_GetFunctionArity
, fun. this is the same as the function object's arity property, if that property has not been overwritten. specifically, if fun is a native function, the result is the value that was passed to the nargs parameter of js_definefunction. otherwise fun is implemented in javascript, and the result is the number of identifiers in its formal parameter list (see ecma 262-3 §13). note that it is not an
error per se to call a javascript function with more or fewer actual arguments than its arity. see also mxr id search for js_getfunctionarity js_definefunction ...
JS_GetFunctionPrototype
pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose function.prototype is being retrieved. description js_getfunctionprototype() retrieves the original function.prototype of a specified object, obj. if an
error occurs, it returns null. note: this expression might have different values over time if the global function property is modified, but this method returns only the original value. see also mxr id search for js_getfunctionprototype bug 726182 ...
JS_GetLocaleCallbacks
syntax jslocalecallbacks * js_getlocalecallbacks(jsruntime *rt); void js_setlocalecallbacks(jsruntime *rt, jslocalecallbacks *callbacks); 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. callbacks jslocalecallbacks * pointer to a jslocalecallbacks struct. ...
JS_GetObjectPrototype
* pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose object.prototype is being retrieved. description js_getobjectprototype() retrieves the original object.prototype of a specified object, obj. if an
error occurs, it returns null. note: this expression might have different values over time if the global object property is modified, but this method returns only the original value. see also mxr id search for js_getobjectprototype bug 725888 ...
JS_GetPropertyDefault
evalue 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_GetScopeChain
t in any function, it's running in a scope that was passed to js_executescript or a similar function by the application. this scope chain may or may not contain cx's current global object. if any code is currently executing in cx, js_getscopechain returns a pointer to the first jsobject on the current scope chain. otherwise, if cx has a global object, js_getscopechain returns that. otherwise, an
error is reported and js_getscopechain returns null. to walk the scope chain, use js_getparent. see also mxr id search for js_getscopechain js_getglobalforscopechain bug 632064 ...
JS_HasArrayLength
bject, obj, has a length property. if the property exists, js_hasarraylength stores the current value of the property in *lengthp. on success, js_hasarraylength returns js_true, and *lengthp receives the current value of the length property. on failure, js_hasarraylength returns js_false, and the value left in *lengthp is undefined. this function differs from js_getarraylength in the treatment of
errors and unusual cases, like when an object's length is negative or not a number. this function may return js_false without having reported any
error or exception. see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement bug 657298 ...
JS_HasElement
of the element to look up. foundp bool * out parameter. on success, it stores true to *foundp, false otherwise. description js_haselement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_haselement sets *foundp to true. if not, it sets *foundp to false and returns true (to indicate no
error occurred). if the search fails with an
error or exception, js_haselement returns false, and 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
<js::value> 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_HasOwnProperty
obj, for an own property with the specified name. it behaves like the javascript expression object.hasownproperty(obj, name). js_hasownpropertybyid is the same but takes a js::handleid for the property name. if the property exists, this function sets *foundp to true and returns true. if the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no
error occurred). if an
error occurs during the search, the function returns false, and the value of *foundp is undefined. see also mxr id search for js_hasownproperty mxr id search for js_hasownpropertybyid bug 1163423 ...
JS_HasProperty
with the specified name. it behaves like the javascript expression name in obj. js_hasucproperty is the corresponding unicode api. js_haspropertybyid is the same but takes a js::handleid for the property name. if the property exists, this function sets *foundp to true and returns true. if the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no
error occurred). if an
error occurs during the search, the function returns false, and the value of *foundp is undefined. see also mxr id search for js_hasproperty mxr id search for js_hasucproperty mxr id search for js_haspropertybyid bug 461163 ...
JS_InternString
f all existing interned strings. if an interned string already exists with the desired value, these functions return the existing string. otherwise a new string is created and added to the table. strings created with these functions are protected from garbage collection for the lifetime of the jsruntime. on success, these functions return a pointer to the interned string. otherwise they report an
error and return null. see also mxr id search for js_internstring mxr id search for js_internstringn mxr id search for js_internucstring mxr id search for js_internucstringn js_getemptystringvalue js_newstringcopyn js_newstringcopyz js_newucstring js_newucstringcopyn js_newucstringcopyz js_valuetostring ...
JS_LookupElement
dard also specifies this behavior: see ecma 262-3 §11.2.1, step 6. so any call to js_lookupelement is equivalent to a call to js_lookupproperty passing a numeric string for the name. if the property obj[index] exists, js_lookupelement sets *vp to the property's stored value and returns true. if no such property exists, js_lookupelement sets *vp to undefined and returns true (to indicate that no
error occurred). on
error or exception, js_lookupelement returns false, and the value left in *vp is undefined. js_lookupelement does not distinguish between a property with a value of undefined and a property that does not exist. see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_newarrayobject js_setarraylength js_setelement bug 1094176 ...
JS_New
32 description js_new creates a new object as though by using the new operator, as described in ecma 262-3 §11.2.2. js_new(cx, ctor, args) is equivalent to the javascript expression new ctor(...args), and js_new(cx, ctor, argc, argv) is equivalent to the javascript expression new ctor(argv[0], argv[1], ... argv[argc-1]). if ctor is not an object that can be used as a constructor, a type
error is raised. on success, js_new returns a pointer to the new object. on
error, it returns null. see also mxr id search for js_new bug 480850 - added bug 959787 - added args parameter ...
JS_NewArrayObject
defines an enumerable array element with the value contents[i] on the new array. js_newarrayobject with length parameter creates a new array object with the specified length; the result is like the javascript expression new array(length). the new array has the specified length, but it doesn't have any elements. on success, js_newarrayobject returns the new array object. otherwise it reports an
error as though by calling js_reportoutofmemory and returns null. obsolete since jsapi 30. js_newarrayobject with length parameter creates a new array object with the specified length. if vector is non-null, then for each index i from 0 to length - 1, js_newarrayobject defines an enumerable array element with the value vector[i] on the new array. (this means that if length is nonzero and vector is n...
JS_NewFunction
ion can be called as a constructor. parent may be used to specify the new function's parent; null is usually the right thing here. name is the name to assign to the function. if name is null, the new function has no name. (js_getfunctionid, passed the new function, will return null.) on success, js_newfunction returns a pointer to the newly created function. otherwise it reports an out-of-memory
error and returns null. see also mxr id search for js_newfunction mxr id search for js_newfunctionbyid js_callfunction js_callfunctionname js_callfunctionvalue js_compilefunction js_compileucfunction js_definefunction js_definefunctions js_getfunctionname js_getfunctionobject bug 607695 - added js_newfunctionbyid bug 1140573 - removed parent parameter bug 1054756 - removed js_newfuncti...
JS_NewGlobalObject
way the cookie crumbles. if callers have no additional state on the global to set up, they may pass fireonnewglobalhook to js_newglobalobject, which causes that function to fire the hook as its final act before returning. otherwise, callers should pass dontfireonnewglobalhook, which means that they are responsible for invoking js_fireonnewglobalobject upon successfully creating the global. if an
error occurs and the operation aborts, callers should skip firing the hook. but otherwise, callers must take care to fire the hook exactly once before compiling any script in the global's scope (we have assertions in place to enforce this). this lets us be sure that debugger clients never miss breakpoints. enum onnewglobalhookoption { fireonnewglobalhook, dontfireonnewglobalhook }; see also ...
JS_NewPropertyIterator
o iterate over the enumerable own properties of obj, in arbitrary order. (this differs from longstanding for..in loop order, which uses the order in which obj's properties were defined. note also that while for..in includes properties inherited from prototypes, iterator objects do not.) on success, this returns an iterator object that can be passed to js_nextproperty to fetch the property ids. on
error, it returns null. the iterator object created by this function is not a javascript iterator. it is an opaque object with no properties visible from javascript. see also bug 1081660 ...
JS_NewUCString
version 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_NewStringCopyZ
char * or const char16_t * pointer to the character array containing the text for the js string to create; or null. description js_newstringcopyz allocates space for a new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string. on success, js_newstringcopyz returns a pointer to the new javascript string. on
error, it returns null. if s is null, an empty javascript string is returned. js_newstringcopy(cx, s) is equivalent to js_newstringcopyn(cx, s, strlen(s)) when s is a null-terminated string. see also mxr id search for js_newstringcopyz mxr id search for js_newucstringcopyz js_getemptystringvalue js_newstringcopyn js_newucstringcopyn js_valuetostring ...
JS_NextProperty
idp js::mutablehandleid out parameter. on success, *idp receives the name or index of the next property name; or jsid_void if there are no more enumerable properties to visit. description on success, js_nextproperty returns true, with *idp containing the id of the next enumerable own property to visit using iterobj, or jsid_void if there is no such property left to visit. on
error, it returns false, and the value left in *idp is undefined. see also bug 1081660 ...
JS_ParseJSON
t on this jscontext. ch jsobject * the object to be searched. chars const jschar * the characters of the string. len uint32 the length of the string. index jsint (in js_parsejsonwithreviver only) a reviver function to apply to the created value after parsing; see json.parse. vp jsval * out parameter. *vp receives the value after parsing (and optionally, processing by the reviver). if an
error occurs, the value left in *vp is undefined. description use these functions to parse a sequence of characters as json. the parsing rules applied by these methods are exactly those specified by ecmascript 5. various json extensions like trailing commas, unquoted property names, more generous number parsing, and so on are not supported. mxr id search for js_parsejson mxr id search for js_parse...
JS_PushArguments
ject (or 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_ResolveStandardClass
ise. description js_resolvestandardclass resolves id, which must contain either a string or an int, to a standard class name in obj if possible, defining the class's constructor and/or prototype and storing true in *resolved. if id does not name a standard class or a top-level property induced by initializing a standard class, store false in *resolved and just return true. return false on
error, as usual for bool result-typed api entry points. this api can be called directly from a global object class's resolve op, to define standard classes lazily. the class's enumerate op should call js_enumeratestandardclasses(cx, obj), to define eagerly during for...in loops any classes not yet resolved lazily. see also mxr id search for js_resolvestandardclass js_enumeratestandardclasses ...
JS_SetBranchCallback
returns js_true, the js engine continues to execute the script. if the callback raises an exception using js_setpendingexception() and returns js_false, then the javascript engine propagates the exception to the script that was executing at the time. if the callback returns js_false without raising an exception, then the javascript engine immediately stops running the script with an uncatchable
error. the engine does not execute finally blocks in this case; this is the same behavior as any native method or callback. description js_setbranchcallback specifies a callback function that is automatically called when a script branches backward during execution, when a function returns, and at the end of the script. one typical use for a callback is in a client application to enable a user to abor...
JS_SetElement
handlevalue 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_SetParent
exposed to a script, the object's parent must not change. the javascript engine relies on this invariant. js_setparent has no way to check that this is the case, but nonetheless, applications must not call js_setparent on an object that has already been exposed to a script. if an application does this, the behavior is undefined. on success, js_setparent returns js_true. otherwise, it reports an
error or sets an exception and returns js_false. see also mxr id search for js_setparent bug 1136980 - removed ...
JS_ValueToBoolean
t. 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
ements the touint16 operator specified in ecma 262-3 9.7. all three functions first convert v to a floating-point number as if by calling js_valuetonumber; nan values are then converted to zero. if that succeeds, the result is then converted to the target integer type. this second conversion cannot fail. on success, js_valuetoecmaint32 stores the converted value in *ip and returns js_true. on
error or exception, it returns js_false, and the value left in *ip is undefined. see also js::touint16 js::toint32 js::touint32 js::toint64 js::touint64 js::tonumber bug 933810 bug 933946 ...
JS_ValueToSource
cx jscontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::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 ...
JSDBGAPI
eextent 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_setdebug
errorhook js_setnewscripthook js_setdestroyscripthook js_getglobaldebughooks js_setcontextdebughooks memory usage js_getobjec...
Parser API
e location information. builder builder default: null a builder object, which can be used to produce ast nodes in custom data formats. the expected callback methods are described under builder objects. target string default: script a type of the parsing target, can be either script or module. if parsing fails due to a syntax
error, an instance of syntax
error is thrown. the syntax
error object thrown by reflect.parse() has the same message property as the syntax
error that would be thrown by eval(src). the linenumber and filename properties of the syntax
error object indicate the source location of the syntax
error. node objects by default, reflect.parse() produces node objects, which are plain javascript objects (i.e., t...
SpiderMonkey 1.8.7
ases the need to explicitly root gc things or use the "root as you go" approach popular with earlier spidermonkey releases. since this is a conservative collector, it will often find "garbage" addresses which can trigger warnings from certain code analysis tools. if you are running valgrind on your embedding, be sure to build spidermonkey with the --enable-valgrind option to suppress superflous
error messages triggered by the garbage collector. this also means that objects will be finalized in a non-deterministic order in spidermonkey 1.8.5. this is not a bug, and, any embedding which depends upon deterministic finalization is fatally flawed. typed rooting api the rooting api has been changed from an
error-prone void ** interface to an interface which accepts pointers to specific types. js_...
SpiderMonkey 38
ed in detail below. new javascript language features javascript 38 includes significant updates to language features, yo. new c++ apis jsapi is now a c++-only api. please note that spidermonkey reserves the js:: namespace for itself (and the js:: namespace for internal use). ...
Running Automated JavaScript Tests
run by calling make check, and appear under b. creating new tests for jit-tests creating new tests for jit-tests is easy. just add a new js file to the tests/basic directory (or any appropriate directory under 'tests'). the test harness will automatically find the test and run it. the test is considered to pass if the exit code of the js shell is zero (i.e., js didn't crash and there were no js
errors). use the asserteq function to verify values in your test. there are some advanced options for tests. see the readme (in js/src/jit-tests) for details. ...
Setting up CDT to work on SpiderMonkey
ll" from the "project" menu. start the indexer by either: selecting "index > rebuild" from the project's context menu located in the project explorer window, or selecting "c/c++ index > rebuild" from the "project" menu. and that is pretty much it: large parts of spidermonkey should now be indexed. unfortunately, there are also large parts that are not properly indexed, leading to
errors and warnings being shown for perfectly valid code, but i find that the parts that do work do so nicely enough to make it totally worth it. ...
TPS Bookmark Lists
item is appended to its parent folder, then the second, and so forth. after and before properties are ignored. bookmarks.verify - the bookmark items in the list are verified to be present. within each folder, the second item in the list is assumed to be immediately after the first item, and so forth. if the second item in a given folder is not directly after the first item in that folder, it's an
error. after and before properties, if specified, are also used to verify an item's position. however, because crossweave verifies that bookmark items appear in the order that they are given in the asset list, after and before are not very useful except in verifying the position of the first item in the list. bookmarks.verifynot - the bookmark items in the list are verified not to be present. bookmarks...
Thread Sanitizer
e using linux to build. threadsanitizer does not work on mac osx yet. llvm/clang the tsan instrumentation is implemented as an llvm pass and integrated into clang. the version of clang you need to use depends on what firefox release you are compiling if you are building from mozilla-central, you must use clang 3.6 or later. clang 3.4 + tsan cannot compile firefox due to an internal compiler
error; some versions of clang 3.5 packaged by linux distros do not work for the same reason. you can check which version of clang you have by running the command: clang -v if you are not building from mozilla-central and are building firefox 39 or earlier, you must use clang 3.3. you can find precompiled binaries for llvm/clang 3.3 on the llvm releases page. we recommend using clang 3.6 or la...
Using RAII classes in Mozilla
eased at the end of the statement. we have two techniques for avoiding this problem: static analysis and runtime assertions. static analysis static analysis passes are run on our testing infrastructure using our clang plugin, you can also run them locally marking a raii class for the static analysis is very simple, and performing this marking causes the static analysis to produce a build-time
error whenever a raii class is allocated as a temporary, on the heap, or in static storage. this involves just one addition to the class, and the inclusion of attributes.h: class moz_raii nsautoscriptblocker {...} this is much simpler and more thorough than the guardobject runtime assertions, but are unfortunately currently only run on mac os x and linux builds, which means that guardobject should ...
Pinning violation reports
e are connecting to the sites they intend. it allows site operators to specify who can issue valid certificates for them, rather than accepting any one of the hundreds of built-in root certificates that ship with your browser. if a site makes use of key pinning, and your browser sees a certificate chain for that site which does not match the pin, firefox will reject the connection and display an
error page. the
error page displayed by firefox when you encounter a pin violation gives you the option of reporting this
error. doing this can help us to make the web safer. ...
Security and the jar protocol
. unless, of course, the browser thinks it's a jar file. so starting with gecko 1.8.0.15 and 1.8.1.10, the jar: protocol is only allowed if the mime type of the file is application/java-archive. a site that serves a file with that type is essentially promising that it has vetted the content and that it is in fact safe to download and execute. any other file type results in an "unsafe file type"
error. ...
Browser security
secure development guidelinesthe following content will likely see significant revision, though can be used as a reference for security best practices to follow when developing code for mozilla.security and the jar protocolthis article discusses security concerns with the jar: protocol, which only firefox has ever implemented for web content. ...
Feed content access API
null); if (data.length) { var parser = components.classes["@mozilla.org/feed-processor;1"] .createinstance(components.interfaces.nsifeedprocessor); var listener = new feedtestresultlistener(); try { parser.listener = listener; parser.parsefromstring(data, uri); } catch(e) { alert("
error parsing feed."); } } } httprequest = new xmlhttprequest(); httprequest.open("get", feedurl, true); try { httprequest.onload = inforeceived; httprequest.send(null); } catch(e) { alert(e); } } the nsifeedprocessor interface lets you parse the feed data from several possible sources; in this case, we're loading a document into a string...
Using the Places annotation service
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 exceptio...
Using the Places favicon service
sing the places annotation service. you should always use nsifaviconservice.getfaviconimageforpage() to get the favicon for a page. if the page has no favicon, or we have never heard of the page, this function will return a "chrome:" uri of the default favicon. this allows efficient caching, since the default favicon will probably be cached in its decoded form by the image library. if there is an
error loading the favicon for an annotation uri, the default favicon data will be returned by the annotation service's protocol handler. however, since the uri will be different from the default favicon, the decoded image will not be cached by the image library. see also nsifaviconservice ...
Accessing the Windows Registry Using XPCOM
y, note that you should close the key when you are done to avoid wasting system resources. opening registry keys before doing anything with a registry key you must first open the key you are interested in. the example above demonstates this using the open() method. if you want to create a new key, you can use the create() method, which takes the same parameters as open(). note that it is not an
error to call create() on an existing key, and doing so has the same result as calling open(). both of these methods take a root key as the first parameter. from javascript, you will want to use the named constants on the interface for this parameter. they are: root_key_classes_root — corresponds to hkey_classes_root root_key_current_user — corresponds to hkey_current_user root_key_local_mach...
XPCOM array guide
ple: an array attribute in an idl file would be nsiarray. will your array store non-refcounted objects and need automatic resizing? if so, use nstarray<t>. example: an array of integers or an array of strings. will your array store non-refcounted objects and be a fixed size? if so, just use a native c++ array unless you need the enumeration options on nstarray<t>. example: an array of
error message static const char* pointers. are all the things you are storing interface pointers to instances of the same interface? if so, use nscomarray. example: a content node's list of nsicontent children. otherwise use nsiarray and make liberal use of queryelementat(). the point of nscomarray is that it's a template, and all the pointers in it must be pointers to the same type; it's nice ...
Packaging WebLock
the following html specifies a complete webpage in which the trigger script is defined as a javascript function, installweblock, that gets c...
Creating XPCOM components
ith the examples conventions acknowledgements an overview of xpcom the xpcom solution gecko components interfaces interfaces and encapsulation the nsisupports base interface xpcom identifiers cid contract id factories xpidl and type libraries xpcom services xpcom types method types reference counting status codes variable mappings common xpcom
error codes using xpcom components component examples cookie manager the webbrowserfind component the weblock component component use in mozilla finding mozilla components using xpcom components in your cpp xpconnect: using xpcom components from script component internals creating components in cpp xpcom initialization xpcom registry manifests registration...
Detailed XPCOM hashtable guide
.> pldhash the pldhash implementation is a fairly low-level implementation, written in c. it is extremely flexible, but requires some time to understand and use. a basic guide is included here, but you should read most of xpcom/glue/pldhash.h if you intend to use pldhash. the c++ wrappers for pldhash (see below) are often much easier and safer to use in c++ code, as many potential casting
errors are easily avoided. you must declare an entry struct type, deriving from pldhashentryhdr. this entry struct should contain whatever data you wish to store in the hashtable (any pointer or fixed-length data type). note: because of the double-hashing implementation, entries may move in memory when the hashtable is altered. if you need entry pointers to remain constant, you may want to consider us...
Components.lastResult
sult of 'implicit' xpconnect calls rather than the result of the target call. example in the following example, the local variable i contains the actual result returned by bar() (assuming that bar() is called via xpconnect), and components.lastresult contains the success code returned by bar(). // given that foo.bar is a method that might return // the success codes ns_ok, '5', and '6' or some
error code... try { 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. bad component! break; } // and so on.... } catch (e) { // t...
Components.utils.evalInSandbox
' with value 5 into global scope. mysandbox.double = double; var result = components.utils.evalinsandbox("x = y + 2; double(x) + 3", mysandbox); console.log(result); // 17 console.log(mysandbox.x); // 7 operations on objects you insert into this sandbox global scope do not carry privileges into the sandbox: mysandbox.foo = components; // this will give a "permission denied"
error components.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...
Components.utils.evalInWindow
evalinwindow("somelocalvariable.newprop = 42", contentwindow); // page-script.js console.log(window.somelocalvariable.newprop); // 42 but note that the add-on script must trust that the page script has not redefined the setter on somelocalvariable: unlike xraywrappers, evalinwindow() does not provide x-ray vision. if the returned object contains a function, calls to evalinwindow() will throw an
error: // page-script.js function bar() { } var somelocalvariablecontainingafunction = {name: "selection1", foo : bar}; // add-on-script.js components.utils.evalinwindow("somelocalvariablecontainingafunction", contentwindow); //
error, function can't be cloned ...
Components.utils.exportFunction
rays provide a filtered view of the original object. for the full details refer to the documentation for xray vision, but for example: functions are not visible in the xrays of javascript object types. ...
Using components
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] report
error=function report
error() { [native code] } cancreatewrapper=function cancreatewrapper() { [native code] } cancallmethod=function cancallmethod() { [native code] } cangetproperty=function cangetproperty() { [native code] } cansetproperty=function cansetproperty() { [native code] } ...
nsScriptableInputStream
actory = components.classes["@mozilla.org/scriptableinputstream;1"]; var sis = factory.createinstance(nsiscriptableinputstream); sis.init(inputstream); try { while (true) { var chunk = sis.read(512); if (chunk.length == 0) break; // ok, chunk now contains a portion of the stream's data. // do something with it! } } catch (e) { dump("
error: failed reading from stream:\n" + e + "\n"); } } see also nsiscriptableinputstream ...
NS_GetComponentManager
mary the ns_getcomponentmanager function returns a reference to the xpcom component manager. #include "nsxpcom.h" #include "nsicomponentmanager.h" nsresult ns_getcomponentmanager( nsicomponentmanager** aresult ); parameters aresult [out] a reference to the xpcom component manager. return values the ns_getcomponentmanager function returns ns_ok if successful. otherwise, it returns an
error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. see bug 99147 for details. see also nsicomponentmanager ...
NS_GetComponentRegistrar
etcomponentregistrar function returns a reference to the xpcom component registrar. #include "nsxpcom.h" #include "nsicomponentregistrar.h" nsresult ns_getcomponentregistrar( nsicomponentmanager** aresult ); parameters aresult [out] a reference to the xpcom component registrar. return values the ns_getcomponentregistrar function returns ns_ok if successful. otherwise, it returns an
error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. see bug 99147 for details. see also nsicomponentregistrar ...
NS_GetMemoryManager
« xpcom api reference summary the ns_getmemorymanager function returns a reference to the xpcom memory manager. #include "nsxpcom.h" #include "nsimemory.h" nsresult ns_getmemorymanager( nsimemory** aresult ); parameters aresult [out] a reference to the xpcom memory manager. return values the ns_getmemorymanager function returns ns_ok if successful. otherwise, it returns an
error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. any code, intended to be used exclusively with mozilla 1.8 and above, may use ns_alloc, ns_realloc, and ns_free instead to access the xpcom memory manager's methods. history this function was finalized for mozilla 0.9.7. see ...
NS_GetServiceManager
eference summary the ns_getservicemanager function returns a reference to the xpcom service manager. #include "nsxpcom.h" #include "nsiservicemanager.h" nsresult ns_getservicemanager( nsiservicemanager** aresult ); parameters aresult [out] a reference to the xpcom service manager. return values the ns_getservicemanager function returns ns_ok if successful. otherwise, it returns an
error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. see bug 99147 for details. see also nsiservicemanager ...
NS_InitXPCOM2
try and runtime libraries. pass null to specify that the current working directory should be used. aappfilelocationprovider [in] the object to be used by xpcom to locate application specific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. return values the ns_initxpcom2 function returns ns_ok if successful. otherwise, it returns an
error code. some of the possible
errors are documented below: ns_
error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. 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 proc...
NS_InitXPCOM3
., the user profile, the component registry, etc.). this parameter may be nsnull. astaticmodules [in] an array of nsstaticmoduleinfo objects. passing null causes the default (built-in) static modules to be registered, if present. astaticmodulecount [in] the number of elements in astaticmodules. return values the ns_initxpcom3 function returns ns_ok if successful. otherwise, it returns an
error code. some of the possible
errors are documented below: ns_
error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. 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 proc...
NS_ShutdownXPCOM
mmary the ns_shutdownxpcom function terminates use of xpcom in the calling process. #include "nsxpcom.h" nsresult ns_shutdownxpcom( nsiservicemanager* asvcmanager ); parameters asvcmanager [in] the nsiservicemanager instance that was returned by ns_initxpcom2 (or ns_initxpcom3) or null. return values the ns_shutdownxpcom function returns ns_ok if successful. otherwise, it returns an
error code. remarks you must call this method once you are finished using xpcom. calling this method triggers the "xpcom-shutdown" notification to be dispatched to observers. once this function has been called, the nsicomponentmanager and nsiservicemanager will refuse to return object instances. history this function was finalized for mozilla 0.9.6. see bug bug 99147 for details. see also ns_i...
imgICache
ut 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. ...
imgIDecoder
* buffer would need to be used in order to call the output stream's other write() method. unsigned long writefrom( in nsiinputstream instr, in unsigned long count ); parameters instr the stream from which to read the encoded image data. count the maximum number of bytes to write to the image. return value the number of bytes actually written to the image, or undefined if an
error occurred. see also imgidecoderobserver imgiload ...
imgIDecoderObserver
in imgicontainer acontainer ); parameters arequest the request on which data is available, or null if being called for an imgidecoder object. acontainer missing description onstopdecode() in theory a decode notification, but currently a load notification. ideally this would be called when the decode is complete. unfortunately, this is currently the only way to signal decoding
errors to consumers, and the only decoding
errors that consumers care about (indeed, the only ones that they're prepared to hear about) are failures to instantiate the decoder (<img src="foo.html"> for example). thus, currently this is just a companion to onstoprequest to signal success or failure. you probably want onstopcontainer instead. this will be revisited in bug 505385. if you're thinking of do...
imgIRequest
t is being cancelled as a result of a failure of a proxy holder and not an internal failure. at least i think that's what it does. regardless, there's no reason for this flag to be public, and it should either go away or become a private state flag within imgrequest. do not rely on it. status_load_complete 0x4 the data has been fully loaded to memory, but not necessarily fully decoded. status_
error 0x8 an
error occurred loading the image. status_frame_complete 0x10 the first frame has been completely decoded. status_decode_complete 0x20 the whole image has been decoded. cors_none 1 cors modes images can be loaded with. by default, all images are loaded with cors_none and cannot be used cross-origin in context like webgl. if an html img element has the crossorigin attribute set, the ...
mozIAsyncHistory
owsing mode. void updateplaces( in moziplaceinfo aplaceinfo, in mozivisitinfocallback acallback optional ); parameters aplaceinfo 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 visitdat...
mozIColorAnalyzer
nce reasons before analyzing it. void findrepresentativecolor( in nsiuri imageuri, in mozirepresentativecolorcallback callback ); parameters imageuri a uri pointing to the image - ideally a data: uri, but any scheme that will load when setting the src attribute of a dom img element should work. callback function to call when the representative color is found or an
error occurs. remarks below are some images with the result of findrepresentativecolor: image representative color 0xb28d3a 0x502e1e 0x53ba3f 0x00a400 see also mozirepresentativecolorcallback bug 634139 ...
mozISpellCheckingEngine
f the engine. not currently 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 ...
mozIStorageAggregateFunction
/ mnumbers.length(); nstarray<print64> data(mnumbers); for (pruint32 i = 0; i < data.length(); i++) { print32 value = data[i] - mean; data[i] = value * value; } total = 0; for (pruint32 i = 0; i < data.length(); i++) total += data[i]; nscomptr<nsiwritablevariant> result = do_createinstance("@mozilla.org/variant;1"); ns_ensure_true(result, ns_
error_out_of_memory); rv = result->setasdouble(sqrt(double(total) / double(data.length()))); ns_ensure_success(rv, rv); ns_addref(*_result = result); return ns_ok; } private: nstarray<print32> mnumbers; }; // now, register our function with the database connection. nscomptr<mozistoragefunction> func = new standarddeviationfunc(); ns_ensure_true(func, ns_
error_out_of_memory); nsre...
mozIStorageFunction
class squarefunction : public mozistoragefunction { public: ns_imethod onfunctioncall(mozistoragevaluearray *aarguments, nsivariant **_result) { print32 value; nsresult rv = aarguments->getint32(&value); ns_ensure_success(rv, rv); nscomptr<nsiwritablevariant> result = do_createinstance("@mozilla.org/variant;1"); ns_ensure_true(result, ns_
error_out_of_memory); rv = result->setasint64(value * value); ns_ensure_success(rv, rv); ns_addref(*_result = result); return ns_ok; } }; // now, register our function with the database connection. nscomptr<mozistoragefunction> func = new squarefunction(); ns_ensure_true(func, ns_
error_out_of_memory); nsresult rv = dbconn->createfunction( ns_literal_cstring("square"), 1, func...
nsIAbstractWorker
dom/interfaces/threads/nsidomworkers.idlscriptable this interface is an abstract interface used to implement the web workers architecture. 1.0 66 introduced gecko 1.9.1 inherits from: nsidomeventtarget last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) attributes attribute type description on
error nsidomeventlistener the
error listener for the worker. see also using web workers nsiworkermessageport nsiworkermessageevent nsiworkerscope nsiworkerglobalscope nsiworker ...
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 ...
nsIAuthPrompt2
oalesced 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 asyncpromptauth( in nsichannel achannel, in nsiauthpromptcallback acallba...
nsIAuthPromptProvider
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. ...
nsIBadCertListener2
the active connection. this object usually supports nsisslsocketcontrol, nsitransportsecurityinfo, nsiidentityinfo, nsisslstatusprovider, nsiclientauthuserdecision and possibly other interfaces. status the ssl status object that describes the problem(s). targetsite the site name that was used to open the current connection. return value the consumer shall return true if it wants to suppress the
error message related to the bad cert (the connection will still get canceled). see also nsisockettransport ...
nsIBinaryInputStream
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. exceptions thrown ns_
error_failure if it can't read alength bytes. readbytes() reads an opaque byte array from the stream. void readbytes( in pruint32 alength, [size_is(alength), retval] out string astring ); parameters alength the number of bytes to read. astring a string containing the bytes read from the stream. exceptions thrown ns_
error_failure if it can't read alength bytes. readcstring() re...
nsICache
d as streams of data or as objects. this constant specify that cache session is a stream based entry when calling nsicacheservice.createsession() method. non_blocking 0 the synchronous opencacheentry() may be blocking or non-blocking. if a cache entry is waiting to be validated by another cache descriptor (so no new cache descriptors for that key can be created), opencacheentry() will return ns_
error_cache_wait_for_validation in non-blocking mode. if the cache entry is validated, then a descriptor for that entry will be created and returned. if the cache entry was doomed, then a descriptor will be created for a new cache entry for the key. blocking 1 the synchronous opencacheentry() may be blocking or non-blocking. in blocking mode, it will wait until the cache entry for the key has been va...
nsICacheListener
n nsresult status ); parameters descriptor the cache entry descriptor. accessgranted the cache access mode. status the status of the cache entry availability. oncacheentrydoomed() this method is called when the processing started by nsicachesession.doomentry() is completed. void oncacheentrydoomed( in nsresult status ); parameters status the status is ns_ok when the entry was doomed, or ns_
error_not_available when there is no such entry. see also nsicache nsicachesession nsicacheentrydescriptor ...
nsICacheService
ine 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() obsolete since gecko 1.8...
nsICacheSession
ession storage policy are currently enabled for instantiation or not, depending on their existence. opencacheentry() this method gives a synchronous cache access. it returns a unique descriptor each time it is called, even if the same key is specified. when called by multiple threads for write access, only one writable descriptor will be granted. if blockingmode is set to false, it will return ns_
error_cache_wait_for_validation rather than block when another descriptor has been given write access but hasn't validated the entry yet. note: if at all possible, you should use asyncopencacheentry() instead of calling opencacheentry(), in order to avoid blocking on i/o on the calling thread. this will streamline overall application performance. a cache session can only give out one descriptor with wr...
nsIChannelEventSink
it must explicitly deal with it, 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. ...
nsIClassInfo
bute 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.getservicebycontractid(). read only. ...
nsIClipboardDragDropHooks
e implementation is set for a window, the hooks will be called in the order they are added. adding the same hook to the same window will not add a second call. each hook can only be called once per user action/api. not all hooks are guaranteed to be called. if there are multiple hooks set for a window, any of them has an opportunity to cancel the action so no further processing will occur. if any
errors occur (without setting the boolean result) the default action will occur. allowdrop() will be called many times during drag so ensure that it is efficient. method overview boolean allowdrop(in nsidomevent event, in nsidragsession session); boolean allowstartdrag(in nsidomevent event); boolean oncopyordrag(in nsidomevent aevent, in nsitransferable trans); boolean onpasteordrop(in nsidom...
nsIClipboardOwner
d a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports method overview void losingownership(in nsitransferable atransferable); methods losingownership() this method notifies the owner of the clipboard transferable that the transferable is being removed from the clipboard. it results into a ns_ok if there are no
errors. void losingownership( in nsitransferable atransferable ); parameters atransferable the transferable. see also nsiclipboard nsitransferable ...
nsICommandLineRunner
assed. 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. ...
nsIConsoleMessage
xpcom/base/nsiconsolemessage.idlscriptable this interface is a base interface for messages passed to or from the nsiconsoleservice. inherits from: nsisupports last changed in gecko 1.7 implementations may provide an object that can be query interfaced, nsisupports.queryinterface(), to provide more specific message information. see nsiscript
error for an example. attributes attribute type description message wstring the message in a string format. [binaryname(messagemoz)] read only. see also nsiconsoleservice ...
nsIConverterOutputStream
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. ...
nsICycleCollectorListener
bird 3.3 / seamonkey 2.1) the order of calls will be call to begin(); then for every node in the graph a call to noteobject() and calls to noteedge() for every edge starting at that node; then a call to begindescriptions(); then for every black node in the cycle collector graph a call to either describerefcountedobject() or to describegcedobject(); and then a call to end(). if begin() returns an
error none of the other functions will be called. method overview void begin(); void begindescriptions(); void describegcedobject(in unsigned long long aaddress, in boolean amarked); void describerefcountedobject(in unsigned long long aaddress, in unsigned long aknownedges, in unsigned long atotaledges); void end(); void noteedge(in unsigned long long afromaddress, in unsigned long long at...
nsIDBChangeListener
there are a couple of ways to access the message database: if you have a nsimsgfolder, you can do this like so: somefolder.msgdatabase.addlistener(mylistener); alternately, you can access the message database through the nsimsgdbview ...
nsIDNSListener
astatus if the lookup failed, this parameter gives the reason. ...
nsIDOMChromeWindow
de. 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 maximum number of times ...
nsIDOMEvent
op 0x00000800 focus 0x00001000 blur 0x00002000 select 0x00004000 change 0x00008000 reset 0x00010000 submit 0x00020000 scroll 0x00040000 load 0x00080000 unload 0x00100000 xfer_done 0x00200000 abort 0x00400000
error 0x00800000 locate 0x01000000 move 0x02000000 resize 0x04000000 forward 0x08000000 help 0x10000000 back 0x20000000 text 0x40000000 alt_mask 0x00000001 control_mask 0x00000002 shift_mask 0x00000004 meta_mask 0x00000008 ...
nsIDOMFileException
s to the methods in the nsidomfile interface. note: gecko's implementation of this interface presently differs from the working draft of the file api specification. content/base/public/nsidomfileexception.idlscriptable please add a summary to this article. 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. see also nsidomfile nsidomfilelist nsidomfilereader ...
nsIDOMHTMLAudioElement
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 channels. ...
nsIDOMMouseScrollEvent
abstractview viewarg, in long detailarg, in long screenxarg, in long screenyarg, in long clientxarg, in long clientyarg, in boolean ctrlkeyarg, in boolean altkeyarg, in boolean shiftkeyarg, in boolean metakeyarg, in unsigned short buttonarg, in nsidomeventtarget relatedtargetarg, in long axis ); parameters typearg the type of event. must be one of "abort", "
error", "load", "loadstart", or "progress". canbubblearg specifies whether or not the created event will bubble. cancelablearg specifies whether or not the created event can be canceled. viewarg the nsidomabstractview in which the event occurred. detailarg screenxarg the x coordinate at which the event occurred, in screen coordinat...
nsIDOMMozNetworkStatsManager
y 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 threshold bytes, a "networkstats-alarm" syste...
nsIDOMOfflineResourceList
ems nsidomofflineresourcelist the list of dynamically-managed entries in the offline resource list. read only. mozlength unsigned long the number of entries in the dynamically managed offline resource list. read only. onchecking nsidomeventlistener an event listener to be called when fetching the application cache manifest and checking for updates. on
error nsidomeventlistener an event listener to be called when an
error occurs during the caching process. onnoupdate nsidomeventlistener an event listener to be called when there is no update to download. ondownloading nsidomeventlistener an event listener to be called when resources are being downloaded into the cache. onprogress nsidomeventlistener a...
nsIDOMParser
nit() method, attempting to initiate a parsing operation will automatically call init() on the domparser with a null principal and null pointers for documenturi and baseuri. cases where these values matter: if you don't specify the document uri by calling init() after creating the parser via createinstance() the created documents will use a moz-nullprincipal:{<guid>} uri, which will show in the
error console in parsing
errors, in particular. supposedly, if you want to create objects that some particular set of unprivileged code will be able to access (see discussion in bug 565480). parsing a string once you've created a domparser object, you can use its parsefromstring method to parse xml or html as described in the web platform documentation. examples within the context of a window: var par...
nsIDOMProgressEvent
o construct a synthetic progressevent. it still is usable from native c++ code. initializes the progress event object. void initprogressevent( in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in boolean lengthcomputablearg, in unsigned long long loadedarg, in unsigned long long totalarg ); parameters typearg the type of event. must be one of "abort", "
error", "load", "loadstart", or "progress". canbubblearg specifies whether or not the created event will bubble. cancelablearg specifies whether or not the created event can be canceled. lengthcomputablearg if the size of the data to be transferred is known, this should be true. otherwise, specify false. loadedarg the number of bytes already transferred. must be a non-negative value. totalarg ...
nsIDOMWindow
sessionstorage nsidomstorage session storage for the current browsing context. data stored in session storage may be accessed by any site in the browsing context. read only.note: prior to gecko 8.0 this attribute was part of nsidomstoragewindow. textzoom float get or set the document scale factor as a multiplier of the default size. when setting this attribute, an ns_
error_not_implemented
error may be returned by implementations not supporting zoom. this attribute should always return 1.0 for implementations not supporting text zoom. 1.0 represents normal (unzoomed) size. native code only! top nsidomwindow the root window for the hierarchy of windows that contain this nsidomwindow. this is the window itself if there is no parent, or if the parent is ...
nsIDOMXPathException
dom/interfaces/xpath/nsidomxpathexception.idlscriptable describes an exception resulting from xpath operations. 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. see also introduction to using xpath in javascript document object model (dom) level 3 xpath specification nsidomxpathevaluator document.evaluate nsidomxpathresult ...
nsIDirectoryEnumerator
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. ...
nsIDocShell
only. restoringdocument boolean track whether we're currently restoring a document presentation. read only. securityui nsisecurebrowserui the securebrowserui object for this docshell. this is set by browser or nswebbrowser for their root docshell. shouldsavelayoutstate boolean indicates whether the current page can be cached. read only. use
errorpages boolean attribute to access whether
error pages are enabled. zoom float set/get the document scale factor. when setting this attribute, a ns_
error_not_implemented
error may be returned by implementations not supporting zoom. implementations not supporting zoom should return 1.0 all the time for the get operation. 1.0 by the way is the default of zoom. this means 100% of...
nsIDownloadManagerUI
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 to put the download...
nsIDroppedLinkHandler
n, 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 the link being dragged...
nsIEventTarget
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 returns true if events d...
nsIFactory
dref 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 method. it exists primari...
nsIFeedResultListener
uld be implemented by programs to receive events from the feed parser as parsing progresses. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void handleresult(in nsifeedresult result); methods handleresult() called when feed processing is complete. even if an
error occurred during processing, there may be valid data available for feed-level data or entries processed before the
error occurred. if you don't care about doing progress display or the like, this is all you need to implement in order to receive the parsed feed. void handleresult( in nsifeedresult result ); parameters result an nsifeedresult describing the parsed feed. see also nsifee...
nsIFileInputStream
ream, or more specifically, when one of the following is called: seek() tell() available() read() readline() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well. note: using this flag results in the file not being opened during the call to init. this means that any
errors that might happen when this flag is not set would happen during the first read. also, the file is not locked when init is called, so it might be deleted before we try to read from it. methods init() void init( in nsifile file, in long ioflags, in long perm, in long behaviorflags ); parameters file file to read from (must qi to nsilocalfile) ioflags the file status fl...
nsIFileOutputStream
when one of the following is called: seek() tell() write() flush() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well. note: using this flag results in the file not being opened during the call to init(). this means that any
errors that might happen when this flag is not set would happen during the first write, and if the file is to be created, it will not appear on the disk until the first write. methods init() void init( in nsifile file, in long ioflags, in long perm, in long behaviorflags ); parameters file file to write to (must qi to nsilocalfile) ioflags file open...
nsIFilePicker
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 nsisimpleenumerator an enumerato...
nsIFileProtocolHandler
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 ...
nsIFrameLoaderOwner
s 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 ...
nsIMessageBroadcaster
manager getchildat(in unsigned long aindex); broadcastasyncmessage() like sendasyncmessage(), but also broadcasts this message to all "child" message managers of this message manager. see nsimessagelistener::receivemessage() for the format of the data delivered to listeners. warning: broadcasting messages can be very expensive and leak sensitive data. use with extreme caution. throws ns_
error_not_initialized if the sender is not initialized. for example, we will throw ns_
error_not_initialized if we try to send a message to a cross-process frame but the other process has not yet been set up. throws ns_
error_failure when the message receiver cannot be found. for example, we will throw ns_
error_failure if we try to send a message to a cross-process frame whose process has crashed. para...
nsIMessageSender
[optional] in jsval objects, [optional] in nsiprincipal principal); sendasyncmessage() send messagename and obj to the "other side" of this message manager. this invokes listeners who registered for messagename using a nsimessagelistenermanager. see nsimessagelistener::receivemessage() for the format of the data delivered to listeners. throws ns_
error_not_initialized if the sender is not initialized. for example, we will throw ns_
error_not_initialized if we try to send a message to a cross-process frame but the other process has not yet been set up. throws ns_
error_failure when the message receiver cannot be found. for example, we will throw ns_
error_failure if we try to send a message to a cross-process frame whose process has crashed. para...
nsIModule
siclassinfo. 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 string aloaderstr, in...
nsIMsgAccount
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
mmaryvalid 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); parameters afold...
nsIMsgFilterCustomAction
isvalidfortype(in nsmsgfiltertypetype type, in nsmsgsearchscopevalue scope); /** * after the user inputs a particular action value for the action, determine * if that value is valid. * * @param actionvalue the value entered. * @param actionfolder folder in the filter list * @param filtertype filter type (manual, offlinemail, etc.) * * @return
errormessage a localized message to display if invalid * set to null if the actionvalue is valid */ autf8string validateactionvalue(in autf8string actionvalue, in nsimsgfolder actionfolder, in nsmsgfiltertypetype filtertype); /* allow duplicate actions in the same filter list? default no. *...
nsIMsgMessageService
this is for consumers who want a particular header but don't want to stream the whole message. nsiuri streammessage(in string amessageuri, ...
nsINavBookmarkObserver
ecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavbookmarkobserver and nsinavbookmarkobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { if (iid.equals(ci.nsinavbookmarkobserver) || iid.equals(ci.nsinavbookmarkobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_
error_no_interface; } see also places manipulating bookmarks using places nsinavbookmarksservice ...
nsINavBookmarksService
atch() for each call to beginupdatebatch. if you do not do this, certain parts of the ui will not get updated and any changes to bookmarks will not get written to disk. from c++ code inside the places component, use nsbookmarksupdatebatcher defined in nsnavbookmarks.h to scope batches. for js or from other components, just please be very careful to close the batch, especially when encountering an
error and returning early. void beginupdatebatch(); parameters none. changebookmarkuri() this method changes the bookmarked uri for a bookmark. it changes which "place" the bookmark points at, which means all annotations, and so on are carried along. void changebookmarkuri( in nsiuri olduri, obsolete since gecko 1.9 in long long aitemid, in nsiuri anewuri ); parameters olduri obsolete...
nsINavHistoryService
system. return value returns true if this uri would be added to the history, otherwise returns false. addvisit() 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 moziasynchistory.updateplaces() instead. see this code for how a function to add visits and handle
errors using the new api could look like. this method adds a visit for a specific page. this will probably not be commonly used other than for backup/restore type operations. if the uri does not have an entry in the history database already, one will be created with no visits, no title, hidden, not typed. adding a visit will automatically increment the visit count for the visited page and will unhide...
nsIObserverService
server, in string atopic, in boolean ownsweak ); parameters anobserver the nsiobserver object which will receive notifications. atopic the notification topic or subject. ownsweak if set to false, the nsiobserverservice will hold a strong reference to anobserver. if set to true and anobserver supports the nsisupportsweakreference interface, a weak reference will be held. otherwise an
error will be returned. (in most cases, you should use false.) enumerateobservers() called to enumerate all observers registered for a particular topic. nsisimpleenumerator enumerateobservers( in string atopic ); parameters atopic the notification topic or subject. return value returns an enumeration of all registered listeners. see nsisimpleenumerator. notifyobservers() this method is...
nsIPipe
e pipe can be either blocking or non-blocking. recall that a non-blocking stream will return ns_base_stream_would_block if it cannot be read or written to without blocking the calling thread. for example, if you try to read from an empty pipe that has not yet been closed, then if that pipe's input end is non-blocking, then the read call will fail immediately with ns_base_stream_would_block as the
error condition. however, if that pipe's input end is blocking, then the read call will not return until the pipe has data or until the pipe is closed. this example presumes that the pipe is being filled asynchronously on some background thread. the pipe supports nsiasyncinputstream and nsiasyncoutputstream, which give the user of a non-blocking pipe the ability to wait for the pipe to become ready aga...
nsIPrivateBrowsingService
ate-toggle switches) 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
ame ); 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
urpose 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 ...
nsIProgressEventSink
iven request. void onstatus( in nsirequest arequest, in nsisupports acontext, in nsresult astatus, in wstring astatusarg ); parameters arequest the request being observed (may qi to nsichannel). acontext if arequest is a channel, then this parameter is the listener context passed to nsichannel.asyncopen(). astatus status code (not necessarily an
error code) indicating the state of the channel (usually the state of the underlying transport). see nsisockettransport for socket specific status codes. astatusarg status code argument to be used with the string bundle service to convert the status message into localized, human readable text. the meaning of this parameter is specific to the value of the status code. for socket status cod...
nsIProperties
n 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 string keys ); p...
nsIPropertyBag
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" cookieenabled:true donottrack:...
nsIProtocolProxyCallback
e(). 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void onproxyavailable(in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus); methods onproxyavailable() this method is called when proxy info is available or when an
error in the proxy resolution occurs. void onproxyavailable( in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus ); parameters arequest the value returned from asyncresolve. auri the uri passed to asyncresolve. aproxyinfo the resulting proxy info or null if there is no associated proxy info for auri. as with the ...
nsIProtocolProxyService
that may be used instead. as a side-effect, this method may affect future result values from resolve/asyncresolve as well as from getfailoverforproxy. nsiproxyinfo getfailoverforproxy( in nsiproxyinfo aproxyinfo, in nsiuri 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 ...
nsIScriptableUnicodeConverter
ray([const,array,size_is(acount)] in octet adata, in unsigned long acount); void converttobytearray(in astring astring,[optional] out unsigned long alen,[array, size_is(alen),retval] out octet adata); nsiinputstream converttoinputstream(in astring astring); attributes attribute type description charset string current character set. throws ns_
error_uconv_noconv if the requested charset is not supported. methods convertfromunicode() converts the data from unicode to one charset. returns the converted string. after converting, finish should be called and its return value appended to this return value. acstring convertfromunicode( in astring asrc ); finish() returns the terminator string. should be called after convertfromunicod...
nsISearchEngine
alue 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, [optional] in astring purpos...
nsISelectionController
llapse the selection or extend it? completescroll() will move page view to the top or bottom of the document. void completescroll( in boolean forward ); parameters forward forward or backward if pr_false. getcaretenabled() gets the current state of the caret, as set by setcaretenabled(). boolean getcaretenabled(); parameters none. return value if aoutenabled==null, returns ns_
error_invalid_arg else ns_ok. getdisplayselection() will get the display mode for the selection. short getdisplayselection(); parameters none. return value off, on, disabled. getselection() will return the selection that the presentation shell may implement. nsiselection getselection( in short type ); parameters type will hold the type of selection. (selectiontype) return value will...
nsISimpleEnumerator
next element in the enumerator. the "next" element is the first element upon the first call. must be preceded by a call to hasmoreelements() which returns pr_true. this method is generally called within a loop to iterate over the elements in the enumerator. nsisupports getnext(); parameters none. return value ns_ok if the call succeeded in returning a non-null value through the out parameter. ns_
error_failure if there are no more elements to enumerate. hasmoreelements() called to determine whether or not the enumerator has any elements that can be 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...
nsISocketTransportService
void shutdown(); obsolete since gecko 1.8 attributes attribute type description autodialenabled boolean controls whether or not the socket transport service should poke the autodialer on connection failure. obsolete since gecko 1.8 methods native code only! attachsocket adds a new socket to the list of controlled sockets. this will fail with the
error code ns_
error_not_available if the maximum number of sockets is already reached. in this case, the notifywhencanattachsocket() method should be used. note: this function may only be called from an event dispatch on the socket thread. void attachsocket( in prfiledescptr afd, in nsasockethandlerptr ahandler ); parameters afd open file descriptor of the socket to control. ahandler sock...
nsIStackFrame
xpcom/base/nsiexception.idlscriptable please add a summary to this article. 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. read only. linenumbe...
nsIStringBundleService
arameters none. formatstatusmessage() formats a message string from a status code and status arguments. typically used to format a message received by a nsiprogresseventsink's onstatus method. wstring formatstatusmessage( in nsresult astatus, in wstring astatusarg ); parameters astatus the status code. this is mapped into a string id and and used in the string lookup process (see nsi
errorservice). astatusarg the status message argument(s). multiple arguments can be separated by newline ('\n') characters. return value the formatted message. see also code snippets : miscellaneous : using string bundles from javascript how to localize html pages, xul files, and js/jsm files from bootstrapped add-ons. the localizing js/jsm files uses the nsistringbundleservice: bootstrapped ...
nsIStructuredCloneContainer
cturedclonecontainer.idlscriptable this interface acts as a container for an object serialized using the structured clone algorithm. 1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) you can copy an object into an nsistructuredclonecontainer using initfromvariant() or initfrombase64(). it is an
error to initialize an nsistructuredclonecontainer more than once. once you've initialized the container, you can get a copy of the object it stores by calling deserializetovariant(). you can also get a base-64-encoded string containing a copy of the container's serialized data, using getdataasbase64(). method overview nsivariant deserializetovariant(); astring getdataasbase64(); void initfromba...
nsISupports
ed 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 descriptions above were ta...
nsISyncMessageSender
sender until all listeners of the message have been invoked. returns an array containing return values from each listener invoked. send messagename and obj to the "other side" of this message manager. this invokes listeners who registered for messagename using a nsimessagelistenermanager. see nsimessagelistener::receivemessage() for the format of the data delivered to listeners. throws ns_
error_not_initialized if the sender is not initialized. for example, we will throw ns_
error_not_initialized if we try to send a message to a cross-process frame but the other process has not yet been set up. throws ns_
error_failure when the message receiver cannot be found. for example, we will throw ns_
error_failure if we try to send a message to a cross-process frame whose process has crashed. para...
nsITaskbarPreviewController
ontext2d object representing the drawing context into which the thumbnail is to be rendered. note that this context is not actually attached to a canvas element. width the width of the surface backing the drawing context. height the height of the surface backing the drawing context. note: it's guaranteed that width ÷ height will equal the thumbnailaspectratio, within the margin of rounding
errors. return value true if you want a frame drawn around the thumbnail, otherwise false. onactivate() invoked when the user clicks on the tab preview. boolean onactivate(); parameters none. return value true if the top level window corresponding to the preview should be activated, false if activation is not accepted. onclick() invoked when one of the buttons on the window preview's toolba...
nsIToolkitProfile
may be the same as the root directory. see nsiprofilelock.localdirectory(). read only. name autf8string the profile's name. rootdir nsilocalfile 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...
nsITraceableChannel
ls(ci.nsisupports)) { return this; } throw cr.ns_nointerface; } }; var httpresponseobserver = { observe: function(asubject, atopic, adata) { var newlistener = new tracinglistener(); asubject.queryinterface(ci.nsitraceablechannel); newlistener.originallistener = asubject.setnewlistener(newlistener); /////// end - do not edit newlistener.promisedone.then( function() { // no
error happened console.log('yay response done:', newlistener.responsebody); }, function(areason) { // promise was rejected, right now i didnt set up rejection, but i should listen to on abort or bade status code then reject maybe } ).catch( function(acatch) { console.
error('something went wrong, a typo by dev probably:', acatch); } ); } }; services.obs.addobserver(httpr...
nsITransportEventSink
ong aprogress, in unsigned long long aprogressmax); methods ontransportstatus() transport status notification. void ontransportstatus( in nsitransport atransport, in nsresult astatus, in unsigned long long aprogress, in unsigned long long aprogressmax ); parameters atransport the transport sending this status notification. astatus the transport status (resolvable to a string using nsi
errorservice). see nsisockettransport for socket specific status codes and more comments. aprogress the amount of data either read or written depending on the value of the status code. this value is relative to aprogressmax. aprogressmax the maximum amount of data that will be read or written. if unknown, 0xffffffff will be passed. see also nsitransport nsisockettransport ...
nsIURIFixup
xup_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 autf8string auritext, in ...
nsIURLFormatter
ing to mozilla websites are strongly encouraged to use urls of the following format: http[s]://%service%.mozilla.[com|org]/%locale%/ method overview astring formaturl(in astring aformat); astring formaturlpref(in astring apref); methods formaturl() formats a string url. the set of known variables is predefined. if a variable is unknown, it is left unchanged and a non-fatal
error is reported. astring formaturl( in astring aformat ); parameters aformat unformatted url as a string. return value the formatted url. formaturlpref() formats a string url stored in a preference. if the preference value cannot be retrieved, a fatal
error is reported and the "about:blank" url is returned. astring formaturlpref( in astring apref ); parameters apref a string ...
nsIVariant
e xpcom interface guidelines getasid() nsresult getasid( out nsid retval ); parameters retval if the internal value is an iid then it is returned. if it is of type interface pointer then then iid of the pointer is returned. if it is of string type then an attempt is made to convert the string to an iid. return value if the conversion succeeds, ns_ok is returned, otherwise ns_
error_cannot_convert_data is returned. native code only!getasint16 print16 getasint16(); parameters none. return value if the internal value is a string, it is first converted to a double, if possible. if it within the numeric limits of a print16 then the value is returned. native code only!getasint32 print32 getasint32(); parameters none. return value if the internal value is a string, it is first c...
nsIWeakReference
y 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 ...
nsIWebBrowserChrome
called when the status text in the chrome needs to be updated. void setstatus( in unsigned long statustype, in wstring status ); parameters statustype indicates what is setting the text. status status string. null is an acceptable value meaning no status. showasmodal() shows the window as a modal window. void showasmodal(); parameters none. return value note: the function
error code returned by this corresponds to the status value specified in exitmodaleventloop. sizebrowserto() tells the chrome to size itself such that the browser will be the specified size. void sizebrowserto( in long acx, in long acy ); parameters acx new width of the browser. acy new height of the browser. ...
nsIWebNavigation
he object can go forward. if true this indicates that there is forward session history available for navigation. read only. currenturi nsiuri the currently loaded uri or null. read only. document nsidomdocument retrieves the current dom document for the frame, or lazily creates a blank document if there is none. this attribute never returns null except for unexpected
error situations. read only. referringuri nsiuri the referring uri for the currently loaded uri or null. read only. sessionhistory nsishistory the session history object used by this web navigation instance. methods goback() tells the object to navigate to the previous session history item. when a page is loaded from session history, all content is loaded from the...
nsIWorkerGlobalScope
' of a worker. this interface allows a worker to look up information about itself, as well as to control itself. 1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) attributes attribute type description location nsiworkerlocation read only. navigator nsiworkernavigator read only. on
error nsidomeventlistener self nsiworkerglobalscope returns the global scope object itself. read only. see also using web workers nsiworkermessageport nsiworkermessageevent nsiworkerscope nsiabstractworker nsiworker ...
nsIWritablePropertyBag
o 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. ...
nsIXMLHttpRequestUpload
is interface provides access to the features needed when uploading data using nsixmlhttprequest. ...
nsIXPCException
is a javascript constructor to create nsixpcexception objects. ...
nsIXPCScriptable
ust return pr_false to indicate failure. newresolve() this method is called when the want_newresolve flag is set. when this method is called, xpconnect is attempting to resolve a lazy property named by id on obj. the js engine will check if the property named by id is defined after this method has been called. this is very similar to jsnewresolveop. if an implementation of this method throws an
error code, the prototype chain will not be checked for the property. prbool newresolve( in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in pruint32 flags, out jsobjectptr objp ); parameters wrapper cx the pointer to the jscontext newresolve is being called from. obj the pointer to the jsobject that the property named by id that is b...
nsIXmlRpcClient
idictionary: struct note that both nsisupportsarray and nsidictionary can only hold 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::getpendingexception()->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 ...
NS_WARNING
summary macro shows a warning on the console (stderr) and in debug logs (nspr logging). contrary to ns_
error this is meant for noncritical
errors. syntax ns_warning("warning text"); ...
NS_CStringAppendData
ng [in] a nsacstring instance to be modified. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null-terminated. return values the ns_cstringappenddata function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringappenddata(str, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello world" ns_cstringcontainerfinish(str); history this function was frozen f...
NS_CStringContainerInit
nce summary the ns_cstringcontainerinit function initializes a nscstringcontainer instance for use as a nsacstring. #include "nsstringapi.h" nsresult ns_cstringcontainerinit( nscstringcontainer& astring ); parameters astring [in] a nscstringcontainer instance to be initialized. return values the ns_cstringcontainerinit function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is equivalent to ns_cstringcontainerinit2(container, nsnull, 0, 0). the nscstringcontainer structure has private members that should not be accessed directly. after a nscstringcontainer object has been initialized via ns_cstringcontainerinit, it may be used as an ordinary nsacstring object. with ns_cstringcontainerinit, the coder is required to call ns_cstringcontai...
NS_CStringContainerInit2
e data pointer. the caller must have allocated the data array using the xpcom memory allocator. this flag should not be combined with ns_cstring_container_init_depend. ns_cstring_container_init_substring data passed into ns_cstringcontainerinit2 is a substring that is not null-terminated. return values the ns_cstringcontainerinit function returns ns_ok if successful. otherwise, it returns an
error code. remarks after a nscstringcontainer object has been initialized via ns_cstringcontainerinit2, it may be used as an ordinary nsacstring object. when the string object is no longer needed, it should be passed to ns_cstringcontainerfinish to free any extra memory that the string object may have allocated. it is generally better to use one of the helper classes, such as nscstring, instead of ...
NS_CStringCopy
ance to another. this is a low-level api. #include "nsstringapi.h" nsresult ns_cstringcopy( nsacstring& adeststring, const nsacstring& asrcstring ); parameters adeststring [in] a nsacstring instance to be modified. asrcstring [in] a nsacstring instance containing the new string value. return values the ns_cstringcopy function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsacstring& avalue) { return ns_cstringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(...
NS_CStringCutData
ring [in] a nsacstring instance to be modified. acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. pass pr_uint32_max to specify the length from acutstart to the end of the string. return values the ns_cstringcutdata function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange . example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello world"); // remove " world" portion of string ns_cstringcutdata(str, 5, pr_uint32_max); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello" ns_cst...
NS_CStringInsertData
ffer specifying where to place the given characters. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_cstringinsertdata function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringinsertdata(str, 5, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello world" ns_cstringcontainerfinish(str); history this fu...
NS_CStringSetData
astring [in] a nsacstring instance to modify. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null-terminated. return values the ns_cstringsetdata function returns ns_ok if successful. otherwise, it returns an
error code. example nscstringcontainer str; rv = ns_cstringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_cstringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsacstring&| parameter. } ns_cstringcontainerfinish(str); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsacstrin...
NS_CStringSetDataRange
ction to replace, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_cstringsetdatarange function returns ns_ok if successful. otherwise, it returns an
error code. example // replace all occurances of |matchval| with |newval| void replacesubstring(nsacstring& str, const nsacstring& matchval, const nsacstring& newval) { const char* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_cstringgetdata(str, &sp); ml = ns_cstringgetdata(matchval, &mp); nl = ns_cstringgetdata(newval, &np); for (const char* ...
NS_CStringToUTF16
be converted. asrcencoding [in] the character encoding of the source string. see nscstringencoding for the set of values that can be passed for this parameter. adest [out] a nsastring instance that will contain the result of the conversion. the result will be encoded using the host byte order. return values the ns_cstringtoutf16 function returns ns_ok if successful. otherwise, it returns an
error code. the set of possible
error codes is currently unspecified. example code nsembedcstring str("hello"); nsembedstring ustr; ns_cstringtoutf16(str, ns_cstring_encoding_ascii, ustr); const prunichar *unicharbuf = ustr.get(); history this function was frozen for mozilla 1.7. see bug bug 239123 for details. see also nsacstring, nsastring, nscstringencoding ...
NS_StringAppendData
string [in] a nsastring instance to be modified. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringappenddata function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello"); ns_stringappenddata(str, l" world"); c...
NS_StringContainerInit
gcontainerinit function initializes a nsstringcontainer instance for use as a nsastring. this is a low-level api. #include "nsstringapi.h" nsresult ns_stringcontainerinit( nsstringcontainer& astring ); parameters astring [in] a nsstringcontainer instance to be initialized. return values the ns_stringcontainerinit function returns ns_ok if successful. otherwise, it returns an
error code. remarks the nsstringcontainer structure has unspecified size and layout. its members may not be accessed directly. after a nsstringcontainer object has been initialized, it may be used as an ordinary nsastring object. the internal buffer allocated by a nsstringcontainer is always null-terminated. with ns_stringcontainerinit, the coder is required to call ns_stringcontainerfinish when done w...
NS_StringCopy
e to another. this is a low-level api. #include "nsstringapi.h" nsresult ns_stringcopy( nsastring& adeststring, const nsastring& asrcstring ); parameters adeststring [in] a nsastring instance to be modified. asrcstring [in] a nsastring instance containing the new string value. return values the ns_stringcopy function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example code /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsastring& avalue) { return ns_stringcopy(avalue, mvalue); } ns_imethodimp mycompon...
NS_StringCutData
ng [in] a nsastring instance to be modified. acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. pass pr_uint32_max to specify the length from acutstart to the end of the string. return values the ns_stringcutdata function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange. note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello world"); // remove " world" portion of stri...
NS_StringInsertData
r specifying where to place the given characters. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringinsertdata function returns ns_ok if successful. otherwise, it returns an
error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange . note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello"); ns_stringinsertdata(str, 5, l" world");...
NS_StringSetData
parameters astring [in] a nsastring instance to modify. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringsetdata function returns ns_ok if successful. otherwise, it returns an
error code. example code nsstringcontainer str; rv = ns_stringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_stringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsastring&| parameter. } ns_stringcontainerfinish(str); } history this function was frozen for mozilla 1.7. see bug 239123 for details. se...
NS_StringSetDataRange
the section to replace, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringsetdatarange function returns ns_ok if successful. otherwise, it returns an
error code. example code // replace all occurances of |matchval| with |newval| void replacesubstring(nsastring& str, const nsastring& matchval, const nsastring& newval) { const prunichar* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_stringgetdata(str, &sp); ml = ns_stringgetdata(matchval, &mp); nl = ns_stringgetdata(newval, &np)...
NS_UTF16ToCString
e string should be encoded using the host byte order. adestencoding [in] the character encoding of the destination string. see nscstringencoding for the set of values that can be passed for this parameter. adest [out] a nsacstring instance that will contain the result of the conversion. return values the ns_utf16tocstring function returns ns_ok if successful. otherwise, it returns an
error code. the set of possible
error codes is currently unspecified. example code // convert utf-16 (or ucs-2) string to utf-8 void copyutf16toutf8(const nsastring& in, nsacstring& out) { ns_utf16tocstring(in, ns_cstring_encoding_utf8, out); } history this function was frozen for mozilla 1.7. see bug bug 239123 for details. see also nsacstring, nsastring, nscstringencoding ...
Performance
see that it is not using an index, so this query would be slow. you can download the command line tool from the sqlite download page. be sure you have a version of the command line tool that is at least as recent as what mozilla uses. as of april 10, 2006, mozilla uses sqlite 3.3.4, but the latest precompiled version of the command line tools is not available for all platforms. this will lead to
errors that say "database is encrypted" because the tool is not able to recognize the file format. you may want to check the sqlite_version definition in db/sqlite3/src/sqlite3.h for the current version if you are having problems. caching sqlite has a cache of database pages in memory. it keeps pages associated with the current transaction so it can roll them back, and it also keeps recently used ones ...
Using nsIDirectoryService
cument. bear in mind that this list is not static. components can add and remove locations at their will. second, you must acquire the implementation and call get() passing the known string key. in the example below, prop is a string that references your requested file locations. ...
Using the clipboard
kselectionclipboard instead, you will copy into the selection buffer, which is generally only available on unix systems. this multi-step process has resulted in text being copied on the clipboard. we can cut to the clipboard instead of copying by doing a copy and then deleting the original data. normally, the text would be in a document or textbox. ...
XPCOM
the cycle collector introduced into xpcom for firefox 3, including a description of the steps involved in modifying an existing c++ class to participate in xpcom cycle collection. ...
XSLT 2.0
by java 1.6v12+ instead of mozilla-specific code) to connect with the java-based saxon-b library, and adds support for having xslt performed automatically when visiting a page with the appropriate xslt processing instruction (and which isn't processed by firefox's own xslt 1.0 processor). for developers saxon-ce a javascript api is provided for initiating an xslt 2.0 transform from a web page.
error and diagnostics output from saxon-ce can be reviewed in the firefox developer console or in firebug. saxon-b the extension demonstrates how one can use liveconnect code to communicate with the saxon-b library, but one might find the javascript code module approach used inside the extension xquseme as a more reusable approach. the code does not currently work on the mac (except for server editi...
Account Provisioner
nt provisioner gives the user the chance to search for and order a vanity email account from a list of partner providers. if the user already has an email account, the user can switch to the original account setup wizard. debugging the account provisioner dialog logs most if not all of its activities, which is useful for debugging. logs can either be dumped to the terminal via dump, or to the
error console. to have logs dumped to the terminal, create a string preference called mail.provider.logging.dump and set its value to all. to have logs dumped to the
error console, create a string preference called mail.provider.logging.console and set its value to all. a mozillazine article on how to set preferences in thunderbird. ...
Address Book examples
you are searching for 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 = se...
Index
d of an email (if it exists, it if often not set). if you are unfamiliar with the setup and 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 ...
MailNews fakeserver
se is very small, most people shouldn't have to write an entirely new daemon and handler setup by themselves. that said, someone writing a new test may have to take into account a new handler. a handler will contain the following methods: <caption> handler methods </caption> name arguments returns notes [command] rest of sent line server's response the name is normalized to be uppercase. on
error command, rest of sent line server's response called if handler does not define the command function. onstartup none server's response called when a connection is made. onmultiline sent line server's response or nothing called when in multi-line mode. postcommand server object none called after every command. the server is smart about the responses and will normalize all occurrences of '...
Thunderbird Binaries
cutting-edge builds. they are built every 24 hours by the tinderboxes from the very latest source code. there are various sorts of nightly builds available for download. if you wish to download nightly builds to help us test for the next release, please read the testing page for where we need help. warning: whilst developers try to ensure that nightly builds are stable, it is possible that
errors can get into nightly builds that can destroy your data or harm it. they should only be used for testing purposes. if you wish to use a nightly build on your main profile, you should make sure you back up your profile. nightly builds from the comm-central trunk the trunk is the central source code that is used for continuous and ongoing development. trunk builds contain the very latest bleed...
Thunderbird extensions
debugging, gloda indexing more thunderbird-specific links some links may be out of date, but they still provide valuable information on the codebase. ...
Using js-ctypes
:('); } for (var cfstr in mycfstrs) { if (mycfstrs.hasownproperty(cfstr)) { var rez_cfrelease = cfrelease(mycfstrs[cfstr]); // returns void } } libcf.close(); calling libc routines on linux/posix this example demonstrates how to use ctypes to call a libc function on linux. /* import js-ctypes */ var {cu} = require("chrome"); var {ctypes} = cu.import("resou...
Library
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 type
error 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 to the declare function. the first being the same as in the...
js-ctypes reference
stantiated by calling ctype objects as functions. these distinctions are crucial, and understanding them will alleviate much of the confusion surrounding js-ctypes. calling a type constructor will return a ctype. calling a ctype will return a cdata. you declare the arguments and return value of a native function with ctype objects. you call a native function with cdata objects. other features
error-handling js-ctypes supports both errno (on all platforms) and getlast
error (on windows platforms). callbacks you can pass regular javascript functions as callbacks to native functions. see the callbacks page for details. 64-bit integer handling because javascript number objects can't directly represent every possible 64-bit integer value, js-ctypes provides new types for these. see int64 and...
Blocking By Domain - Plugins
o the plugin block list. list contents and updates the plugin block lists are freely-licensed lists maintained by mozilla in github. the initial contents of the third-party plugin block list are based on disconnect's open source blocklist. subsequent updates to the list will be made using telemetry from firefox experiments. in general, sites will not be removed from the list unless there is an
error that renders a site in a seriously defective manner. any concerns or questions about the plugin block lists should be directed to plugin-blocking-by-domain@mozilla.com. ...
Gecko Plugin API Reference - Plugins
ault npn_evaluate npn_getproperty npn_setproperty npn_removeproperty npn_hasproperty npn_hasmethod npn_setexception 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 creation original document information copyright information: netscape communication ...
Wait-cursor - XUL
maybe i'm missing something here, but window.setattribute(...) throws an
error. i'm using window.setcursor('wait') and window.setcursor('auto') for get this effect. - ng.mangine ...
Debugging service workers - Firefox Developer Tools
ce worker in action in the applications panel, you need to successfully register it. registration is done with a block of code along these lines, using the register() method: if('serviceworker' in navigator) { navigator.serviceworker .register('sw.js') .then(function() { console.log('service worker registered'); }); } if you get the path wrong, for example, you'll get an
error in the web console giving you a hint as to what's wrong, which depends on what exactly is wrong with the code. if this is not enough to help you figure out the problem, you could also try going to the javascript debugger and stepping through your code to pinpoint exactly where it is going wrong. debugging your service worker in any case, when the service worker is successfully registered, you'l...
Set a conditional breakpoint - Firefox Developer Tools
line: when the program reaches that line, the debugger pauses. a conditional breakpoint also has a condition associated with it, which is represented as an expression. when the program reaches the line, the debugger pauses only if the breakpoint's specified expression evaluates to true. this makes it possible to debug specific scenarios, such as bugs that only happen on odd entries in a list, or
errors that occur the last time through a loop, for example. to set a conditional breakpoint, activate the context menu in the source pane, on the line where you want the breakpoint, and select "add conditional breakpoint". you'll then see a textbox where you can enter the expression. press return to finish. conditional breakpoints are shown as orange arrows laid over the line number. if you conte...
Step through code - Firefox Developer Tools
this lets you know what kind of breakpoint the code is paused on (breakpoint, event breakpoint, etc.), and also provides a step button and a play button. the thinking here is that if you've got your devtools open in a separ...
Debugger.Source - Firefox Developer Tools
a a header in the http reply that carried the generated javascript.) this property is writable, so you can change the source map url by setting it. all debugger.source objects referencing the same source will see the change. setting an empty string has no effect and will not change existing value. if the instance refers to webassembly code, null. attempts to write to this property throw a type
error. displayurl if the script had a special //# sourceurl comment, as described in the source maps specification, then this property’s value holds the string that was given. otherwise, this is null. element the debugger.object instance referring to the dom element to which this source code belongs, if any, or undefined if it belongs to no dom element. source belongs to a dom element in the ...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
e.column; } else { name = '(root)'; place = ''; } console.log(indent + totals.get(site) + ': ' + name + place); for (let [child, grandchildren] of children) walk(child, grandchildren, indent + ' '); } walk(null, rootchildren, ''); } })(); in the scratchpad, ensure that no text is selected, and press the "run" button. (if you get an
error complaining that components.utils is not defined, be sure you've selected browser from the scratchpad's environment menu, as described in step 2.) save the following html text to a file, and visit the file in your browser. make sure the current browser tab is displaying this page. <div onclick="dodivsandspans()"> click here to make the page do some allocations. </div> <script> funct...
Debugger-API - Firefox Developer Tools
language’s implementation. 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...
The Firefox JavaScript Debugger - Firefox Developer Tools
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 expressions reference keyboard shortcuts source map
errors ...
Deprecated tools - Firefox Developer Tools
b on macos) when in editor mode, the enter key adds a new line in the input, and you can evaluate the expression using ctrl + enter (cmd + enter on macos). when evaluating, the input isn't cleared, which makes it possible to quickly iterrate over a snippet of code. the results are displayed in the console output, to the right of the input, providing immediate feedback. unlike in scratchpad,
errors are properly displayed in the output with an expandable stacktrace, making it easier to debug the code you're currently writing. starting firefox 72, you can import a javascript file content in the console input with ctrl + o (cmd + o on macos), as well as saving the console input content to a file using ctrl + s (cmd + s on macos). webide and connect page webide was deprecated as of firefox ...
Index - Firefox Developer Tools
eakpoints debugger, dev tools, event debugging, event handler, event listener, javascript debugging, tools, breakpoint, events starting with firefox 69, debugging an application that includes event handlers is simplified because the debugger now includes the ability to automatically break when the code hits an event handler. this article explains how to use it. 137 source map
errors debugger, debugging, dev tools, reference, source maps, tools source maps are json files providing a way to associate transformed sources, as seen by the browser, with their original sources, as written by the developer. you can sometimes encounter problems working with source maps. this page explains the most common problems and how to fix them. 138 ui tour this...
Network request list - Firefox Developer Tools
th a name that matches the specified value. set-cookie-name:_ga set-cookie-value shows the resources that have a set-cookie header with a value that matches the specified value. set-cookie-value:true regexp shows the resources having a url that matches the given regular expression. regexp:\d{5} regexp:mdn|mozilla for example, to find all 404, not found,
errors, you can type "404" into the search and auto-complete suggests "status-code:404" so you'll end up with something like this: search in requests use the search panel to run a full-text search on headers and content. click the search icon in the toolbar. this opens the search sidebar. enter a string in the search field of the sidebar, and press enter or return. the search results area be...
Examine and edit CSS - Firefox Developer Tools
ce (as of firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to true in the configuration editor to enable this feature); change the display based on print media rules. a warning icon appears next to unsupported css properties or rules that have invalid values. this can help you understand why certain styles are not being applied. in the following example, a spelling
error, "background-colour" instead of "background-color" has made the rule invalid: rule display it displays each rule as in a stylesheet, with a list of selectors followed by a list of property:value; declarations. highlight matched elements: next to the selector is a target icon: click this to highlight all nodes in the page that match this selector. overridden declaration: declarations tha...
Validators - Firefox Developer Tools
rietary html as well as invalid html. w3c css validator the w3c css validator will validate the css within any web page or external css files according to the w3c css standards. w3c rdf validator the rdf validator service will validate the rdf/xml contained on a given uri. link checker this tool will check links on a given web page. html tidy html tidy is a tool that can be used to report
errors in an html page and to format web pages for better reading. (some authoring software, such as html-kit, builds in html tidy which makes validation quick and easy.) html validator pro this is an automated html5 checker using the same validator as the w3c. provide a starting url and the tool will find and validate all pages in a website. accessibility services lynx viewer checks a web page us...
Web Console Helpers - Firefox Developer Tools
nded to the file name. --selector string the css query selector for a single element on the page. when supplied, only this element will be included in the screenshot. :unblock (starting in firefox 80) followed by an unquoted string, removes blocking for urls containing that string. in the network monitor, the string is removed from the request blocking sidebar. no
error is given if the string was not previously blocked. values() given an object, returns a list of the values on that object; serves as a companion to keys(). please refer to the console api for more information about logging from content. variables tempn the "use in console" option in the inspector generates a variable for a node named temp0, temp1, temp2, etc. referencing the node. examp...
The JavaScript input interpreter - Firefox Developer Tools
rk next to it when the feature is enabled, which is missing when it is disabled. select the menuitem to change the state. instant evaluation this feature is available in firefox nightly, in versions labeled 74 and later. when the "instant evaluation" feature is enabled, the interpreter displays results of expressions as you're typing them in single-line mode. note that the result might be an
error message. expressions that have side effects are not evaluated. you can enable or disable instant evaluation via the settings ("gear") menu in the web console toolbar. the menuitem instant evaluation has a checkmark next to it when the feature is enabled, which is missing when it is disabled. select the menuitem to change the state. execution context code that you have executed becomes part of ...
Web Console UI Tour - Firefox Developer Tools
the web console's interface is split into three horizontal sections, detailed in the sections below. toolbar the toolbar across the top contains a number of features: garbage can: click this icon to clear the contents of the console. funnel: click this icon to filter the messages that are displayed in the console. filter categories: you can click a filter category (such as
errors, warnings, css, or xhr) to display just those types of messages. settings ("gear" menu): new in firefox 71, you can click the gear icon to access the new settings menu, where you can toggle the following features on and off: persist logs: when enabled, the console doesn't clear on page reload, or new page load. show timestamps: when enabled, timestamps are shown on the left-hand side of each messag...
Web Console - Firefox Developer Tools
the javascript input interpreter how to interact with a document using the console. split console use the console alongside other tools. console messages details of the messages that the console logs. ...
ANGLE_instanced_arrays.drawArraysInstancedANGLE() - Web APIs
.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 comment angle_instanced_arraysthe definition of 'angle_ins...
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
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); specifications specification status comment angl...
AbortController.AbortController() - Web APIs
= document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.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 an abort
error. 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 ...
AbortController.abort() - Web APIs
= document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.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 an abort
error. you can find a full working example on github — see abort-api (see it running live also). specifications specification status comment domthe definition of 'abort()' in that specification. living standard initial definition ...
AbortController.signal - Web APIs
= document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.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 an abort
error. you can find a full working example on github — see abort-api (see it running live also). specifications specification status comment domthe definition of 'signal' in that specification. living standard initial definition ...
AbortController - Web APIs
= document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.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 domexception named abort
error. 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
= document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.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 an abort
error. current version of firefox rejects the promise with a domexception 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. l...
AbsoluteOrientationSensor - Web APIs
nd. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor = new absoluteorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere. model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('
error',
error => { if (event.
error.name == 'notreadable
error') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requesting permissions for multiple device sensors. because the permissions uses promises, a good way to request permissions is to use promise.all. const sensor = new absoluteorientationsensor(); promise.all([na...
AbstractWorker - Web APIs
worker interface of the web workers api is an abstract interface that defines properties and methods that are common to all types of worker, including not only the basic worker, but also serviceworker and sharedworker. as an abstract class, you don't directly interact with abstractworker. properties the abstractworker interface doesn't inherit any properties. event handlers abstractworker.on
error an eventlistener which is invoked whenever an
errorevent of type
error bubbles through the worker. methods the abstractworker interface doesn't implement or inherit any methods. example as an abstract interface, you won't directly use abstractworker in your code. instead, you'll interact with either worker or sharedworker, both of which inherit the properties of abstractworker. this code s...
Accelerometer.Accelerometer() - Web APIs
ent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var accelerometer = new accelerometer([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.on
error will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends device hardware and consequently may be less than requested. referenceframe: either 'device' or 'screen'. the default is 'device'. specifications specification status comment generic sensor api candidate recommendation de...
AmbientLightSensor.illuminance - Web APIs
that would ever be shown to a user. see feature-policy for implementation insfructions. syntax var level = ambientlightsensor.illuminance value a number indicating the current light level in lux. example if ( 'ambientlightsensor' in window ) { const sensor = new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.on
error = (event) => { console.log(event.
error.name, event.
error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recommendation defines sensors in general. ambient light sensorthe definition of 'illuminance' in that specification. candidate recommendation ...
AmbientLightSensor - Web APIs
entlightsensor() creates a new ambientlightsensor object. properties ambientlightsensor.illuminance returns the current light level in lux of the ambient light level around the hosting device. example if ( 'ambientlightsensor' in window ) { const sensor = new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.on
error = (event) => { console.log(event.
error.name, event.
error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recommendation defines sensors in general. ambient light sensorthe definition of 'ambientlightsensor' in that specification. candidate recommendation ...
AnalyserNode.fftSize - Web APIs
e 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 domexception with the name indexsize
error 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 for relevant code). var audi...
AnalyserNode.maxDecibels - Web APIs
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 -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 indexsize
error 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).
Animation.cancel() - Web APIs
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 domexception named abort
error. specifications specification status comment web animationsthe definition of 'animation.cancel()' in that specification. working draft editor's draft. ...
Animation.pause() - Web APIs
the pause() method of the web animations api's animation interface suspends playback of the animation. syntax animation.pause(); parameters none. return value none. exceptions invalidstate
error the animation's currenttime is unresolved (for example, if it's never been played or isn't currently playing) and the end time of the animation is positive infinity. throws an invalidstate
error if the animation's currenttime is unresolved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. example animation.pause() is used many times in the alice in web animations api land growing/shrinking alice game, largely because animations created with the element.animate() method immediately start playing and must be paused manually if you want to avoi...
AudioBuffer() - Web APIs
e 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 notsupported
error 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). range
error there isn't enough memory available to allocate the buffer. specifications specification status comment web audio apithe definition of 'audiobuffer' in that specification. working dr...
AudioBuffer.copyFromChannel() - Web APIs
nation 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 indexsize
error 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 its current length.
AudioBufferSourceNode.loop - Web APIs
ue); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; }, function(e){"
error with decoding audio data" + e.err}); } request.send(); } // wire up buttons to stop and play audio, and range slider control play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); playbackcontrol.removeattribute('disabled'); } specification specification status comment web audio apithe definition of 'loop' i...
AudioBufferSourceNode.loopEnd - Web APIs
loopstartcontrol.oninput = function() { source.loopstart = loopstartcontrol.value; loopstartvalue.innerhtml = loopstartcontrol.value; } loopendcontrol.oninput = function() { source.loopend = loopendcontrol.value; loopendvalue.innerhtml = loopendcontrol.value; } specifications specification status comm...
AudioBufferSourceNode.loopStart - Web APIs
loopstartcontrol.oninput = function() { source.loopstart = loopstartcontrol.value; loopstartvalue.innerhtml = loopstartcontrol.value; } loopendcontrol.oninput = function() { source.loopend = loopendcontrol.value; loopendvalue.innerhtml = loopendcontrol.value; } specifications specification status comm...
AudioBufferSourceNode.playbackRate - Web APIs
ue); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; }, function(e){"
error with decoding audio data" + e.err}); } request.send(); } // wire up buttons to stop and play audio, and range slider control play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); playbackcontrol.removeattribute('disabled'); } stop.onclick = function() { source.stop(0); play.removeattribute('disabled'); playbackcontrol.setattribut...
AudioBufferSourceNode.start() - Web APIs
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 type
error 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. invalidstate
error 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 don't need to sp...
AudioNode - Web APIs
the actual processing is done internally by the browser and cannot be altered, you could write a wrapper around an audio node to provide custom properties and methods. slightly better performance: in both chrome and firefox, the factory methods call the constructors internally. keep in mind that microsoft edge does not yet appear to support the constructors; it will throw a "function expected"
error when you use the constructors. brief history: the first version of the web audio spec only defined the factory methods. after a design review in october 2013, it was decided to add constructors because they have numerous benefits over factory methods. the constructors were added to the spec from august to october 2016. factory methods continue to be included in the spec and are not deprecated. ...
AudioParam.setValueAtTime() - Web APIs
diocontext.currenttime. the new value is given in the value parameter. syntax var audioparam = audioparam.setvalueattime(value, starttime) parameters value a floating point number representing the value the audioparam will change to at the given time. starttime a double representing the time (in seconds) after the audiocontext was first created that the change in value will happen. a type
error is thrown if this value is negative. returns a reference to this audioparam object. in some browsers older implementations of this interface return void. examples this simple example features a media element source with two control buttons (see our webaudio-examples repo for the source code, or view the example live). when the buttons are pressed, the currgain variable is incremented/decreme...
AudioProcessingEvent - Web APIs
// load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"
error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingeven...
AudioScheduledSourceNode.start() - Web APIs
r 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(). range
error 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 desired number of seconds to the context's current time stamp returne...
AudioScheduledSourceNode.stop() - Web APIs
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(). range
error 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 audiocontext(); osc = context.createoscillator(); osc.connect(context.destination);...
AudioWorkletGlobalScope.registerProcessor - Web APIs
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 notsupported
error the name is an empty string, or a constructor under the given name is already registered. registering the same name twice is not allowed. type
error 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 example we create a custom ...
AudioWorkletNode() - Web APIs
ng 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 notsupported
error the specified options.outputchannelcount is 0 or larger than the current implementation supports. indexsize
error 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 web audio apithe...
AudioWorkletNode - Web APIs
ioworkletprocessor has a static parameterdescriptors getter, the audioparamdescriptor array returned from it is used to create audioparam objects on the audioworkletnode. with this mechanism it is possible to make your own audioparam objects accessible from your audioworkletnode. you can then use their values in the associated audioworkletprocessor. event handlers audioworkletnode.onprocessor
error fired when an
error is thrown in associated audioworkletprocessor. once fired, the processor and consequently the node will output silence throughout its lifetime. methods also inherits methods from its parent, audionode. the audioworkletnode interface does not define any methods of its own. examples in this example we create a custom audioworkletnode that outputs white noise. first, we n...
AudioWorkletNodeOptions - Web APIs
meters 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. usage notes when creating an audioworkletnode, these options can have various effects. if the number of inputs and number of outputs are both set to 0, a notsupported
error will be thrown and the node construction process aborted. if the length of the outputchannelcount array doesn't match numberofoutputs, an indexsize
error will be thrown. if outputchannelcount isn't specified, and numberofinputs and numberofoutputs are both 1, the audioworkletnode's initial channel count is set to 1. this has the effect of changing the output channel count to dynamically change to...
AudioWorkletProcessor.process - Web APIs
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 onprocessor
error 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 extends audioworkletprocessor { process (inputs, outputs, parameters) { // take the first ou...
BaseAudioContext.createBuffer() - Web APIs
tes 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 notsupported
error 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). range
error 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 audiocontext(); var buffer = au...
BaseAudioContext.createIIRFilter() - Web APIs
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 invalidstate
error all of the feedforward coefficients are 0, and/or the first feedback coefficient is 0. notsupported
error 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 ...
BaseAudioContext.createPeriodicWave() - Web APIs
to define a periodic waveform that can be used to shape the output of an oscillatornode. syntax var wave = audiocontext.createperiodicwave(real, imag[, constraints]); returns a periodicwave. parameters real an array of cosine terms (traditionally the a terms). imag an array of sine terms (traditionally the b terms). the real and imag arrays have to have the same length, otherwise an
error is thrown. constraints optional an dictionary object that specifies whether normalization should be disabled (if not specified, normalization is enabled by default.) it takes one property: disablenormalization: if set to true, normalization is disabled for the periodic wave. the default is false. if normalized, the resulting wave will have a maximum absolute peak value of 1. exam...
BaseAudioContext.createScriptProcessor() - Web APIs
// load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"
error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingeven...
BasicCardRequest - Web APIs
elected: true } ] }; var options = {requestshipping: true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. }) .catch(function(err) { // do something with the
error from request.show(). }); } catch (e) { // catch any other
errors. } once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined...
BasicCardResponse.billingAddress - Web APIs
ng address of the card. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the
error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may l...
BasicCardResponse.cardNumber - Web APIs
the credit card number. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the
error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may l...
BasicCardResponse.cardSecurityCode - Web APIs
the card security code. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the
error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may l...
BasicCardResponse.cardholderName - Web APIs
name of the cardholder. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the
error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may l...
BasicCardResponse.expiryMonth - Web APIs
in the range 01 to 12. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the
error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may l...
BasicCardResponse.expiryYear - Web APIs
the range 0000 to 9999. example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the
error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may l...
BasicCardResponse - Web APIs
elected: true } ] }; var options = {requestshipping: true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. }) .catch(function(err) { // do something with the
error from request.show(). }); } catch (e) { // catch any other
errors. } once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined...
BeforeInstallPromptEvent - Web APIs
at a time of their own choosing. this method returns a promise. example window.addeventlistener("beforeinstallprompt", function(e) { // log the platforms provided as options in an install prompt console.log(e.platforms); // e.g., ["web", "android", "windows"] e.userchoice.then(function(choiceresult) { console.log(choiceresult.outcome); // either "accepted" or "dismissed" }, handle
error); }); ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
es. 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 invalidaccess
error 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 containing the input fr...
BluetoothDevice - Web APIs
id characteristic in the device_information service. bluetoothdevice.paired read only a boolean value indicating whether the device is paired with the system. bluetoothdevice.gattserver read only a reference to the device's gatt server or null if the device is disconnected. methods bluetoothdevice.watchadvertisments() a promise that resolves to undefined or is rejected with an
error if advetisments can’t shown for any reason. bluetoothdevice.unwatchadvertisments() stops watching for advertisments. bluetoothdevice.connectgatt() a promise that resolves to an instance of bluetoothgattremoteserver. specifications specification status comment web bluetooththe definition of 'bluetoothdevice' in that specification. draft initial definiti...
BluetoothRemoteGATTCharacteristic - Web APIs
scriptor for a given descriptor uuid. bluetoothremotegattcharacteristic.getdescriptors() returns a promise that resolves to an array of all bluetoothgattdescriptor objects for a given descriptor uuid. bluetoothremotegattcharacteristic.readvalue() returns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported. otherwise it throws an
error. bluetoothremotegattcharacteristic.writevalue() sets the value property to the bytes contained in an arraybuffer and returns a promise. bluetoothremotegattcharacteristic.startnotifications() returns a promise when navigator.bluetooth is added to the active notification context. bluetoothremotegattcharacteristic.stopnotifications() returns a promise when navigator.bluetooth is removed from t...
readValue() - Web APIs
syntax bluetoothremotegattdescriptor.readvalue().then(function(value[]) { ... }) returns a promise that resolves to an arraybuffer. specifications specification status comment web bluetooththe definition of 'readvalue()' in that specification. draft initial definition. ...
BluetoothRemoteGATTDescriptor - Web APIs
ristic configuration descriptor. bluetoothremotegattdescriptor.valueread only returns the currently cached descriptor value. this value gets updated when the value of the descriptor is read. methods bluetoothremotegattdescriptor.readvalue() returns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported. otherwise it throws an
error. bluetoothremotegattdescriptor.writevalue() sets the value property to the bytes contained in an arraybuffer and returns a promise. specifications specification status comment web bluetooththe definition of 'bluetoothremotegattdescriptor' in that specification. draft initial definition. browser compatibility the compatibility table on this page is genera...
Body.arrayBuffer() - Web APIs
arraybuffer(), decode the audio data using audiocontext.decodeaudiodata, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the audiocontext.destination. ...
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
an 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 streamsthe definition of 'bytelengthqueuingstrategy()' in that specification. living standard initial definition. ...
ByteLengthQueuingStrategy.size() - Web APIs
ze(chunk); parameters chunk a chunk of data being passed through the stream. return value an integer representing the byte length of the given chunk. 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 = queueingstrategy.size(chunk); specifications specification status comment streamsthe definition of 'size' in that specification. living standard initial definition. ...
ByteLengthQueuingStrategy - Web APIs
telengthqueuingstrategy object instance. properties none. methods bytelengthqueuingstrategy.size() returns the given chunk’s bytelength property. examples const queueingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... }, cancel(err) { console.log("stream
error:", err); } }, queueingstrategy); var size = queueingstrategy.size(chunk); specifications specification status comment streamsthe definition of 'bytelengthqueuingstrategy' in that specification. living standard initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to ...
CDATASection - Web APIs
e symbols < and & don’t need escaping as they normally do when inside a cdata section. in xml, a cdata section looks like: <![cdata[ ... ]]> for example: <foo>here is a cdata section: <![cdata[ < > & ]]> with all kinds of unescaped text.</foo> the only sequence which is not allowed within a cdata section is the closing sequence of a cdata section itself, ]]>: <![cdata[ ]]> will cause an
error ]]> note that cdata sections should not be used within html; they only work in xml. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveaspectratio="xminymin meet"><a xlink:href="/docs/...
CSS.registerProperty() - Web APIs
g 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 invalidmodification
error the given name has already been registered. syntax
error the given name isn't a valid custom property name (starts with two dashes, e.g. --foo). type
error 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 have it not inherit its value:...
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 type
error 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 type
error 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.max() - Web APIs
the max() method of the cssnumericvalue interface returns the highest value from among the values passed. the passed values must be of the same type. syntax var cssunitvalue = cssnumericvalue.man(number1 ... numbern); parameters number either a number or a cssnumericvalue. return value a cssunitvalue. exceptions type
error indicates that an invalid type was passed to the method. examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. // prints "2cm" console.log(css.cm("1").max(css.cm("2")).tostring()); // prints "max(1cm, 0.393701in)" console.log(css.cm("1").max(css.in("0.393701")).tostring()); specifications specification status comment css typed ...
CSSNumericValue.min() - Web APIs
the min() method of the cssnumericvalue interface returns the lowest value from among those values passed. the passed values must be of the same type. syntax var cssunitvalue = cssnumericvalue.min(number1 ... numbern); parameters number either a number or a cssnumericvalue. return value a cssunitvalue. exceptions type
error indicates that an invalid type was passed to the method. examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. // prints "1cm" console.log(css.cm("1").min(css.cm("2")).tostring()); // prints "max(1cm, 0.393701in)" console.log(css.cm("1").max(css.in("0.393701")).tostring()); specifications specification status comment css typed...
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 type
error 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 syntax
error 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 type
error 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 type
error 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.to() - Web APIs
the to() method of the cssnumericvalue interface converts a numberic value from one unit to another. syntax var cssunitvalue = cssnumericvalue.to(unit); parameters unit the unit to which you want to convert. return value a cssmathsum. exceptions syntax
error indicates that an invalid type was passed to the method. type
error indicates that the passed values cannot be summed. examples // prints "0.608542cm" console.log(css.px("23").to("com").tostring()); specifications specification status comment css typed om level 1the definition of 'to' 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 syntax
error undefined type
error 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. ...
CSSRule.cssText - Web APIs
erty of the cssrule interface returns the actual text of a cssstylesheet style-rule. note: do not confuse this property with element-style cssstyledeclaration.csstext. be aware that this property can no longer be set directly, as it is now specified to be functionally modify-only, and silently so. in other words, attempting to set it does absolutely nothing, and doesn't even omit a warning or
error. furthermore, it has no settable sub-properties. therefore, to modify it, use the stylesheet's cssrules[index] properties .selectortext and .style (or its sub-properties). see using dynamic styling information for details. syntax string = cssrule.csstext example <style> body { background-color: darkblue; } </style> <script> var stylesheet = document.stylesheets[0]; alert(stylesh...
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.setProperty() - Web APIs
ain "!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 domexception (nomodificationallowed
error): 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, and text color to random values (see the live ...
CSSStyleRule.selectorText - Web APIs
see using dynamic styling information. syntax string = cssrule.selectortext example // for cssrule: body { background-color: darkblue; } var stylesheet = document.stylesheets[0]; alert(stylesheet.cssrules[0].selectortext); // body notes the implementation may have stripped out insignificant whitespace while parsing the selector. if set to a selector string which cannot be parsed, a syntax
error is thrown. specifications specification status comment css object model (cssom)the definition of 'cssstylerule.selectortext' in that specification. working draft browser compatibility the compatibility table in 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-d...
CSSStyleSheet - Web APIs
to apply to the matching elements. this differs from insertrule(), which simply takes the textual representation of the entire rule as a single string. removerule() functionally identical to deleterule(); removes the rule at the specified index from the stylesheet's rule list. notes in some browsers, if a stylesheet is loaded from a different domain, accessing cssrules results in security
error. a stylesheet is associated with at most one document, which it applies to (unless disabled). a list of cssstylesheet objects for a given document can be obtained using the document.stylesheets property. a specific style sheet can also be accessed from its owner object (node or cssimportrule), if any. a cssstylesheet object is created and inserted into the document's document.stylesheets list a...
Using the CSS properties and values API - Web APIs
up a transition from one value to another. when registered, though, you've told the browser what type of value it should expect, and because it knows that, it can then set up the transitions properly. gotchas there are two gotchas when registering a property. the first is that, once a property is registered, there's no way to update it, and trying to re-register it with javascript will throw an
error indicating it's already been defined. second, unlike standard properties, registered properties aren't validated when they're parsed. rather, they're validated when they're computed. that means both that invalid values won't appear as invalid when inspecting the element's properties, and that including an invalid property after a valid one won't fall back to the valid property. an invalid proper...
CSS Typed Object Model API - Web APIs
mericvalue an interface representing operations that all numeric values can perform, including: cssnumericvalue.add - adds supplied numbers to the cssnumericvalue. cssnumericvalue.sub - subtracts supplied numbers to the cssnumericvalue. cssnumericvalue.mul - multiplies supplied numbers to the cssnumericvalue. cssnumericvalue.div - divides a supplied number by other numbers, throwing an
error if 0. cssnumericvalue.min - returns the minimum value passed cssnumericvalue.max - returns the maximum value passed cssnumericvalue.equals - returns true if all the values are the exact same type and value, in the same order. otherwise, false cssnumericvalue.to - converts value into another one with the specified unit. cssnumericvalue.tosum cssnumericvalue.type cssnumericvalue.parse...
Cache.addAll() - Web APIs
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 type
error 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 an installevent to fire, then runs waituntil() to handle th...
Cache.match() - Web APIs
addeventlistener('fetch', function(event) { // we only want to call event.respondwith() if this is a get request for an html document. if (event.request.method === 'get' && event.request.headers.get('accept').indexof('text/html') !== -1) { console.log('handling fetch event for', event.request.url); event.respondwith( fetch(event.request).catch(function(e) { console.
error('fetch failed; returning offline page instead.', e); return caches.open(offline_cache).then(function(cache) { return cache.match(offline_url); }); }) ); } }); specifications specification status comment service workersthe definition of 'cache match' in that specification. working draft initial definition. ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
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 security
error (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 var stream = canvaselt.capturestream(25); // 25 fps // send the current state of the canvas as a frame to the stream stream.getvideotracks()[0].requestframe(); ...
CanvasRenderingContext2D.createImageData() - Web APIs
ctangle around the vertical axis. height the height to give the new imagedata object. a negative value flips the rectangle around the horizontal axis. imagedata an existing imagedata object from which to copy the width and height. the image itself is not copied. return value a new imagedata object with the specified width and height. the new object is filled with transparent black pixels.
errors thrown indexsize
error thrown if either of the width or height arguments is zero. examples creating a blank imagedata object this snippet creates a blank imagedata object using the createimagedata() method. html <canvas id="canvas"></canvas> javascript the generated object is 100 pixels wide and 50 pixels tall, making 5,000 pixels in all. each pixel within an imagedata object consist...
CanvasRenderingContext2D.drawImage() - Web APIs
wn. 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 canvas using the drawimage() method. html <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" h...
CanvasRenderingContext2D.getImageData() - Web APIs
e 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 indexsize
error thrown if either sw or sh are zero. security
error 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 security
error 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 image data from a ...
CanvasRenderingContext2D.putImageData() - Web APIs
rom which the image data will be extracted. defaults to 0. dirtyy optional vertical position (y coordinate) of the top-left corner from which the image data will be extracted. defaults to 0. dirtywidth optional width of the rectangle to be painted. defaults to the width of the image data. dirtyheight optional height of the rectangle to be painted. defaults to the height of the image data.
errors thrown notsupported
error thrown if any of the arguments is infinite. invalidstate
error thrown if the imagedata object's data has been detached. examples understanding putimagedata to understand what this algorithm does under the hood, here is an implementation on top of canvasrenderingcontext2d.fillrect(). html <canvas id="canvas"></canvas> javascript var canvas = document.getelem...
ChannelMergerNode() - Web APIs
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 invalidstate
error 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.remove() - Web APIs
ove() <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <div id="div-03">here is div-03</div> var el = document.getelementbyid('div-02'); el.remove(); // removes the div with the 'div-02' id childnode.remove() is unscopable the remove() method is not scoped into the with statement. see symbol.unscopables for more information. ...
Clients.openWindow() - Web APIs
in firefox, the method is allowed to show popups only when called as the result of a notification click event. in chrome for android, the method may instead open the url in an existing browsing context provided by a standalone web app previously added to the user's home screen. as of recently, this also works on chrome for windows. ...
Clipboard.read() - Web APIs
lue a promise that resolves with a datatransfer object containing the clipboard's contents. the promise is rejected if permission to access the clipboard is not granted. example after using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard. if it's not a png image, an
error message is presented. otherwise, an image element referred to using the variable imgelem has its source replaced with the clipboard's contents. // first, ask the permissions api if we have some kind of access to // the "clipboard-read" feature. navigator.permissions.query({name: "clipboard-read"}).then(result => { // if permission to read the clipboard is granted or if the user will // be p...
ClipboardItem() - Web APIs
board api. note: you can only pass in one clipboard item at a time. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.
error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification. working draft initial definition. ...
ContentIndex.add() - Web APIs
ult. 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 type
error 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 the content ind...
ConvolverNode() - Web APIs
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 notsupported
error 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. browser compatibility the compatibility table on this page i...
ConvolverNode.buffer - Web APIs
convolver.buffer = concerthallbuffer; specifications specification status comment web audio apithe definition of 'buffer' in that specification. working draft ...
ConvolverNode.normalize - Web APIs
convolver.normalize = false; // must be set before the buffer, to take effect convolver.buffer = concerthallbuffer; specifications specification status comment web audio apithe definition of 'normalize' in that specification. working draft ...
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
t 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 streamsthe definition of 'countqueuingstrategy()' in that specification. living standard initial definition. ...
CountQueuingStrategy.size() - Web APIs
the total queue size is a count of the number of chunks in the queue. syntax var size = countqueuingstrategy.size(); parameters none. return value 1. 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 streamsthe definition of 'size' in that specification. living standard initial definition. ...
CountQueuingStrategy - Web APIs
or countqueuingstrategy() creates a new countqueuingstrategy object instance. properties none. methods countqueuingstrategy.size() returns 1. examples const queueingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... }, abort(err) { console.log("sink
error:", err); } }, queueingstrategy); var size = queueingstrategy.size(); specifications specification status comment streamsthe definition of 'countqueuingstrategy' in that specification. living standard initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data,...
CredentialsContainer.get() - Web APIs
. valid values 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 "abort
error" domexception. 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. ...
Crypto.getRandomValues() - Web APIs
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. domexception (name: quotaexceeded
error) 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 degree of entropy mandated by the web cryptography...
CustomElementRegistry.upgrade() - Web APIs
the upgrade() method of the customelementregistry interface upgrades all shadow-containing custom elements in a node subtree, even before they are connected to the main document. syntax customelements.upgrade(root); parameters root a node instance with shadow-containing descendant elements that are to be upgraded. if there are no descendant elements that can be upgraded, no
error is thrown. return value void. examples taken from the html spec: const el = document.createelement("spider-man"); class spiderman extends htmlelement {} customelements.define("spider-man", spiderman); console.assert(!(el instanceof spiderman)); // not yet upgraded customelements.upgrade(el); console.assert(el instanceof spiderman); // upgraded! specifications specification status ...
CustomElementRegistry.whenDefined() - Web APIs
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 syntax
error if the provided name is not a valid custom element name, the promise rejects with a syntax
error. 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 class="menu-placeholder">loading...</div> <nav-menu> ...
DOMConfiguration - Web APIs
note: this interface has never been supported in gecko, and has been removed from the dom specification. ...
DOMException() - Web APIs
mexception object with a specified message and name. syntax var domexception = new domexception(); var domexception = new domexception(message); var domexception = new domexception(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 domexception a newly created domexception object. example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification. candidate recommendation adds the constructor for the domexception class. browser compatibility the compatibility table on this page is generated from stru...
DOMException.code - Web APIs
this field is used for historical reasons. new dom exceptions don't use this anymore: they put this info in the domexception.name attribute. syntax var domexceptioncode = domexceptioninstance.code; value a short number. 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. ...
DOMException.message - Web APIs
syntax var domexceptionmessage = domexceptioninstance.message; value a domstring. 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. ...
DOMLocator - Web APIs
properties domlocator.linenumber read only returns a positive integer or -1. domlocator.columnnumber read only returns a positive integer or -1. domlocator.byteoffset read only returns a positive integer or -1. domlocator.utf16offset read only returns a positive integer or -1. domlocator.relatednode read only returns a positive integer or -1. domlocator.uri read only returns a positive integer or -1. methods this interface neither implements, nor inherits, any method. ...
DOMMatrix - Web APIs
the specified 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 type
error 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 type
error exception is thrown. frommatrix() creates a new mutable dommatrix object given an existing matrix or a dommatrixini...
DOMTokenList.remove() - Web APIs
return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. ...
DataTransferItemList.add() - Web APIs
ng 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 notsupported
error 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, drag it to the drop zone...
DataTransferItemList.remove() - Web APIs
he 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 invalidstate
error 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; datalist.add(ev.target.id, "...
DisplayMediaStreamConstraints.audio - Web APIs
is to be included in the stream. if a mediatrackconstraints object is given, and an audio source is available, an audio track matching the settings given in the constraints object is included in the mediastream returned by getdisplaymedia(). if no audio source is available, or the user agent doesn't support audio tracks with getdisplaymedia(), the returned mediastream has no audio track, but no
error occurs. the audio track is always considered optional. example specifications specification status comment unknownthe definition of 'displaymediastreamconstraints.audio' in that specification. unknown initial definition ...
DisplayMediaStreamConstraints - Web APIs
the mediastream. the default value is false. video if true (the default), the display contents are included in a mediastreamtrack within the stream provided by getdisplaymedia(). optionally, a mediatrackconstraints object may be given, providing options specifying processing to be performed on the video data before adding it to the stream. a value of false is not permitted, and results in a type
error being thrown. specifications specification status comment unknownthe definition of 'displaymediastreamconstraints' in that specification. unknown initial definition ...
Document.createCDATASection() - Web APIs
ome <cdata> data & then some'); docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err. 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 th...
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.evaluate() - Web APIs
the first node in the document that matches the expression. first_ordered_node_type 9 a result set containing the first node in the document that matches the expression. results of node_iterator types contain references to nodes in the document. modifying a node will invalidate the iterator. after modifying a node, attempting to iterate through the results will result in an
error. results of node_snapshot types are snapshots, which are essentially lists of matched nodes. you can make changes to the document by altering snapshot nodes. modifying the document doesn't invalidate the snapshot; however, if the document is changed, the snapshot may not correspond to the current state of the document, since nodes may have moved, been changed, added, or removed. specifications ...
Document.exitPointerLock() - Web APIs
the exitpointerlock() method asynchronously releases a pointer lock previously requested through element.requestpointerlock. to track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlock
error events. syntax document.exitpointerlock(); specifications specification status comment pointer lockthe definition of 'document' in that specification. candidate recommendation extend the document interface ...
Document.head - Web APIs
doctype html> <head id="my-document-head"> <title>example: using document.head</title> </head> <script> var thehead = document.head; console.log(thehead.id); // "my-document-head"; console.log( thehead === document.queryselector("head") ); // true </script> notes document.head is read-only. trying to assign a value to this property will fail silently or, in strict mode, throws a type
error . specifications specification status comment html 5.1the definition of 'document.head' in that specification. recommendation html5the definition of 'document.head' in that specification. recommendation html living standardthe definition of 'document.head' in that specification. living standard initial definition. ...
Document.open() - Web APIs
port a two-argument document.open(), with the following signature: document.open(type, replace) where type specified the mime type of the data you are writing (e.g. text/html) and replace if set (i.e. a string of "replace") specified that the history entry for the new document would replace the current history entry of the document being written to. this form is now obsolete; it won't throw an
error, but instead just forwards to document.open() (i.e. is the equivalent of just running it with no arguments). the history-replacement behavior now always happens. specifications specification status comment html living standardthe definition of 'document.open()' in that specification. living standard document object model (dom) level 2 html specificat...
Document.writeln() - Web APIs
text followed by a newline character to a document. syntax document.writeln(line); parameters line is string containing a line of text. example document.writeln("<p>enter password:</p>"); notes document.writeln is the same as document.write but adds a newline. note: document.writeln (like document.write) does not work in xhtml documents (you'll get a "operation is not supported" (ns_
error_dom_not_supported_err)
error on the
error console). this is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml mime type. more information is available in the w3c xhtml faq. specifications specification status comment html living standardthe definition of 'document.writeln()' in that specification. ...
DocumentOrShadowRoot.getSelection() - Web APIs
is passed to the function. this can make the object appear to be a string when used with other functions when it is really an object with properties and methods. in the above example, selobj.tostring() is automatically called when it is passed to window.alert(). however, attempting to use a javascript string property or method such as length or substr directly on a selection object results in an
error if it does not have that property or method and may return unexpected results if it does. to use a selection object as a string, call its tostring() method directly: var selectedtext = selobj.tostring(); selobj is a selection object. selectedtext is a string (selected text). related objects you can call window.getselection(), which works identically to document.getselection(). it is wort...
Introduction to the DOM - Web APIs
r create a similar one to test the dom interfaces you are interested in and see how they work on the browser platform. you can update the contents of the test() function as needed, create more buttons, or add elements as necessary. ...
DoubleRange - Web APIs
ed on this, augmenting it to support exact and ideal values as well. properties max a floating-point value specifying the largest permissible value of the property it describes. min a floating-point value specifying the smallest permissible value of the property it describes. the specified min and/or and max values are required. if no match can be found that is within the given range, an
error will occur. specifications specification status comment media capture and streamsthe definition of 'doublerange' in that specification. candidate recommendation initial definition ...
EXT_float_blend - Web APIs
he use of 32-bit floating-point draw buffers by enabling the extension webgl_color_buffer_float (for webgl1) or ext_color_buffer_float (for webgl2). doing so automatically enables ext_float_blend as well. with this extension enabled, calling drawarrays() or drawelements() with blending enabled and a draw buffer with 32-bit floating-point components will no longer result in an invalid_operation
error. usage notes on devices that support the ext_float_blend extension, it is automatically, implicitly, enabled when any one or more of ext_color_buffer_float, oes_texture_float, or webgl_color_buffer_float are enabled. this ensures that content written before ext_float_blend was exposed by webgl will function as expected. examples const gl = canvas.getcontext('webgl2'); // enable necessary ext...
EffectTiming.duration - Web APIs
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 type
error 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(function(el) ...
EffectTiming.iterations - Web APIs
fiterations }; 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 type
error 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([ { transform:...
Element.attachShadow() - Web APIs
atesfocus 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 invalidstate
error the element you are trying to attach to is already a shadow host. notsupported
error 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 (see it live also). you can see that we use attachshadow() in the mi...
Element.closest() - Web APIs
tor 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 syntax
error 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.closest("div div")...
Element.insertAdjacentElement() - Web APIs
ent 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 syntax
error the position specified is not a recognised value. type
error 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 and has an element parent. example beforebtn.addeventliste...
Element.insertAdjacentText() - Web APIs
e 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 syntax
error 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('click', function() { para.insertadjacenttext('afterbegin',tex...
Element.onfullscreenchange - Web APIs
gine to be a function that makes adjustments to the app's user interface to present itself optimally when it's in full-screen mode versus being displayed in a window. ...
Element.outerHTML - Web APIs
nnerhtml 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 syntax
error an attempt was made to set outerhtml using an html string which is not valid. nomodificationallowed
error 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 var d = document...
Element.requestPointerLock() - Web APIs
the element.requestpointerlock() method lets you asynchronously ask for the pointer to be locked on the given element. to track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlock
error events at the document level. syntax instanceofelement.requestpointerlock(); specifications specification status comment pointer lockthe definition of 'requestpointerlock()' in that specification. candidate recommendation ...
Element.setAttribute() - Web APIs
ample 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 invalidcharacter
error 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 demonstrates two things: the fi...
Element.setAttributeNodeNS() - Web APIs
t.getelementbyid("two"); var a = d1.getattributenodens(myns, "special-align"); d2.setattributenodens(a.clonenode(true)); alert(d2.attributes[1].value) // returns: `utterleft' notes if the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is returned. note that if you try to set without cloning the node, mozilla gives an ns_
error_dom_inuse_attribute_err "attribute already in use"
error, as the dom requires cloning for attr to be reused (unlike other nodes which can be moved). dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namespace-aware methods for d...
Element.toggleAttribute() - Web APIs
e 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 invalidcharacter
error 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.queryselector("input"); button.a...
Event.eventPhase - Web APIs
d.onmousemove = function () { clear = true } } } } } function ondivclick(e) { if (clear) { clear() clear = false } if (e.eventphase == 2) e.currenttarget.style.backgroundcolor = 'red'; let level = e.eventphase == 0 ? "none" : e.eventphase == 1 ? "capturing" : e.eventphase == 2 ? "target" : e.eventphase == 3 ? "bubbling" : "
error"; divinfo.innerhtml += e.currenttarget.id + "; eventphase: " + level + "<br/>"; } function clear() { for (let i = 0; i < divs.length; i++) { if (divs[i].id != "divinfo") { divs[i].style.backgroundcolor = (i & 1) ? "#f6eedb" : "#cceeff" } } divinfo.innerhtml = '' } result specifications specification status comment domthe definition of 'event.e...
Event.type - Web APIs
for a list of available event types, see the event reference. syntax let eventtype = event.type; value a domstring containing the type of event. example this example logs the event type whenever you press a keyboard key or click a mouse button. ...
EventTarget.addEventListener() - Web APIs
ose handleevent() method serves as the callback function. the callback function itself has the same parameters and return value as the handleevent() method; that is, the callback accepts a single parameter: an object based on event describing the event that has occurred, and it returns nothing. for example, an event handler callback that can be used to handle both fullscreenchange and fullscreen
error might look like this: function eventhandler(event) { if (event.type == 'fullscreenchange') { /* handle a full screen toggle */ } else /* fullscreen
error */ { /* handle a full screen toggle
error */ } } safely detecting option support in older versions of the dom specification, the third parameter of addeventlistener() was a boolean value indicating whether or not to use capture. ...
FeaturePolicy.getAllowlistForFeature() - Web APIs
the getallowlistforfeature() method of the featurepolicy allows query of the allow list for a specific feature for the current feature policy. syntax const allowlist = featurepolicy.getallowlistforfeature(<feature>) parameter feature name a specific feature name must be specified. return value an allow list for the specified feature.
errors the function will raise a warning if the specified feature policy directive name is not known. however, it will also return empty array, inditating that no origin is allowed to use the feature. example the followin example prints all the origins that are allowed to use camera api by the feature policy. please note that camera api might be restricted by the permissions api, if the user did not grant the corrsponding permission yet. // ...
FetchEvent.respondWith() - Web APIs
cification handles redirects for navigations ends up using 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 network
error 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. invalidstate
error the event has not been dispatched or respondwithwith() has already been invoked. example...
Fetch basic concepts - Web APIs
to none (the default). when a request or response object is created, it has an associated headers object whose guard is set as summarized below: new object's type creating constructor guard setting of associated headers object request request() request request() with mode of no-cors request-no-cors response response() response
error() or redirect() methods immutable a header's guard affects the set(), delete(), and append() methods which change the header's contents. a type
error is thrown if you try to modify a headers object whose guard is immutable. however, the operation will work if guard is request and the header name isn't a forbidden header name . guard is request-no-cors and the header name/value is a s...
Fetch API - Web APIs
sponse directly using the request() and response() constructors, but it's uncommon to do this directly. instead, these are more likely to be created as results of other api actions (for example, fetchevent.respondwith() from service workers). differences from jquery the fetch specification differs from jquery.ajax() in three main ways: the promise returned from fetch() won’t reject on http
error status even if the response is an http 404 or 500. instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites are silently ignored. fetch() won’t send...
FileReader: abort event - Web APIs
t.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('
error', handleevent); reader.addeventlistener('abort', handleevent); } function handleselected(e) { eventlog.textcontent = ''; const selectedfile = fileinput.files[0]; if (selectedfile) { addlisteners(reader); reader.readasdataurl(selectedfile); } reader.abort(); } fileinput.addeventlistener('change', handleselected); result specifications specif...
FileReader: load event - Web APIs
t.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('
error', handleevent); reader.addeventlistener('abort', handleevent); } function handleselected(e) { eventlog.textcontent = ''; const selectedfile = fileinput.files[0]; if (selectedfile) { addlisteners(reader); reader.readasdataurl(selectedfile); } } fileinput.addeventlistener('change', handleselected); result specifications specification status ...
FileReader: loadend event - Web APIs
t.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('
error', handleevent); reader.addeventlistener('abort', handleevent); } function handleselected(e) { eventlog.textcontent = ''; const selectedfile = fileinput.files[0]; if (selectedfile) { addlisteners(reader); reader.readasdataurl(selectedfile); } } fileinput.addeventlistener('change', handleselected); result specifications specification status ...
FileReader: loadstart event - Web APIs
t.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('
error', handleevent); reader.addeventlistener('abort', handleevent); } function handleselected(e) { eventlog.textcontent = ''; const selectedfile = fileinput.files[0]; if (selectedfile) { addlisteners(reader); reader.readasdataurl(selectedfile); } } fileinput.addeventlistener('change', handleselected); result specifications specification status ...
FileReader: progress event - Web APIs
t.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('
error', handleevent); reader.addeventlistener('abort', handleevent); } function handleselected(e) { eventlog.textcontent = ''; const selectedfile = fileinput.files[0]; if (selectedfile) { addlisteners(reader); reader.readasdataurl(selectedfile); } } fileinput.addeventlistener('change', handleselected); result specifications specification status ...
FileReader.readyState - Web APIs
states: value state description 0 empty reader has been created. none of the read methods called yet. 1 loading a read method has been called. 2 done the operation is complete. empty the filereader has been created, but no readas method was called yet. loading a readas method was invoked. a file or blob is being read, and no
error has occurred yet. done the read operation is complete. this could mean that: the entire file or blob has been read into memory, a file read
error occurred, or abort() was called and the read was cancelled. example var reader = new filereader(); console.log('empty', reader.readystate); // readystate will be 0 reader.readastext(blob); console.log('loading', reader.readystate); // readystate w...
FileSystemDirectoryEntry.createReader() - Web APIs
es all of the entries in the specified filesystemdirectoryentry and returns them in an array. function readdirectory(directory) { let dirreader = directory.createreader(); let entries = []; let getentries = function() { dirreader.readentries(function(results) { if (results.length) { entries = entries.concat(toarray(results)); getentries(); } }, function(
error) { /* handle
error --
error is a file
error object */ }); }; getentries(); return entries; } this works by creating an internal function, getentries(), which calls itself recursively to get all the entries in the directory, concatenating each batch to the array. each iteration, readentries() is called to get more entries. when it returns an empty array, the end of the directory h...
FileSystemEntry.fullPath - Web APIs
mentry.fullpath; value a usvstring indicating the entry's full path. example this example shows a function which is called with a file system; it then gets a filesystemfileentry for a file named data.json and returns its full path. function gotfilesystem(fs) { let path = ""; fs.root.getfile("data.json", { create: true, exclusive: true }, function(entry) { path = fullpath; }, handle
error(
error)); return path; } obviously, this is somewhat contrived, since we know that the file's full path is "/data.json", having just looked it up ourselves, but the concept holds up for scenarios in which you don't know it. specifications specification status comment file and directory entries apithe definition of 'fullpath' in that specification. draft ini...
FileSystemEntry.isDirectory - Web APIs
use both isdirectory and isfile as needed to ensure that the entry is something you know how to work with. syntax var isdirectory = filesystementry.isdirectory; value a boolean indicating whether or not the filesystementry is a directory. example this example shows how this property might be used to determine whether to process the entry as a directory or file. if the entry is neither, an
error handler is called with an appropriate message. if (entry.isdirectory) { processsubdirectory(entry); } else if (entry.isfile) { processfile(entry); } else { display
errormessage("unsupported file system entry specified."); } specifications specification status comment file and directory entries apithe definition of 'isdirectory' in that specification. draft ...
FileSystemEntry.isFile - Web APIs
ems. be sure to use both isdirectory and isfile as needed to ensure that the entry is something you know how to work with. syntax var isfile = filesystementry.isfile; value a boolean indicating whether or not the filesystementry is a file. example this example shows how this property might be used to determine whether to process the entry as a directory or file. if the entry is neither, an
error handler is called with an appropriate message. if (entry.isdirectory) { processsubdirectory(entry); } else if (entry.isfile) { processfile(entry); } else { display
errormessage("unsupported file system entry specified."); } specifications specification status comment file and directory entries apithe definition of 'isfile' in that specification. draft in...
FileSystemEntry - Web APIs
e. // taking care of the browser-specific prefixes. window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; ... // opening a file system with temporary storage window.requestfilesystem(temporary, 1024*1024 /*1mb*/, function(fs) { fs.root.getfile('log.txt', {}, function(fileentry) { fileentry.remove(function() { console.log('file removed.'); }, on
error); }, on
error); }, on
error); properties this interface provides the following properties. filesystem read only a filesystem object representing the file system in which the entry is located. fullpath read only a usvstring object which provides the full, absolute path from the file system's root to the entry; it can also be thought of as a path which is relative to the root directory,...
File and Directory Entries API support in Firefox - Web APIs
isn't implemented. only the asynchronous versions of the interfaces are implemented. any interfaces with names that end in "sync" aren't available. firefox only supports reading from files in the file system. you can't write to them. in particular, the filesystemfileentry.createwriter() method, used to create a filewriter to handle writing to a file, is not implemented and will just treturn an
error. firefox doesn't support the "filesystem:" url scheme. ...
FontFace.load - Web APIs
d of the fontface interface loads a font 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 network
error if the loading process fails. exceptions network
error 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. ...
FontFace.loaded - Web APIs
the loaded read-only property of the fontface interface returns a promise that resolves with the current fontface object when the font specified in the object's constructor is done loading or rejects with a syntax
error. syntax var apromise = fontface.loaded; value a promise that resolves with the current fontface object. specifications specification status comment css font loading module level 3the definition of 'loaded' in that specification. working draft initial definition. ...
FontFace.status - Web APIs
the status read-only property of the fontface interface returns an enumerated value indicating the status of the font, one of "unloaded", "loading", "loaded", or "
error". syntax var status = fontface.status; value one of "unloaded", "loading", "loaded", or "
error". specifications specification status comment css font loading module level 3the definition of 'status' in that specification. working draft initial definition. ...
FontFace - Web APIs
r. fontface.featuresettings a cssomstring that retrieves or sets infrequently used font features that are not available from a font's variant properties. it is equivalent to the font-feature-settings descriptor. fontface.loaded read only returns a promise that resolves with the current fontface object when the font specified in the object's constructor is done loading or rejects with a syntax
error. fontface.status read only returns an enumerated value indicating the status of the font, one of "unloaded", "loading", "loaded", or "
error". fontface.stretch a cssomstring that retrieves or sets how the font stretches. it is equivalent to the font-stretch descriptor. fontface.style a cssomstring that retrieves or sets the style of the font. it is equivalent to the font-style descriptor. ...
FontFaceSet - Web APIs
e which resolves once font loading and layout operations have completed. events fontfaceset.onloading an eventlistener called whenever an event of type loading is fired, indicating a font-face set has started loading. fontfaceset.onloadingdone an eventlistener called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. fontfaceset.onloading
error an eventlistener called whenever an event of type loading
error is fired, indicating that an
error occurred whilst loading a font-face set. methods fontfaceset.add() adds a font to the font set. fontfaceset.check() a boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. fontfaceset.clear() removes all manually-added fonts from the font set. css-conn...
FullscreenOptions.navigationUI - Web APIs
ill choose which of the above settings to apply. this is the default value. example in this example, the entire document is placed into full-screen mode by calling requestfullscreen() on the document's document.documentelement, which is the document's root <html> element. let elem = document.documentelement; elem.requestfullscreen({ navigationui: "show" }).then({}).catch(err => { alert(`an
error occurred while trying to switch into full-screen mode: ${err.message} (${err.name})`); }); the promise's resolve handler does nothing, but if the promise is rejected, an
error message is displayed by calling alert(). specifications specification status comment fullscreen apithe definition of 'fullscreenoptions' in that specification. living standard initial d...
HTMLButtonElement - Web APIs
ement.value is a domstring representing the current form control value of the button. methods inherits methods from its parent, htmlelement name return type description checkvalidity() boolean not supported for reset or button elements. reportvalidity() boolean not supported for reset or button elements. setcustomvalidity(in domstring
error) void not supported for reset or button elements. with gecko-based browser, use the :-moz-submit-invalid pseudo-class to style submit buttons based on the validation of a form. specifications specification status comment html living standardthe definition of 'htmlbuttonelement' in that specification. living standard html 5.2the definition...
HTMLCanvasElement.captureStream() - Web APIs
icates 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 notsupported
error 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); specifications ...
HTMLCanvasElement.toBlob() - Web APIs
nal 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 security
error 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, then appends a ne...
HTMLCanvasElement.toDataURL() - Web APIs
mage/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 security
error 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'); var dataurl = can...
HTMLCanvasElement - Web APIs
l to an offscreencanvas object, either on the main thread or on a worker. obsolete methods htmlcanvaselement.mozgetasfile() returns a file object representing the image contained in the canvas; this file is a memory-based file, with the specified name. if type is not specified, the image type is image/png. events listen to these events using addeventlistener(). webglcontextcreation
error fired if the user agent is unable to create a webglrenderingcontext or webgl2renderingcontext context. webglcontextlost fired if the user agent detects that the drawing buffer associated with a webglrenderingcontext or webgl2renderingcontext object has been lost. webglcontextrestored fired if the user agent restores the drawing buffer for a webglrenderingcontext or webgl2renderingcontext obj...
HTMLContentElement.select - Web APIs
the htmlcontentelement.select property reflects the select attribute. it is a domstring containing a space-separated list of css selectors that select the content to insert in place of the <content> element. syntax object.select = "cssselector cssselector ..."; example // select <h1> elements and elements with class="
error" mycontentobject.select = "h1 .
error"; specifications this feature is no longer defined by any standards. ...
HTMLDialogElement.showModal() - Web APIs
ther 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 invalidstate
error 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 button. <!-- simple pop-up dialog box, containing a form --> <dialog id="favdialog"> <form method="d...
HTMLFieldSetElement - Web APIs
ue because <fieldset> objects are never candidates for constraint validation. htmlfieldsetelement.reportvalidity() always returns true because <fieldset> objects are never candidates for constraint validation. htmlfieldsetelement.setcustomvalidity() sets a custom validity message for the field set. if this message is not the empty string, then the field set is suffering from a custom validity
error, and does not validate. specifications specification status comment html living standardthe definition of 'htmlfieldsetelement' in that specification. living standard html 5.1the definition of 'htmlfieldsetelement' in that specification. recommendation html5the definition of 'htmlfieldsetelement' in that specification. recommendati...
HTMLFormElement.requestSubmit() - Web APIs
ton. 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 type
error the specified submitter is not a submit button. notfound
error 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 dawn of time? th...
HTMLFormElement - Web APIs
its the form to the server. deprecated methods htmlformelement.requestautocomplete() triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. the form will receive an event once the user has finished with the interface, the event will either be autocomplete when the fields have been filled or autocomplete
error when there was a problem. events listen to these events using addeventlistener(), or by assigning an event listener to the oneventname property of this interface. formdata the formdata event fires after the entry list representing the form's data is constructed. also available via the onformdata property. reset the reset event fires when a form is reset. also available via the onreset ...
HTMLImageElement.alt - Web APIs
perhaps the most important reason to use the alt tag is to support accessibility, as the alt text may be used by screen readers and other assistive technologies to help differently-abled users make full use of your content. it will be read aloud or sent to the touch device, for example, to support visually impaired users. ...
HTMLImageElement.crossOrigin - Web APIs
in property on an <img> element to configure cors access for the fetch of a newly-created image. const imageurl = "https://mdn.mozillademos.org/files/16797/clock-demo-400px.png"; const container = document.queryselector(".container"); function loadimage(url) { const image = new image(200, 200); image.addeventlistener("load", () => container.prepend(image) ); image.addeventlistener("
error", () => { const errmsg = document.createelement("output"); errmsg.value = `
error loading image at ${url}`; container.append(errmsg); }); image.crossorigin = "anonymous"; image.alt = ""; image.src = url; } loadimage(imageurl); html <div class="container"> <p>here's a paragraph. it's a very interesting paragraph. you are captivated by this paragraph. keep reading this pa...
HTMLImageElement - Web APIs
pty space, in pixels, to leave above and below the image. methods inherits properties from its parent, htmlelement. htmlimageelement.decode() returns a promise that resolves when the image is decoded and it's safe to append the image to the dom. this prevents rendering of the next frame from having to pause to decode the image, as would happen if an undecoded image were added to the dom.
errors if an
error occurs while trying to load or render the image, and an on
error event handler has been configured to handle the
error event, that event handler will get called. this can happen in a number of situations, including: the src attribute is empty or null. the specified src url is the same as the url of the page the user is currently on. the specified image is corrupted in some way t...
HTMLInputElement: invalid event - Web APIs
bmission. when a form is submitted, invalid events are fired at each form control that is invalid. the validity of submittable elements is checked before submitting their owner <form>, or after the checkvalidity() method of the element or its owner <form> is called. it is not checked on blur. examples if a form is submitted with an invalid value, the submittable elements are checked and, if an
error is found, the invalid event will fire on the invalid element. in this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged. html <form action="#"> <ul> <li><label>enter an integer between 1 and 10: <input type="number" min="1" max="10" required></label></li> <li><input type="submit" value="submit"></li> </ul> </form><p id="log"><...
HTMLInputElement.mozGetFileNameArray() - Web APIs
the htmlinputelement.mozgetfilenamearray() method returns an array of the names of the files that were selected by the user on an html input element. note: this method is gecko-specific and is not available in other browsers. also, it throws an
error if used in web pages. syntax inputelement.mozgetfilenamearray(alength, afilenames); parameters alength if specified, will receive the number of file names in the returned array. afilenames is an array into which the file names are placed. example var numfiles = 0; var filearray = {}; inputelement.mozgetfilenamearray(numfiles, filearray); ...
HTMLInputElement.mozSetFileNameArray() - Web APIs
the htmlinputelement.mozsetfilenamearray() method sets the names of the files that selected on an html input element. note: this method is gecko-specific and is not available in other browsers. also, it throws an
error if used in web pages. syntax inputelement.mozsetfilenamearray(afilenames, alength); parameters afilenames is the array of file names to apply to the element. alength is the number of file names in the array. example var filearray = {"/foo/bar.txt", "/foo/foosball.txt"}; inputelement.mozsetfilenamearray(filearray, filearray.length); ...
HTMLInputElement.stepDown() - Web APIs
or example, 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 invalidstate
error 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. syn...
HTMLInputElement.stepUp() - Web APIs
for example, 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 invalidstate
error 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="nu...
HTMLInputElement - Web APIs
quently replace all of its content. setselectionrange() selects a range of text in the input element (but does not focus it). setrangetext() replaces a range of text in the input element with new text. setcustomvalidity() sets a custom validity message for the element. if this message is not the empty string, then the element is suffering from a custom validity
error, and does not validate. checkvalidity() returns a boolean that is false if the element is a candidate for constraint validation, and it does not satisfy its constraints. in this case, it also fires an invalid event at the element. it returns true if the element is not a candidate for constraint validation, or if it satisfies its constraints. reportvalidity() runs the check...
HTMLKeygenElement - Web APIs
he validity states that this element is in. willvalidate is a boolean that is always false because keygen objects are never candidates for constraint validation. methods name & arguments return description checkvalidity() boolean always returns true because keygen objects are never candidates for constraint validation. setcustomvalidity(in domstring
error) void sets a custom validity message for the element. if this message is not the empty string, then the element is suffering from a custom validity
error, and does not validate. ...
HTMLMediaElement: abort event - Web APIs
the abort event is fired when the resource was not fully loaded, but not as the result of an
error. bubbles no cancelable no interface event event handler property onabort examples const video = document.queryselector('video'); const videosrc = 'https://path/to/video.webm'; video.addeventlistener('abort', () => { console.log(`abort loading: ${videosrc}`); }); const source = document.createelement('source'); source.setattribute('src', videosrc); source.setattribute('type', 'video/webm'); video.appendchild(source); specifications specification status html living standard living standard html5 recommendation ...
HTMLMediaElement.load() - Web APIs
d its src 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 "abort
error" domexception. 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 pl...
HTMLMediaElement.srcObject - Web APIs
urce is assigned to a newly-created <video> element, with fallback for older browsers and browsers that don't yet support assignment of mediasource directly. const mediasource = new mediasource(); const video = document.createelement('video'); // older browsers may not have srcobject if ('srcobject' in video) { try { video.srcobject = mediasource; } catch (err) { if (err.name != "type
error") { throw err; } // even if they do, they may only support mediastream video.src = url.createobjecturl(mediasource); } } else { video.src = url.createobjecturl(mediasource); } specifications specification status comment html living standardthe definition of 'srcobject' in that specification. living standard initial definition. ...
HTMLObjectElement - Web APIs
ent objects. methods inherits methods from its parent, htmlelement. htmlobjectelement.checkvalidity() retuns a boolean that always is true, because object objects are never candidates for constraint validation. htmlobjectelement.setcustomvalidity() sets a custom validity message for the element. if this message is not the empty string, then the element is suffering from a custom validity
error, and does not validate. specifications specification status comment html living standardthe definition of 'htmlobjectelement' in that specification. living standard html5the definition of 'htmlobjectelement' in that specification. recommendation the w3c specification is a latest of a previous version of html living standard technically, the pr...
HTMLOutputElement - Web APIs
lems, it returns true. when the problem is reported, the user agent may focus the element and change the scrolling position of the document or perform some other action that brings the element to the user's attention. user agents may report more than one constraint violation if this element suffers from multiple problems at once. if the element is not rendered, then the user agent may report the
error for the running script instead of notifying the user. htmloutputelement.setcustomvalidity() sets a custom validity message for the element. if this message is not the empty string, then the element is suffering from a custom validity
error, and does not validate. modes this element behaves in one of two modes: default mode and value mode. default mode initially, the element is in default m...
HTMLSelectElement - Web APIs
th the constraints on the element, if any, to the user. if there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true. htmlselectelement.setcustomvalidity() sets the custom validity message for the selection element to the specified message. use the empty string to indicate that the element does not have a custom validity
error. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: input event fires when the value of an <input>, <select>, or <textarea> element has been changed. example get information about the selected option /* assuming we have the following html <select id='s'> <option>first</option> <option selected>...
HTMLTableElement.deleteRow() - Web APIs
the htmltableelement.deleterow() method removes a specific row (<tr>) from a given <table>. syntax htmltableelement.deleterow(index) parameters index index is an integer 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>c...
HTMLTableElement.insertRow() - Web APIs
case if 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 indexsize
error 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 ...
HTMLTableRowElement.insertCell() - Web APIs
ertcell() 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 indexsize
error 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 u...
HTMLTableRowElement - Web APIs
te 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 domexception with the indexsize
error 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 domexception with the indexsize
error value. returns a reference to a htmltablecel...
HTMLTableSectionElement - Web APIs
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. if the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than 0, it raises a domexception with the indexsize
error value. htmltablesectionelement.insertrow() inserts a new row just before the given position in the section. if the given position is not given or is -1, it appends the row to the end of section. if the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than -1, it raises a domexception with the indexsize
error value. specifications ...
HTMLTextAreaElement - Web APIs
orts the problems with the constraints on the element, if any, to the user. if there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true. setcustomvalidity(domstring) sets a custom validity message for the element. if this message is not the empty string, then the element is suffering from a custom validity
error, and does not validate. the two methods blur() and focus() are inherited from htmlelement from html5 on, but were defined on htmltextareaelement in dom level 2 html and earlier specifications. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: input event fires when the value of an <input>, <select>,...
HTMLTrackElement - Web APIs
icate that another track would be more appropriate. htmltrackelement.readystate read only returns an unsigned short that show the readiness state of the track: constant value description none 0 indicates that the text track's cues have not been obtained. loading 1 indicates that the text track is loading and there have been no fatal
errors encountered so far. further cues might still be added to the track by the parser. loaded 2 indicates that the text track has been loaded with no fatal
errors.
error 3 indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way. some or all of the cues are likely missing and will not be obtained. ...
Dragging and Dropping Multiple Items - Web APIs
ozitemcount; output("items: " + count + "\n"); for (var i = 0; i < count; i++) { output(" item " + i + ":\n"); var types = dt.moztypesat(i); for (var t = 0; t < types.length; t++) { output(" " + types[t] + ": "); try { var data = dt.mozgetdataat(types[t], i); output("(" + (typeof data) + ") : <" + data + " >\n"); } catch (ex) { output("<<
error>>\n"); dump(ex); } } } } function output(text) { document.getelementbyid("output").textcontent += text; dump(text); } </script> </head> <body> <div id="output" style="min-height: 100px; white-space: pre; border: 1px solid black;" ondragenter="document.getelementbyid('output').textcontent = ''; event.stoppropagation(); event.preventdefault();" ondragover="event...
Recommended Drag Types - Web APIs
// currentevent is an existing drag operation event currentevent.datatransfer.setdata("text/x-moz-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-dest-filename", leafname); currentevent.datatransfer.mozsetdataat('application/x-moz-file-promise', new dataprovider(success,
error), 0, components.interfaces.nsisupports); function dataprovider(){} dataprovider.prototype = { queryinterface : function(iid) { if (iid.equals(components.interfaces.nsiflavordataprovider) || iid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; }, getflavordata : function(atransferable, aflavor...
Headers.delete() - Web APIs
the value of guard is immutable. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.delete(name); parameters name the name of the http header you want to delete from the headers object. returns void. ...
Headers.get() - Web APIs
t, it returns null. 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. syntax myheaders.get(name); parameters name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a type
error. the name is case-insensitive. returns a bytestring sequence representing the values of the retrieved header or null if this header is not set. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty myheaders.get('not-set'); // returns null you could add a header to this using headers.append, then retrieve it using get(): myheaders.append('c...
Headers.getAll() - Web APIs
an empty array. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.getall(name); parameters name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a type
error. returns an array containing a bytestring sequence representing the values of the retrieved header. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then retrieve it using getall(): myheaders.append('content-type', 'image/jpeg'); myheaders.getall('content-type'); // returns [ "image/j...
Headers.has() - Web APIs
tating whether a headers object contains a certain header. 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. syntax myheaders.has(name); parameters name the name of the http header you want to test for. if the given name is not a valid http header name, this method throws a type
error. returns a boolean. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then test for the existence of it using has(): myheaders.append('content-type', 'image/jpeg'); myheaders.has('content-type'); // returns true myheaders.has('accept-encoding'); // returns false specifications ...
Headers.set() - Web APIs
value to the end of the set of values. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.set(name, value); parameters name the name of the http header you want to set to a new value. if the given name is not the name of an http header, this method throws a type
error. value the new value you want to set. returns void. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then set a new value for this header using set(): myheaders.append('content-type', 'image/jpeg'); myheaders.set('content-type', 'text/html'); if the specified header does not alrea...
Headers - Web APIs
e clear, the difference between headers.set() and headers.append() is that if the specified header does already exist and does accept multiple values, headers.set() will overwrite the existing value with the new one, whereas headers.append() will append the new value onto the end of the set of values. see their dedicated pages for example code. note: all of the headers methods will throw a type
error if you try to pass in a reference to a name that isn't a valid http header name. the mutation operations will throw a type
error if the header has an immutable guard. in any other failure case they fail silently. note: when header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined. obsolete methods headers.g...
IDBCursor.advance() - Web APIs
thod 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 domexception of one of the following types: exception description transactioninactive
error this idbcursor's transaction is inactive. type
error the value passed into the count parameter was zero or a negative number. invalidstate
error 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 in the object ...
IDBCursor.delete() - Web APIs
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 domexception of one of the following types: exception description transactioninactive
error this idbcursor's transaction is inactive. readonly
error the transaction mode is read-only. invalidstate
error the cursor was created using idbindex.openkeycursor, 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 all the records in the ...
IDBDatabase.close() - Web APIs
connection once this method is called. methods that create transactions throw an exception if a closing operation is pending. note: this feature is available in web workers. syntax idbdatabase.close(); example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // opening a database. // create event handlers for both success and failure of dbopenrequest.on
error = function(event) { note.innerhtml += "<li>
error loading database.</li>"; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += "<li>database initialised.</li>"; // store the result of opening the database in the db variable. db = dbopenrequest.result; // now let"s close the database again! db.close(); }; specification specification status comment ...
IDBDatabase: close event - Web APIs
atabase connection is unexpectedly closed. this could happen, for example, if the underlying storage is removed or if the user clears the database in the browser's history preferences. note that it is not fired if the database connection is closed normally using idbdatabase.close(). ...
IDBDatabase.name - Web APIs
atabase connection being opened, the resulting idbdatabase object being stored in a db variable, and the name property then being logged. for a full example, see our to-do notifications app (view example live). // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being // opened successfully, or not dbopenrequest.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. this is used a lot below db = dbopenrequest.result; // this line will log the name of the database, which should be "todolist" console.log(db.name)...
IDBDatabase.objectStoreNames - Web APIs
s feature is available in web workers. syntax var list[] = idbdatabase.objectstorenames; value a domstringlist containing a list of the names of the object stores currently in the connected database. example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not dbopenrequest.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. this is used a lot below db = dbopenrequest.result; // this line will log the version of the connected database, which should be // an object that ...
IDBDatabase.version - Web APIs
, this attribute is an empty string. note: this feature is available in web workers. syntax var myinteger = idbdatabase.version; value an integer containing the version of the connected database. example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database // being opened successfully, or not dbopenrequest.on
error = function(event) { note.innerhtml += '<li>
error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. this is used a lot below db = dbopenrequest.result; // this line will log the version of the connected database, which should be "4" console.log(db...
IDBFactory.cmp() - Web APIs
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 definition of 'cmp()' in that specification. recommendation indexed database api draftthe definition of '...
databases - Web APIs
eturns a list represening all the available databases, including their names and versions. note: this feature is available in web workers. 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 domexception of the following types: attribute description security
error the method is called from an opaque origin. other
error specification does not describe all possible
errors. exa...
IDBFactorySync - Web APIs
aseexception); 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 idbdatabaseexception 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. ...
IDBIndex.count() - Web APIs
equest = 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 domexception of one of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. data
error the key or key range provided contains an invalid key. invalidstate
error the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex...
IDBIndex.get() - Web APIs
ptional 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 domexception of one of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. data
error the key or key range provided contains an invalid key. invalidstate
error the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex...
IDBIndex.getKey() - Web APIs
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 domexception of one of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. data
error the key or key range provided contains an invalid key. invalidstate
error the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex...
IDBIndex.name - Web APIs
the name property of the idbindex interface contains a string which names the index. note: this feature is available in web workers. syntax var indexname = idbindex.name; idbindex.name = indexname; value a domstring specifying a name for the index. exceptions there are a several exceptions which can occur when you attempt to change an index's name. invalidstate
error the index, or its 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". transactioninactive
error the current transaction is not active. constraint
error an index is already using the specified name. example in the following example we open a transaction and an object store, then ...
IDBIndex.openCursor() - Web APIs
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 domexception of one of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. type
error the value for the direction parameter is invalid. data
error the key or key range provided contains an invalid key. invalidstate
error the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple co...
IDBIndex.openKeyCursor() - Web APIs
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 domexception of one of the following types: exception description transactioninactive
error this idbindex's transaction is inactive. type
error the value for the direction parameter is invalid. data
error the key or key range provided contains an invalid key. invalidstate
error the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple ...
IDBKeyRange.bound() - Web APIs
e. 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 domexception of the following type: exception description data
error 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 following example illustrates how you'd use a bound key range. here we declare a keyrangevalue = idbkeyrange.bound("a", "f"...
IDBKeyRange.includes() - Web APIs
ean 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 domexception of the following type: attribute description data
error the supplied key was not a valid key. example var keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns false polyfill the includes() method was added in the second edition of the indexed db specification. for browsers that do not support it, the following polyfi...
IDBKeyRange.lowerBound() - Web APIs
ge = 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 domexception of the following type: exception description data
error 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 after it. we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencur...
IDBKeyRange.only() - Web APIs
erface 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 domexception of the following types: exception description data
error 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.opencursor, declaring keyrangevalue as its...
IDBKeyRange.upperBound() - Web APIs
e = 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 domexception of the following type: exception description data
error 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 open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declar...
IDBMutableFile - Web APIs
cts are bound to a fake file system built on top of indexeddb, such an object is created using the idbdatabase.createmutablefile method. properties mutablefile.name read only the name of the handled file. mutablefile.type read only the mime type of the handled file. events handler mutablefile.onabort the abort event is triggered each time the handled file is aborted. mutablefile.on
error the
error event is triggered each time something goes wrong. methods mutablefile.open() returns a lockedfile object to read or write the associated file safely. mutablefile.getfile() returns a domrequest object. in case of success, the request's result is a file object representing a snapshot of the handled file. specifications not part of any specification at present. see also lo...
IDBObjectStore.count() - Web APIs
t(); 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 domexception of one of the following types: exception description invalidstate
error this idbobjectstore has been deleted. transactioninactive
error this idbobjectstore's transaction is inactive. data
error the specified key or key range is invalid. example in this simple fragment we create a transaction, retrieve an object store, then count the number of records in the store using count() — when the success handler fires, we log the count value...
IDBObjectStore.getKey() - Web APIs
e 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 domexception of one of the following types: exception description transactioninactive
error this idbobjectstore's transaction is inactive. data
error the key or key range provided contains an invalid key. invalidstate
error the idbobjectstore has been deleted or removed. example let openrequest = indexeddb.open("telemetry"); openrequest.onsuccess = (event) => { let db = event.target.result; let store = db.transaction("netlogs").objects...
IDBObjectStore.index() - Web APIs
s 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 domexception of one of the following types: exception description invalidstate
error the source object store has been deleted, or the transaction for the object store has finished. notfound
error there is no index with the given name (case-sensitive) in the database. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbinde...
IDBObjectStore.openCursor() - Web APIs
l 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 domexception of one of the following types: exception description invalidstate
error this idbobjectstore or idbindex has been deleted. transactioninactive
error this idbobjectstore's transaction is inactive. data
error the specified key or key range is invalid. 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: var transaction = db.tran...
IDBObjectStore.openKeyCursor() - Web APIs
l 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 domexception of one of the following types: exception description invalidstate
error this idbobjectstore or idbindex has been deleted. transactioninactive
error this idbobjectstore's transaction is inactive. data
error the specified key or key range is invalid. 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: var transaction = db.tran...
IDBRequest.readyState - Web APIs
note: this feature is available in web workers. syntax var currentreadystate = request.readystate; value the idbrequestreadystate of the request, which takes one of the following two values: value meaning pending the request is pending. done the request is done. ...
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.onabort - Web APIs
day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error: ' + transaction.
error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report t...
IDBTransaction.oncomplete - Web APIs
day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.on
error = function(event) { note.innerhtml += '<li>transaction not opened due to
error: ' + transaction.
error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report t...
IIRFilterNode.getFrequencyResponse() - Web APIs
quencies, 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 notsupported
error 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 need, one containing th...
ImageCapture() constructor - Web APIs
the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor. navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(
error => console.log(
error)); specifications specification status comment mediastream image capturethe definition of 'imagecapture' in that specification. working draft initial definition. ...
ImageCapture.takePhoto() - Web APIs
to instantiate the imagecapture object. var takephotobutton = document.queryselector('button#takephoto'); var canvas = document.queryselector('canvas'); takephotobutton.onclick = takephoto; function takephoto() { imagecapture.takephoto().then(function(blob) { console.log('took photo:', blob); img.classlist.remove('hidden'); img.src = url.createobjecturl(blob); }).catch(function(
error) { console.log('takephoto()
error: ',
error); }); } specifications specification status comment mediastream image capturethe definition of 'takephoto()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please...
ImageData() - Web APIs
such array is given, an image with a transparent black rectangle of the specified width and height will be created. width an unsigned long representing the width of the image. height an unsigned long representing the height of the image. this value is optional if an array is given: the height will be inferred from the array's size and the given width. return value a new imagedata object.
errors thrown indexsize
error thrown if array is specified, but its length is not a multiple of (4 * width) or (4 * width * height). examples creating a blank imagedata object this example creates an imagedata object that is 200 pixels wide and 100 pixels tall, containing a total of 20,000 pixels. let imagedata = new imagedata(200, 100); // imagedata { width: 200, height: 100, data: uint8clampe...
InstallEvent - Web APIs
l event. resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { return cache.addall(urlstoprefetch.map(function(urltoprefetch) { return new request(urltoprefetch, {mode: 'no-cors'}); })).then(function() { console.log('all resources have been fetched and cached.'); }); }).catch(function(
error) { console.
error('pre-fetching failed:',
error); }) ); }); specifications specification status comment service workers working draft as of may 2015, the install event is an instance of extendableevent rather than a child of it. ...
IntersectionObserver.IntersectionObserver() - Web APIs
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 syntax
error the specified rootmargin is invalid. range
error 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, {threshol...
KeyframeEffect.setKeyframes() - Web APIs
ing 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 type
error 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 keyframe objects existingkeyframeeffect.setkeyframes( [ { ...
LargestContentfulPaint - Web APIs
shows how to create a performanceobserver that listens for largest-contentful-paint entries and logs the lcp value to the console. this example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to true. note that in this example data is only sent to the server when the user leaves the tab. // catch
errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new performanceobserver((entrylist) => { const entries = entrylist.getentries(); const lastentry = entries[entries.length - 1]; // update `lcp` to the latest value, using `rendertime` if it's available, // otherwise using `loadtime`. (note:...
LayoutShift - Web APIs
er input. layoutshift.sources returns an array of layoutshiftattribution objects with information on the elements that were shifted. methods layoutshift.tojson() converts the properties to json. examples the following example shows how to capture layout shifts and log them to the console. note that in this example data is only sent to the server when the user leaves the tab. // catch
errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativelayoutshiftscore = 0; const observer = new performanceobserver((list) => { for (const entry of list.getentries()) { // only count layout shifts without recent user input. if (!entry.hadrecentinput) { cumulativelayoutshiftscore += entry.value; ...
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 domexception 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 domexception 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...
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. living standard no change from html5. ...
Location: replace() - Web APIs
eplace() 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 domexception 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 domexception of the syntax_
error type is thrown. syntax object.replace(url); parameters url is a domstring containing the url of the pag...
LockManager.request() - Web APIs
until this returns. }); signal example to only wait for a lock for a short period of time, use the signal option. const controller = new abortcontroller(); // wait at most 200ms. settimeout(() => controller.abort(), 200); try { await navigator.locks.request('my_resource', {signal: controller.signal}, async lock => { // the lock was acquired! }); } catch (ex) { if (ex.name === 'abort
error') { // the request aborted before it could be granted. } } specifications specification status comment web locks apithe definition of 'request()' in that specification. draft initial definition. ...
LockedFile.active - Web APIs
be large incompatibilities between implementations and the behavior may change in the future. the active property allows to know if the lockedfile object is still usable (true) or not (false). if the object is inactive then it is impossible to perform any read or write operation with it. typically, a lockedfile object becomes inactive when the lockedfile.abort() method is called or if an
error occurs. syntax var state = instanceoflockedfile.active value a boolean. specifications specification status comment filesystem api editor's draft draft proposal. ...
LockedFile - Web APIs
ctive read only a flag indicating if the file can be accessed (true) or not (false). lockedfile.location the position of the reading/writing pointer within the file. events handler lockedfile.oncomplete the complete event is triggered each time a read or write operation is successful. lockedfile.onabort the abort event is triggered each time the abort() method is called. lockedfile.on
error the
error event is triggered each time something goes wrong. methods lockedfile.getmetadata() allows to retrieve the file metadata (size and date of the last modification). returns a filerequest. lockedfile.readasarraybuffer() allows to retrieve a part of the content of the file as an arraybuffer. returns a filerequest object. lockedfile.readastext() allows to retrieve a part of the co...
MediaCapabilities.encodingInfo() - Web APIs
encodingconfiguration 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 type
error 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 mediaconfig = ...
MediaConfiguration - Web APIs
ia-source. if the media is an audio file, the audio configuration must include a valid audio mime type as contenttype, the number of channels, the bitrate, and the sample rate. video configurations mush include a valid video mime type as contenttype, the bitrate, and framerate, along with the width and the height of the video file. all of these must be present, as in the examples below, or a type
error will occur. a valid media decoding configuration, to be submitted as the parameter for mediacapabilities.decodinginfo() method, has it's `type` set as: file: for plain playback file. media-source: for media source files. a valid media encoding configuration, to be submitted as the parameter for mediacapabilities.encodinginfo() method, has it's `type` set as: record: for r...
MediaRecorder() - Web APIs
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 notsupported
error 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 an mp4 file). ... if...
MediaRecorder.mimeType - Web APIs
ar chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var options = { audiobitspersecond: 128000, videobitspersecond: 2500000, mimetype: 'video/mp4' } var mediarecorder = new mediarecorder(stream,options); m = mediarecorder; m.mimetype; // would return 'video/mp4' ... }) .catch(function(
error) { console.log(
error.message); }); changing line 14 to the following causes mediarecorder to try to use avc constrained baseline profile level 4 for video and aac-lc (low complexity) for audio, which is good for mobile and other possible resource-constrained situations. mimetype: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' assuming this configuration is acceptable to the user agent...
MediaRecorder.onwarning - Web APIs
the mediarecorder.onwarning event handler (part of the mediarecorder api) handles the recordingwarning event, allowing you to run code in response to non-fatal
errors being thrown during media recording via a mediarecorder, which don't halt recording. syntax mediarecorder.onwarning = function(event) { ... } mediarecorder.addeventlistener('warning', function(event) { ... }) example ... mediarecorder.onwarning = function(e) { console.log("a warning has been raised: " + e.message); } ... properties message contains information about the
error that occurred. ...
MediaRecorder.pause() - Web APIs
the media.pause() method (part of the mediarecorder api) is used to pause recording of media streams. when a mediarecorder object’s pause()method is called, the browser queues a task that runs the below steps: if mediarecorder.state is "inactive", raise a dom invalidstate
error and terminate these steps. if 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 invalidstate
error 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 = functi...
MediaRecorder.stop() - Web APIs
the mediarecorder.stop() method (part of the mediarecorder api) is used to stop media capture. when the stop() method is invoked, the ua queues a task that runs the following steps: if mediarecorder.state is "inactive", raise a dom invalidstate
error and terminate these steps. if the mediarecorder.state is not "inactive", continue on to the next step. set the mediarecorder.state to "inactive" and stop capturing media. raise a dataavailable event containing the blob of data that has been gathered. raise a stop event. syntax mediarecorder.stop()
errors an invalidstate
error is raised if the stop() method is called while the mediarecorder object’s mediarecorder.state is "inactive" — it makes no sense to stop media capture if it is already stopped. example ... stop.onclick = ...
MediaSession.setPositionState() - Web APIs
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 type
error 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 callback which ...
MediaSource.duration - Web APIs
operty 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 invalidaccess
error an attempt was made to set a duration value that was negative, or nan. invalidstate
error 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 desaulniers (view the fu...
MediaSource.isTypeSupported() - Web APIs
ng codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.
error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystat...
MediaSource.readyState - Web APIs
example written by nick desaulniers (view the full demo live, or download the source for further investigation.) if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.
error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystat...
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 notfound
error 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. recomm...
MediaSource - Web APIs
codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.
error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystat...
MediaStreamTrack.applyConstraints() - Web APIs
esents the basic set of constraints that must apply for the promise to resolve. the object may contain an advanced property containing an array of additional mediatrackconstrants objects, which are treated as exact requires. return value a promise which resolves when the constraints have been successfully applied. if the constraints cannot be applied, the promise is rejected with a mediastream
error whose name is overconstrained
error, to indicate that the constraints could not be met. this can happen if the specified constraints are too strict to find a match when attempting to configure the track. examples the following shows how to specify a basic and advanced set of constraints. it specifies that the page or web app needs a width between 640 and 1280 and a height between 480 and 720, wi...
MediaStreamTrack.onoverconstrained - Web APIs
ned event is received. such an event is sent when the track is again able to send data. syntax track.onoverconstrained = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type mediastream
errorevent. example dc.onoverconstrained = function() { alert("overconstrained event detected!"); }; ...
MediaStream Image Capture API - Web APIs
// 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 domexception of type notsupported
error 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 imagecapture.getphotocapabilitie...
MediaTrackConstraints.autoGainControl - Web APIs
simple true or false, the user agent will attempt to obtain media with automatic gain control enabled or disabled as specified, if possible, but will not fail if this can't be done. if, instead, the value is given as an object with an exact field, that field's boolean value indicates a required setting for the automatic gain control feature; if it can't be met, then the request will result in an
error. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'autogaincontrol' in that specification. candidate recommendation initial specification. ...
MediaTrackConstraints.echoCancellation - Web APIs
value is a simple true or false, the user agent will attempt to obtain media with echo cancellation enabled or disabled as specified, if possible, but will not fail if this can't be done. if, instead, the value is given as an object with an exact field, that field's boolean value indicates a required setting for the echo cancellation feature; if it can't be met, then the request will result in an
error. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'echocancellation' in that specification. candidate recommendation initial specification. ...
MediaTrackConstraints.noiseSuppression - Web APIs
value is a simple true or false, the user agent will attempt to obtain media with noise suppression enabled or disabled as specified, if possible, but will not fail if this can't be done. if, instead, the value is given as an object with an exact field, that field's boolean value indicates a required setting for the noise suppression feature; if it can't be met, then the request will result in an
error. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'noisesuppression' in that specification. candidate recommendation initial specification. ...
Media Capabilities API - Web APIs
different browsers support different media types and new media types are always being developed. with the media capabilities api, developers can ensure each user is getting the best bitrate and storage savings for their browser, device, and os capabilities. whether a device uses ...
Media Session API - Web APIs
start media. the following example adds a pointerup event to an on-page play button, which is then used to kick off the media session code: playbutton.addeventlistener('pointerup', function(event) { var audio = document.queryselector('audio'); // user interacted with the page. let's play audio... audio.play() .then(_ => { /* set up media session controls, as shown above. */ }) .catch(
error => { console.log(
error) }); }); specifications specification status comment media session standard draft initial definition. ...
MerchantValidationEvent() - Web APIs
ring 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 type
error the string specified as validationurl could not be parsed as a url. range
error 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. candidate recomm...
MerchantValidationEvent.complete() - Web APIs
lete(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: invalidstate
error 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, we see the client-side code needed to support merchant validation for a payment request called p...
Metadata.modificationTime - Web APIs
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. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera...
Metadata.size - Web APIs
of the file in bytes. example this example checks the size of a log file and removes it if it's larger than a megabyte. workingdirectory.getfile("log/important.log", {}, function(fileentry) { fileentry.getmetadata(function(metadata) { if (metadata.size > 1048576) { fileentry.remove(function() { /* log file removed; do something clever here */ }); } }); }, handle
error); this api has no official w3c or whatwg specification. 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. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera...
Microdata DOM API - Web APIs
same 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 invalidaccess
error 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.g...
Microsoft API extensions - Web APIs
d mspointerhover media apis htmlvideoelement.msframestep() htmlvideoelement.mshorizontalmirror htmlvideoelement.msinsertvideoeffect() htmlvideoelement.msislayoutoptimalforplayback htmlvideoelement.msisstereo3d htmlvideoelement.mszoom htmlaudioelement.msaudiocategory htmlaudioelement.msaudiodevicetype htmlmediaelement.mscleareffects() htmlmediaelement.msinsertaudioeffect() media
error.msextendedcode msgraphicstrust msgraphicstruststatus msisboxed msplaytodisabled msplaytopreferredsourceuri msplaytoprimary msplaytosource msrealtime mssetmediaprotectionmanager mssetvideorectangle msstereo3dpackingmode msstereo3drendermode onmsvideoformatchanged onmsvideoframestepcompleted onmsvideooptimallayoutchanged msfirstpaint pinned sites apis mssitemodeevent mssitem...
MouseEvent() - Web APIs
n case of a mouseenter or mouseover) or is entering (in case of a mouseout or mouseleave). "region", optional and defaulting to null, of type domstring, is the id of the hit region affected by the event. the absence of any hit region is affected, is represented by the null value. in some implementations, passing anything other than a number for the screen and client fields will throw a type
error. the mouseeventinit dictionary also accepts fields from uieventinit and from eventinit dictionaries. specifications specification status comment css object model (cssom) view modulethe definition of 'mouseevent' in that specification. working draft redefines screen and client fields long to double. document object model (dom) level 3 events sp...
MutationObserver.observe() - Web APIs
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 type
error thrown in any of the following circumstances: the options are configured such that nothing will actually be monitored. (for example, if mutationobserverinit.childlist, mutationobserverinit.attributes, and mutationobserverinit.characterdata are all false.) the value of options.attributes is false (indicating that attribute changes are not to be monitored), but attributeoldvalue is true ...
NDEFReader.scan() - Web APIs
ndefrecord.mediatype. signal -- optional abortsignal that allows to cancell this scan() operation. return value a promise that resolves with undefined immediatelly after scheduling read operations for the nfc adapter. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: abort
error the scan operation was aborted with abortsignal passed in options. notallowed
error the permission for this operation was rejected. notsupported
error there is no nfc adapter compatible with web nfc, or a connection can not be established. specifications specification status comment web nfc, scan() draft initial definition. ...
NDEFReader - Web APIs
defreader.ndefreader() returns an ndefreader with configuration specified in the parameters or default ones if no parameters are specified. properties in addition to the properties listed below, ndefreader inherits properties from its parent interface, eventtarget. ndefreader.onreading an event handler for reading event, that notifies about availability of a new reading. ndefreader.on
error an event handler for
error event which is called to notify that an
error occured during reading. methods the ndefreader interface inherits the methods of eventtarget, its parent interface. ndefreader.scan() called to activate the reader (after ensuring hardware and ua compatibility and obtaining permission from the user) or get an
error explaining why feature is not available. speci...
NDEFWriter - Web APIs
abstract interface used to write data to compatible nfc devices, e.g. nfc tags supporting ndef, when these devices are within the reader's magnetic induction field. constructor ndefwriter.ndefwriter() returns an ndefwriter. methods ndefwriter.write() called to write ndef message to a tag (after ensuring hardware and ua compatibility and obtaining permission from the user) or get an
error explaining why feature is not available. specifications specification status comment web nfc, ndefreader draft initial definition. ...
Navigator.getBattery() - Web APIs
promise = navigator.getbattery(); return value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: security
error 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
error note: no user agent currently throws this exception, but the specification describes the following behaviors: this document is not allowed to use this feature. for...
Node.compareDocumentPosition() - Web APIs
ment and contains the node on which comparedocumentposition() was called, then both the document_position_contains and document_position_preceding bits would be set, producing a value of 10 (0x0a). example const head = document.head; const body = document.body; if (head.comparedocumentposition(body) & node.document_position_following) { console.log('well-formed document'); } else { console.
error('<head> is not before <body>'); } note: because the result returned by comparedocumentposition() is a bitmask, the bitwise and operator must be used for meaningful results. specifications specification status comment domthe definition of 'node.comparedocumentposition()' in that specification. living standard document object model (dom) level 3 core sp...
Node - Web APIs
erties: attributes, namespaceuri, prefix, and localname. removed the following methods: issupported(), hasattributes(), getfeature(), setuserdata(), and getuserdata(). document object model (dom) level 3 core specificationthe definition of 'node' in that specification. obsolete the methods insertbefore(), replacechild(), removechild(), and appendchild() returns one more kind of
error (not_supported_err) if called on a document. the normalize() method has been modified so that text node can also be normalized if the proper domconfiguration flag is set. added the following methods: comparedocumentposition(), issamenode(), lookupprefix(), isdefaultnamespace(), lookupnamespaceuri(), isequalnode(), getfeature(), setuserdata(), and getuserdata(). added the following pro...
NodeList.item() - Web APIs
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. ...
NodeList - Web APIs
s an iterator allowing code to go through all values (nodes) of the key/value pairs contained in the collection. example it's possible to loop over the items in a nodelist using a for loop: for (let i = 0; i < mynodelist.length; i++) { let item = mynodelist[i]; } don't use for...in to enumerate the items in nodelists, since they will also enumerate its length and item properties and cause
errors if your script assumes it only has to deal with element objects. also, for..in is not guaranteed to visit the properties in any particular order. for...of loops will loop over nodelist objects correctly: const list = document.queryselectorall('input[type=checkbox]'); for (let checkbox of list) { checkbox.checked = true; } recent browsers also support iterator methods (foreach()) as well as ...
Notification - Web APIs
parameter of the constructor. notification.vibrate read only specifies a vibration pattern for devices with vibration hardware to emit. event handlers notification.onclick a handler for the click event. it is triggered each time the user clicks on the notification. notification.onclose a handler for the close event. it is triggered when the user closes the notification. notification.on
error a handler for the
error event. it is triggered each time the notification encounters an
error. notification.onshow a handler for the show event. it is triggered when the notification is displayed. methods static methods these methods are available only on the notification object itself. notification.requestpermission() requests permission from the user to display notifications. insta...
Using the Notifications API - Web APIs
ion. this is in line with the specification, which states: "when a notification is closed, either by the underlying notifications platform or by the user, the close steps for it must be run." notification events there are four events that are triggered on the notification instance: click triggered when the user clicks on the notification. close triggered once the notification is closed.
error triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason. show triggered when the notification is displayed to the user. these events can be tracked using the onclick, onclose, on
error, and onshow handlers. because notification also inherits from eventtarget, it's possible to use the addeventlistener() method on i...
OVR_multiview2.framebufferTextureMultiviewOVR() - Web APIs
ge. 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.framebuffertexturemultiviewovr(gl.draw_...
OfflineAudioContext.resume() - Web APIs
the resume() method of the offlineaudiocontext interface resumes the progression of 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 invalidstate
error. syntax offlineaudiocontext.resume().then(function() { ... }); parameters none. returns a promise resolving to void. exceptions the promise is rejected when the following exception is encountered. invalidstate
error 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. wo...
OfflineAudioContext.suspend() - Web APIs
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. invalidstate
error 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 definition of 'suspend()' in that specification. working draft initial definitio...
OrientationSensor - Web APIs
ond. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor = new absoluteorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere. model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('
error',
error => { if (event.
error.name == 'notreadable
error') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors. becuase the permissions uses promises, a good way to request permissions is to use promise.all. const sensor = new absoluteorientationsensor(); promise.all([nav...
OscillatorNode.type - Web APIs
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 invalidstate
error 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 (window.audiocontext ...
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 type
error thrown when one of the arguments is invalid or missing. invalidmodification
error 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 p...
PannerNode.PannerNode() - Web APIs
: 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 range
error the refdistance, maxdistance, or rollofffactor properties have been given a value that is outside the accepted range. invalidstate
error 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 speci...
PannerNode.coneOuterGain - Web APIs
ount 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 invalidstate
error 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 function to figure out...
PannerNode.maxDistance - Web APIs
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 range
error 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 position of one or bo...
PannerNode.refDistance - Web APIs
e as the audio source 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 range
error is thrown. exceptions range
error 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 ...
PannerNode.rolloffFactor - Web APIs
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 range
error 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 sound const z_dis...
ParentNode.replaceChildren() - Web APIs
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 hierarchyrequest
error: 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 parents, without having to re...
PaymentRequest.PaymentRequest() - Web APIs
elected: true } ] }; var options = {requestshipping: true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. }) .catch(function(err) { // do something with the
error from request.show(). }); } catch (e) { // catch any other
errors. } specifications specification status comment payment request apithe definition of 'paymentrequest() constructor' in that specification. candidate recommendation initial definition. ...
PaymentRequest.canMakePayment() - Web APIs
instance, you might call canmakepayment() to determine if the browser will let the user pay using payment request api, and if it won't, you could fall back to another payment method, or offer a list of methods that aren't handled by payment request api (or even provide instructions for paying by mail or by phone). syntax paymentrequest.canmakepayment() .then( canpay => { ... }) .catch(
error => { ... }) canpay = await paymentrequest.canmakepayment(); returns a promise to a boolean that resolves to true if the user agent supports any of the payment methods supplied when instantiating the request using the paymentrequest constructor. if the payment can't be processed, the promise receives a value of false. note: if you call this too often, the browser may reject the returned prom...
PaymentRequest.onshippingaddresschange - Web APIs
w paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of clarity. }).catch(function(err) { console.
error("uh oh, something bad happened", err.message); }); specifications specification status comment payment request apithe definition of 'onshippingaddresschange' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the da...
PaymentRequest.onshippingoptionchange - Web APIs
= 'jp') { shippingoption.id = 'jp'; shippingoption.label = 'international shipping'; shippingoption.amount.value = '10.00'; details.total.amount.value = '65.00'; // shipping to elsewhere is unsupported } else { // empty array indicates rejection of the address details.shippingoptions = []; return promise.resolve(details); console.log(details.
error); } // hardcode for simplicity if (details.displayitems.length === 2) { details.displayitems[2] = shippingoption; } else { details.displayitems.push(shippingoption); } details.shippingoptions = [shippingoption]; return promise.resolve(details); })(details, request.shippingaddress)); }); specifications specification status comment ...
PaymentRequest.shippingAddress - Web APIs
ent = new paymentrequest(supportedinstruments, details, options); payment.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for brevity. ...
PaymentRequest.shippingOption - Web APIs
candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please...
PaymentRequest: shippingaddresschange event - Web APIs
return detailsupdate; }; you can also establish a handler for shippingaddresschange using the onshippingaddresschange event handler property: paymentrequest.onshippingaddresschange = event => { let detailsupdate = checkaddress(paymentrequest.shippingaddress); event.updatewith(detailsupdate); }; specifications specification status comment payment request apith...
PaymentResponse.onpayerdetailchange - Web APIs
ame(payername)); oldpayername = payername; } if (oldpayeremail !== payeremail) { promisestovalidate.push(validateemail(payeremail)); oldpayeremail = payeremail; } if (oldpayerphone !== payerphone) { promisestovalidate.push(validatephone(payerphone)); oldpayerphone = payerphone; } // as each validation promise resolves, add the results of the // validation to the
errors list const
errors = await promise.all(promisestovalidate).then(results => results.reduce((
errors, result), object.assign(
errors, result)) ); // if we found any
errors, wait for them to be corrected if (object.getownpropertynames(
errors).length) { await response.retry(
errors); } else { // we have a good payment; send the data to the server await fetch("/pay-for-things...
PaymentResponse.shippingAddress - Web APIs
w paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of brevity. ...
PaymentResponse.shippingOption - Web APIs
st(supportedinstruments, details, options); request.addeventlistener('shippingoptionchange', function(evt) { evt.updatewith(new promise(function(resolve, reject) { updatedetails(details, request.shippingoption, resolve, reject); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of brevity. ...
PaymentResponse - Web APIs
aymentresponse.shippingoption read only secure context returns the id attribute of the shipping option selected by the user. this option is only present when the requestshipping option is set to true in the options parameter of the paymentrequest() constructor. methods paymentresponse.retry() secure context if something is wrong with the payment response's data (and there is a recoverable
error), this method allows a merchant to request that the user retry the payment. the method takes an object as argument, which is used to signal to the user exactly what is wrong with the payment response so they can try to correct any issues. paymentresponse.complete() secure context notifies the user agent that the user interaction is over. this causes any remaining user interface to be closed. th...
performance.mark() - Web APIs
mance interface's getentries*() methods (getentries(), getentriesbyname() or getentriesbytype()). the mark()'s stores its data internally as performanceentry. note: this feature is available in web workers. syntax performance.mark(name); arguments name a domstring representing the name of the mark. if the name given to this method already exists in the performancetiming interface, syntax
error is thrown. return value void example the following example shows how to use mark() to create and retrieve performancemark entries. // create a bunch of marks. performance.mark("squirrel"); performance.mark("squirrel"); performance.mark("monkey"); performance.mark("monkey"); performance.mark("dog"); performance.mark("dog"); // get all of the performancemark entries. const allentries = ...
PerformanceServerTiming - Web APIs
his: const http = require('http'); function requesthandler(request, response) { const headers = { 'server-timing': ` cache;desc="cache read";dur=23.2, db;dur=53, app;dur=47.2 `.replace(/\n/g, '') }; response.writehead(200, headers); response.write(''); return settimeout(_ => { response.end(); }, 1000) }; http.createserver(requesthandler).listen(3000).on('
error', console.
error); the performanceservertiming entries are now observable from javascript via the performanceresourcetiming.servertiming property: let entries = performance.getentriesbytype('resource'); console.log(entries[0].servertiming); // 0: performanceservertiming {name: "cache", duration: 23.2, description: "cache read"} // 1: performanceservertiming {name: "db", duration: 53, description...
PerformanceTiming.connectEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.connectend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the connection is opened network. if the transport layer reports an
error and the connection establishment is started again, the last connection establisment end time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. syntax time = performancetiming.connectend; specifications specification status c...
PerformanceTiming.connectStart - Web APIs
erface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.connectstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the request to open a connection is sent to the network. if the transport layer reports an
error and the connection establishment is started again, the last connection establisment start time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. syntax time = performancetiming.connectstart; specifications specification status comment navigation timingthe definition of 'performancetiming.connectstart' in that spec...
Permissions.query() - Web APIs
er, 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 type
error 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 if (result.state == 'prompt') { showbuttontoenablelocal...
Permissions.revoke() - Web APIs
vant 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 type
error 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(result) { repor...
Multi-touch interaction - Web APIs
upport the application but aren't directly involved with the event flow. cache management these functions manage the global event caches evcache1, evcache2 and evcache3. ...
RTCDtlsTransport.state - Web APIs
ting dtls is in the process of negotiating a secure connection and verifying the remote fingerprint. connected dtls has completed negotiation of a secure connection and verified the remote fingerprint. closed the transport has been closed intentionally as the result of receipt of a close_notify alert, or calling rtcpeerconnection.close(). failed the transport has failed as the result of an
error (such as receipt of an
error alert or failure to validate the remote fingerprint). examples this example presents a function, tallysenders(), which iterates over an rtcpeerconnection's rtcrtpsenders, tallying up how many of them are in various states. the function returns an object containing properties whose values indicate how many of the senders are in each state. let pc = new rtcpeerconne...
RTCIceCandidate.RTCIceCandidate() - Web APIs
idate 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 type
error 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 specification. ...
RTCIceCandidate.address - Web APIs
ddress 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 operation
error 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 topol...
RTCIceCandidate.candidate - Web APIs
p = "192.168.0.56" port = 44323 type = "host" example in this example, we see a function which receives as input an sdp string containing an ice candidate received from the remote peer during the signaling process. function handlenewicecandidate(candidatesdp) { var candidateobj = new rtcicecandidate(candidatesdp); mypeerconnection.addicecandidate(candidateobj).catch({ /* handle the
error thrown by addicecandidate() */ }); } the handlenewicecandidate() function shown here passes the received candidate's sdp text into rtcicecandidate() to receive an rtcicecanddiate object in return, which represents the candidate. the new candidate is then passed into rtcpeerconnection.addicecandidate() to add the candidate to the list of candidates for webrtc to consider using for the connecti...
RTCIceCandidate.foundation - Web APIs
be used 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 operation
error 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 t...
RTCIceCandidate.port - Web APIs
var port = 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 operation
error 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 numbe...
RTCIceCandidate.priority - Web APIs
ue indicating 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 operation
error 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 c...
RTCIceCandidate.sdpMLineIndex - Web APIs
var sdpmlineindex = 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 type
error 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
d from 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 type
error 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
the stun 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 operation
error 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 communic...
RTCIceCandidate.usernameFragment - Web APIs
if it does, ssnewcandidate() aborts. otherwise, after checking every receiver, it adds the new candidate to the connection. specifications specification status comment webrtc 1.0: real-tim...
RTCIceCandidateInit.sdpMLineIndex - Web APIs
he rtcicecandidate 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 type
error 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
ndidateinit 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 type
error 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. ...
RTCIceTransport - Web APIs
whether the ice agent is the one that makes the final decision as to the candidate pair to use or not. state read only a domstring indicating what the current state of the ice agent is. the value of state can be used to determine whether the ice agent has made an initial connection using a viable candidate pair ("connected"), made its final selection of candidate pairs ("completed"), or in an
error state ("failed"), among other states. see the rtcicetransportstate enumerated type for a complete list of states. methods also includes methods from eventtarget, the parent interface. getlocalcandidates() returns an array of rtcicecandidate objects, each describing one of the ice candidates that have been gathered so far for the local device. these are the same candidates which have alread...
RTCInboundRtpStreamStats.fecPacketsReceived - Web APIs
the fecpacketsreceived property of the rtcinboundrtpstreamstats dictionary indicates how many forward
error correction (fec) packets have been received by this rtp receiver from the remote peer. an fec packet provides parity information which can be used to attempt to reconstruct rtp data packets which have been corrupted in transit. syntax var fecpacketsreceived = rtcinboundrtpstreamstats.fecpacketsreceived; value an unsigned integer value which indicates the total number of fec packets which have been recieved from the remote peer during this rtp session. forward
error correction uses an exclusive-or method to perform parity checks on the received data. by using the fec parity information to attempt to reconstruct damaged packets, it is possible to avoid the need to retransmit damaged p...
RTCInboundRtpStreamStats - Web APIs
edrtpstreamstats dictionary, whose properties are also available. averagertcpinterval a floating-point value indicating the average rtcp interval between two consecutive compound rtcp packets. bytesreceived a 64-bit integer which indicats the total numer of bytes that have been received so far for this media source. fecpacketsdiscarded an integer value indicating the number of rtp forward
error correction (fec) packets which have been received for this source, for which the
error correction payload was discarded. fecpacketsreceived an integer value indicating the total number of rtp fec packets received for this source. this counter may also be incremented when fec packets arrive in-band along with media content; this can happen with opus, for example. fircount an integer value whic...
RTCPeerConnection.addStream() - Web APIs
if the signalingstate is set to stable, the event negotiationneeded is sent on the rtcpeerconnection to indicate that ice negotiation must be repeated to consider the new stream. ...
RTCPeerConnection.addTrack() - Web APIs
ream 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 invalidaccess
error the specified track (or all of its underlying streams) is already part of the rtcpeerconnection. invalidstate
error 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 streams are specific to e...
RTCPeerConnection.addTransceiver() - Web APIs
ion 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 type
error 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.close() - Web APIs
urns (they may still be in the process of stopping, but for all intents and purposes, they're stopped). once this method returns, the signaling state as returned by rtcpeerconnection.signalingstate is closed. make sure that you delete all references to the previous rtcpeerconnection before attempting to create a new one that connects to the same remote peer, as not doing so might result in some
errors depending on the browser. example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); pc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function () { console.log("datachannel close"); }; ...
RTCPeerConnection.getIdentityAssertion() - Web APIs
it is not expected for the application dealing with the rtcpeerconnection: this is automatically done; an explicit call only allows to anticipate the need. syntax pc.getidentityassertion(); there is neither parameter nor return value for this method. ...
RTCPeerConnection: identityresult event - Web APIs
to inform it that an assertion has been generated by an associated identity provider (idp) during the process of creating an sdp offer or answer. note: while older versions of the webrtc specification used events to report assertions, this has been deprecated and removed from the specification. instead, the peeridentity property returns a promise that resolves with an identity or rejects if an
error occurs or if unable to validate the identity. bubbles no cancelable no interface rtcidentityevent event handler property onidentityresult specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'identityresult' in that specification. candidate recommendati...
RTCPeerConnection.onconnectionstatechange - Web APIs
you can look at the value of the peer connection's connectionstate property to determine what the new state is. example pc.onconnectionstatechange = function(event) { switch(pc.connectionstate) { case "connected": // the connection has become fully connected break; case "disconnected": case "failed": // one or more transports has terminated unexpectedly or in an
error break; case "closed": // the connection has been closed break; } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.onconnectionstatechange' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.onnegotiationneeded - Web APIs
ndler for negotiationneeded events to handle creating an offer, configuring the local end of the connection, and sending the offer to the remote peer. pc.onnegotiationneeded = function() { pc.createoffer().then(function(offer) { return pc.setlocaldescription(offer); }) .then(function() { // send the offer to the remote peer through the signaling server }); }) .catch(report
error); } first, it creates the offer by calling createoffer(). when that succeeds, the offer is passed into setlocaldescription() to set the local description for the connection. once that's succeeded in turn, the offer can be sent to the signaling server for delivery to the remote peer. specifications specification status comment webrtc 1.0: real-time communication betw...
RTCPeerConnection.onsignalingstatechange - Web APIs
rface specifies a function to be called when the signalingstatechange event occurs on an rtcpeerconnection interface. the function receives as input the event object of type event; this event is sent when the peer connection's signalingstate changes, which may happen either because of a call to setlocaldescription() or to setremotedescription(). syntax rtcpeerconnection.onsignalingstatechange =
errorhandler; value set this to a function which you provide that receives an event object as input; this contains the signalingstatechange event. this event object doesn't provide details about what changed, but you can examine the signalingstate property to determine what the new state is. you may also, as always, set up a handler for the signalingstatechange event using addeventlistener(): myrt...
RTCPeerConnection.removeStream() - Web APIs
the rtcpeerconnection.removestream() method removes a mediastream as a local source of audio or video. if the negotiation already happened, a new one will be needed for the remote peer to be able to use it. because this method has been deprecated, you should instead use removetrack() if your target browser versions have implemented it. if the signalingstate is set to "closed", an invalidstate
error is raised. if the signalingstate is set to "stable", the event negotiationneeded is sent on the rtcpeerconnection. syntax rtcpeerconnection.removestream(mediastream); parameters mediastream a mediastream specifying the stream to remove from the connection. return value undefined. example var pc, videostream; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerc...
RTCPeerConnection.removeTrack() - Web APIs
ing 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 invalidstate
error 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); }); document.getelementby...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
let logentry = `<div class="stats-entry"><h2>report id: ${endremoteoutbound.id}</h2>` + `remote peer sent ${packetssent} packets ${timestring}.<br>` + `${framestring}` + `data size: ${bytessent} bytes.</div>`; statsbox.innerhtml += logentry; } else { statsbox.innerhtml += `<div class="stats-
error">unable to find initial statistics for id ${endremoteoutbound.id}.</div>` } } statsbox.scrollto(0, statsbox.scrollheight); } } } here's what's going on in the networkteststop() function: after calling the rtcpeerconnection method getstats() to get the latest statistics report for the connection and storing it in endreport, this is an rtcstatsreport object, which maps ...
RTCRtpCapabilities - Web APIs
s of the transport. those components are: red (redundant audio data) the media type of an red entry may vary due to there being several versions of it, but it will end with red, such as video/red or video/fwdred. the base red standard can be found in rfc 2198. there may be multiple entries for red if different forms are supported; each will have a unique media type in that case. fec (forward
error correction) an fec component handles
error correction data; its media type may also vary due to there being advanced versions of the standard available, but it will always end with fec. one possible value is video/ulpfec (a generic
error connection model). there may also be multiple fec entries if more than one form is supported. rtx (retransmission) this component is responsible for retransmi...
RTCRtpEncodingParameters.scaleResolutionDownBy - Web APIs
t the 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 range
error 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.setStreams() - Web APIs
er.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 invalidstate
error 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 event being dispatched ...
RTCRtpTransceiver.direction - Web APIs
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: invalidstate
error 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 invalidstate
error exception will occur if the connection is closed or the receiver is stopped. if the new value of direction is in fact different from the existing value, renegotiation of the connection is required, so a negotiation...
RTCRtpTransceiver.stop() - Web APIs
perty 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 invalidstate
error 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 renegotiation is triggered by...
RTCSessionDescription() - Web APIs
ption yourself. navigator.getusermedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // adding a local stream won't trigger the onaddstream callback pc.addstream(stream); pc.createoffer(function(offer) { pc.setlocaldescription(new rtcsessiondescription(offer), function() { // send the offer to a server to be forwarded to the friend you're calling. },
error); },
error); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescription()' in that specification. candidate recommendation initial specification. ...
RTCStatsIceCandidatePairState - Web APIs
his represents the state of this candidate pair within the ice check list for the rtcpeerconnection. see ice check lists in rtcicecandidatepairstats.state for further information about how ice check lsits work. values failed a check for this pair has been performed but failed. a failure can occur either because no response was received or because the response indicated that an unrecoverable
error occurred. frozen no check has been performed yet for this candidate pair, and performing the check is blocked until another check is successful. once that check has succeeded, this pair will unfreeze and move into the waiting state. in-progress a check has been initiated for this pair, but the check's transaction is still in progress. succeeded a check for this pair has been completed succe...
Range.compareBoundaryPoints() - Web APIs
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 domexception with a notsupported
error 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_end, sourcerange); spe...
Range.setEnd() - Web APIs
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 domexception objects of the following types: invalidnodetype
error the node specified by endnode is a doctype node; range endpoints cannot be located inside a doctype node. indexsize
error 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 cdatasection, then endoffset is the number of characters from the start of endnode. for other no...
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 type
error 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 type
error 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 - Web APIs
controller.byobrequest read only returns the current byob pull request. readablebytestreamcontroller.desiredsize read only returns the desired size required to fill the stream's internal queue. methods readablebytestreamcontroller.close() closes the associated stream. readablebytestreamcontroller.enqueue() enqueues a given chunk in the associated stream. readablebytestreamcontroller.
error() causes any future interactions with the associated stream to
error. examples tbd. specifications specification status comment streamsthe definition of 'readablebytestreamcontroller' in that specification. living standard initial definition ...
ReadableStream.cancel() - Web APIs
m 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 type
error 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 searchterm = "...
ReadableStream.getReader() - Web APIs
at 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 range
error the provided mode value is not "byob" or undefined. type
error 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 sequentially and output ...
ReadableStream.tee() - Web APIs
e 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 type
error 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 code. function t...
ReadableStream - Web APIs
ed, no other reader can be acquired until this one is released. readablestream.pipethrough() provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. readablestream.pipeto() pipes the current readablestream to a given writablestream and returns a promise that fulfills when the piping process completes successfully, or rejects if any
errors were encountered. readablestream.tee() the tee method tees this readable stream, returning a two-element array containing the two resulting branches as new readablestream instances. each of those streams receives the same incoming data. readablestream[@@asynciterator]() alias of getiterator method. examples in the following example, an artificial response is created to stream html fragmen...
ReadableStreamBYOBReader.ReadableStreamBYOBReader() - Web APIs
tes 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 type
error 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
e 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 type
error 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.closed - Web APIs
the closed read-only property of the readablestreambyobreader interface returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream
errors. syntax var closed = readablestreambyobreader.closed; value a promise. examples tbd. specifications specification status comment streamsthe definition of 'closed' in that specification. living standard initial definition. ...
ReadableStreamBYOBReader.read() - Web APIs
alue a promise, which fulfills/rejects with a result depending on the state of the stream. the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes
errored, the promise will be rejected with the relevant
error. exceptions type
error 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 standa...
ReadableStreamBYOBReader.releaseLock() - Web APIs
the releaselock() method of the readablestreambyobreader interface releases the reader's lock on the stream. after the lock is released, the reader is no longer active. if the associated stream is
errored when the lock is released, the reader will appear
errored 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 type
error being thrown. syntax readablestreambyobreader.releaselock(); parameters none. return value undefined. exceptions type
error the source object is not a readablestreambyobreader, or a read request is pending. examples tbd. specification...
ReadableStreamBYOBReader - Web APIs
ustom readablestream() constructor). constructor readablestreambyobreader() creates and returns a readablestreambyobreader object instance. properties readablestreambyobreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream
errors. methods readablestreambyobreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreambyobreader.read() returns a promise providing access to the next chunk in the stream's internal queue. readablestreambyobreader.releaselock() releases the ...
ReadableStreamBYOBRequest.respondWithNewView() - Web APIs
the respondwithnewview() method of the readablestreambyobrequest interface xxx syntax readablestreambyobrequestinstance.respondwithnewview(view); parameters view xxx return value void. exceptions type
error 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
ll 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 type
error 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 readablestream.c...
ReadableStreamDefaultController.desiredSize - Web APIs
ize = readablestreamdefaultcontroller.desiredsize; value an integer. note that this can be negative if the queue is over-full. examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using desiredsize to manually detect when the stream is full and apply backpressure, and also of using readablestreamdefaultcontroller.
error() to manually trigger a stream
error if another part of the system it relies on fails. specifications specification status comment streamsthe definition of 'desiredsize' in that specification. living standard initial definition. ...
ReadableStreamDefaultController - Web APIs
omatically during readablestream construction. properties readablestreamdefaultcontroller.desiredsize read only returns the desired size required to fill the stream's internal queue. methods readablestreamdefaultcontroller.close() closes the associated stream. readablestreamdefaultcontroller.enqueue() enqueues a given chunk in the associated stream. readablestreamdefaultcontroller.
error() causes any future interactions with the associated stream to
error. 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 readab...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
rns 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 type
error 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, until the stream ...
ReadableStreamDefaultReader.cancel() - Web APIs
e: 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 type
error 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 being read, a...
ReadableStreamDefaultReader.closed - Web APIs
syntax var closed = readablestreamdefaultreader.closed; value a promise. examples in this snippet, a previously-created reader is queried to see if the stream has been closed. when it is closed, the promise fulfills and the message is logged to the console. ...
ReadableStreamDefaultReader.read() - Web APIs
alue a promise, which fulfills/rejects with a result depending on the state of the stream. the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes
errored, the promise will be rejected with the relevant
error. exceptions type
error 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-create...
ReadableStreamDefaultReader.releaseLock() - Web APIs
the releaselock() method of the readablestreamdefaultreader interface releases the reader's lock on the stream. if the associated stream is
errored when the lock is released, the reader will appear
errored 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 readablestreamdefaultreader.read() method has not finished. this will result in a type
error being thrown. syntax readablestreamdefaultreader.releaselock(); parameters none. return value undefined. exceptions type
error the source object is not a readablestreamdefaultreader, or a read request is pending. examples function fetchstream() { const reader = stream.getreader(); ... ...
ReadableStreamDefaultReader - Web APIs
rk (e.g. a fetch request). constructor readablestreamdefaultreader() creates and returns a readablestreamdefaultreader object instance. properties readablestreamdefaultreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream
errors. methods readablestreamdefaultreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreamdefaultreader.read() returns a promise providing access to the next chunk in the stream's internal queue. readablestreamdefaultreader.releaselock() rele...
RelativeOrientationSensor - Web APIs
or. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor = new relativeorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere. model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('
error',
error => { if (event.
error.name == 'notreadable
error') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors. becuase the permissions uses promises, a good way to request permissions is to use promise.all. const sensor = new relativeorientationsensor(); promise.all([nav...
Reporting API - Web APIs
urls. the endpoints are arranged into groups; an endpoint group can work together to provide load balancing (each endpoint will receive a specified proportion of report traffic) and safeguarding against failure (fallback endpoints can be specified to use if the primary ones fail). note: there is no absolute guarantee of report delivery — a report could still fail to be collected if a serious
error occurs. reports sent to endpoints can be retrieved independently of the running of the websites they relate to, which is useful — a crash for example could bring down a web site and stop anything running, but a report could still be obtained to give the developer some clues as to why it happened. reporting observers reports can also be obtained via reportingobserver objects created via java...
Request.clone() - Web APIs
in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) if intend to modify the request, you may prefer the request constructor. syntax var newrequest = request.clone(); parameters none. return value a request object, which is an exact copy of the request that clone() was called on. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request. ...
Request.mode - Web APIs
cors, no-cors, same-origin, or navigate.) this is used to determine if cross-origin requests lead to valid responses, and which properties of the response are readable. syntax var mymode = request.mode; value a requestmode value. the associated mode, available values of which are: same-origin — if a request is made to another origin with this mode set, the result is simply an
error. you could use this to ensure that a request is always being made to your origin. no-cors — prevents the method from being anything other than head, get or post, and the headers from being anything other than simple headers. if any serviceworkers intercept these requests, they may not add or override any headers except for those that are simple headers. in addition, javascript may not access ...
Request.redirect - Web APIs
the redirect read-only property of the request interface contains the mode for how redirects are handled. syntax var myredirect = request.redirect; value a requestredirect enum value, which can be one the following strings: follow
error manual if not specified when the request is created, it takes the default value of follow. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request redirect value in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification. living standard initial definition ...
Response.clone() - Web APIs
in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) syntax var response2 = response1.clone(); parameters none. value a response object. example in our fetch response clone example (see fetch response clone live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(). ...
Response.redirect() - Web APIs
t 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 range
error the specified status is not a redirect status. type
error 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 ...
Response.redirected - Web APIs
"unexpected redirect"; } else { elem.innerhtml = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "
error" in the init parameter when calling fetch(), like this: fetch("awesome-picture.jpg", { redirect: "
error" }).then(function(response) { return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); specifications specification status comment fetchthe definiti...
Response - Web APIs
e response. body interface properties response implements body, so it also has the following properties available to it: body.body read only a simple getter exposing a readablestream of the body contents. body.bodyused read only stores a boolean that declares whether the body has been used in a response yet. methods response.clone() creates a clone of a response object. response.
error() returns a new response object associated with a network
error. response.redirect() creates a new response with a different url. body interface methods response implements body, so it also has the following methods available to it: body.arraybuffer() takes a response stream and reads it to completion. it returns a promise that resolves with an arraybuffer. body.blob() takes a respons...
SVGElement - Web APIs
le, globaleventhandlers, htmlorforeignelement, svgelementinstance events listen to these events using addeventlistener() or by assigning an event listener to the equivalent on... handler property defined on globaleventhandlers or windoweventhandlers. abort fired when page loading is stopped before an svg element has been allowed to load completely. also available via the onabort property.
error fired when an svg element does not load properly or when an
error occurs during script execution. also available via the on
error property. load fires on an svgelement when it is loaded in the browser. also available via the onload property. resize fired when an svg document is being resized. also available via the onresize property. scroll fired when an svg document view is being shifte...
SVGRect - Web APIs
the exact effect of this coordinate depends on each element. if the attribute is not specified, the effect is as if a value of 0 were specified. svgrect.y the exact effect of this coordinate depends on each element.if the attribute is not specified, the effect is as if a value of 0 were specified. svgrect.width this represents the width of the rectangle.a value that is negative results to an
error. a value of zero disables rendering of the element svgrect.height this represents the height of the rectangle.a value that is negative results to an
error.a value of zero disables rendering of the element. methods this interface also inherits properties from its parent, domrectreadonly. specifications specification status comment geometry interfaces module level 1th...
ScriptProcessorNode.bufferSize - Web APIs
; // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"
error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingeven...
ScriptProcessorNode.onaudioprocess - Web APIs
// load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"
error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingeven...
ScriptProcessorNode - Web APIs
; // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"
error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingeven...
Selection.setBaseAndExtent() - Web APIs
g 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 indexsize
error 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 additional paragraph that sits in between the two nodes. next, we have two form inputs that allow you to set the anchoroffset and focusoffset — they both have a default value o...
Sensor - Web APIs
ambientlightsensor gyroscope linearaccelerationsensor magnetometer orientationsensor properties sensor.activated read only returns a boolean indicating whether the sensor is active. sensor.hasreading read only returns a boolean indicating whether the sensor has a reading. sensor.timestamp read only returns the time stamp of the latest sensor reading. event handlers sensor.on
error called when an
error occurs on one of the child interfaces of the sensor interface. sensor.onreading called when a reading is taken on one of the child interfaces of the sensor interface. sensor.onactivate called when one of the sensor interface's becomes active. methods sensor.start() activates one of the sensors based on sensor. sensor.stop() deactivates one of the sensors based on...
Server-sent events - Web APIs
it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. these incoming messages can be treated as events + data inside the web page. concepts and usage to learn how to use server-sent events, see our article using server-sent events. interfaces eventsource defines all the features that handle connecting to a server, receiving events/data,
errors, closing a connection, etc. examples simple sse demo using php specification specification status comment html living standardthe definition of 'server-sent events' in that specification. living standard see also tools eventsource polyfill for node.js remy sharp’s eventsource polyfill yaffle’s eventsource polyfill rick waldron’s jqu...
ServiceWorkerGlobalScope.onnotificationclick - Web APIs
displayed notification spawned by serviceworkerregistration.shownotification(). notifications created on the main thread or in workers which aren't service workers using the notification() constructor will instead receive a click event on the notification object itself. note: trying to create a notification inside the serviceworkerglobalscope using the notification() constructor will throw an
error. syntax serviceworkerglobalscope.onnotificationclick = function(notificationevent) { ... }; example self.onnotificationclick = function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(funct...
onnotificationclose - Web APIs
displayed notification spawned by serviceworkerregistration.shownotification(). notifications created on the main thread or in workers which aren't service workers using the notification() constructor will instead receive a close event on the notification object itself. note: trying to create a notification inside the serviceworkerglobalscope using the notification() constructor will throw an
error. syntax serviceworkerglobalscope.onnotificationclose = function(notificationevent) { ... }; serviceworkerglobalscope.addeventlistener('notificationclose', function(notificationevent) { ... }); example //inside a service worker. self.onnotificationclose = function(event) { console.log('on notification close: ', event.notification.tag); }; specifications specification status ...
ServiceWorkerRegistration - Web APIs
// if updatefound is fired, it means that there's // a new service worker being installed. var installingworker = registration.installing; console.log('a new service worker is being installed:', installingworker); // you can listen for changes to the installing service worker's // state via installingworker.onstatechange }); }) .catch(function(
error) { console.log('service worker registration failed:',
error); }); } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkerregistration' in that specification. working draft initial definition. push apithe definition of 'pushmanager' in that specificatio...
SharedWorker() - Web APIs
ls 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 security
error 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 network
error is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntax
error is raised if aurl cannot be parsed. examples the following code snippet shows creation of a sharedworker object using th...
SharedWorker - Web APIs
e: if sharedworker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port). constructors sharedworker() creates a shared web worker that executes the script at the specified url. properties inherits properties from its parent, eventtarget, and implements properties from abstractworker. abstractworker.on
error is an eventlistener that is called whenever an
errorevent of type
error bubbles through the worker. sharedworker.port read only returns a messageport object used to communicate with and control the shared worker. methods inherits methods from its parent, eventtarget, and implements methods from abstractworker. example in our basic shared worker example (run shared worker), we have two...
SourceBuffer.appendWindowEnd - Web APIs
ut. 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 invalidaccess
error an attempt was made to set the value to less than or equal to sourcebuffer.appendwindowstart, or nan. invalidstate
error this sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), or this sourcebuffer has been removed from the mediasource. example tbd specifications specification status comment media sourc...
SourceBuffer.appendWindowStart - Web APIs
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 invalidaccess
error an attempt was made to set the value to less than 0, or a value greater than or equal to sourcebuffer.appendwindowend. invalidstate
error this sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), or this sourcebuffer has been removed from the mediasource. example tbd specifications specification status comment ...
SourceBuffer.mode - Web APIs
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 invalidaccess
error an attempt was made to set the value to segments when the initial value is sequence. invalidstate
error the sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), the last media segment appended to this sourcebuffer is incomplete, or this sourcebuffer has been removed from the mediasource. example this snippet sets the sourcebuffer ...
SourceBuffer.remove() - Web APIs
buffer.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 invalidaccess
error 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. invalidstate
error the sourcebuffer.updating property is equal to true, or this sourcebuffer has been removed from the mediasource. example tbd. specifications specification ...
SourceBuffer.timestampOffset - Web APIs
ments 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 invalidstate
error one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is currently true), a media segment inside the sourcebuffer is currently being parsed, or this sourcebuffer has been removed from the mediasource. example tbd specifications specification status comment media source extensionsthe de...
SourceBuffer.trackDefaults - Web APIs
on 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 invalidstate
error 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 ...
SpeechRecognition - Web APIs
event listener to the oneventname property of this interface. audiostart fired when the user agent has started to capture audio. also available via the onaudiostart property. audioend fired when the user agent has finished capturing audio. also available via the onaudioend property. end fired when the speech recognition service has disconnected. also available via the onend property.
error fired when a speech recognition
error occurs. also available via the on
error property. nomatch fired when the speech recognition service returns a final result with no significant recognition. this may involve some degree of recognition, which doesn't meet or exceed the confidence threshold. also available via the onnomatch property. result fired when the speech recognition service returns...
SpeechSynthesisUtterance - Web APIs
t the utterance will be spoken at. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. boundary fired when the spoken utterance reaches a word or sentence boundary. also available via the onboundary property. end fired when the utterance has finished being spoken. also available via the onend property.
error fired when an
error occurs that prevents the utterance from being succesfully spoken. also available via the on
error property mark fired when the spoken utterance reaches a named ssml "mark" tag. also available via the onmark property. pause fired when the utterance is paused part way through. also available via the onpause property. resume fired when a paused utterance is resumed. als...
StaticRange.StaticRange() - Web APIs
t 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 invalidnodetype
error a domexception 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.. specifications ...
Using the Storage Access API - Web APIs
ess. document.hasstorageaccess().then(hasaccess => { if (!hasaccess) { return document.requeststorageaccess(); } }).then(_ => { // now we have first-party storage access! // let's access some items from the first-party cookie jar document.cookie = "foo=bar"; // set a cookie localstorage.setitem("username", "john"); // access a localstorage entry }).catch(_ => { //
error obtaining storage access. }); note that access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click — so this code needs to be run inside some kind of user gesture-based event handler, for example: btn.addeventlistener('click', () => { // run code here }); ...
Streams API - Web APIs
, then process the whole lot after it is fully received. with streams being available to javascript, this all changes — you can now start processing raw data with javascript bit by bit as soon as it is available on the client-side, without needing to generate a buffer, string, or blob. there are more advantages too — you can detect when streams start or end, chain streams together, handle
errors and cancel streams as required, and react to the speed of the stream is being read at. the basic usage of streams hinges around making responses available as streams. for example, the response body returned by a successful fetch request can be exposed as a readablestream, and you can then read it using a reader created with readablestream.getreader(), cancel it with readablestream.cancel(), etc...
SubtleCrypto.decrypt() - Web APIs
e 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: invalidaccess
error 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). operation
error raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or there was an
error decrypting the ciphertext). supported algorithms the decrypt() method supports the ...
SubtleCrypto.deriveBits() - Web APIs
he 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: invalidaccess
error 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 the derived key doesn't define a key length. supported algorithms see the supported algorithms sectio...
SubtleCrypto.encrypt() - Web APIs
-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: invalidaccess
error 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). operation
error raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or aes-gcm plaintext longer than 2³⁹−256 bytes). supported algorithms the web crypto api provides...
SubtleCrypto.exportKey() - Web APIs
keyinfo 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: invalidaccess
error raised when trying to export a non-extractable key. notsupported raised when trying to export in an unknown format. type
error 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 arraybuffer containing the bytes for the key. see the complete code on github. /* export the given key ...
SubtleCrypto.generateKey() - Web APIs
ew 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: syntax
error raised when the result is a cryptokey of type secret or private but keyusages is empty. syntax
error 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 encryption key pair. see the complete code on github. let keypair = window.crypto.sub...
SubtleCrypto.importKey() - Web APIs
ey: 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: syntax
error raised when keyusages is empty but the unwrapped key is of type secret or private. type
error 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, and json web key. raw you can use this format to import or export aes or hmac secret keys, ...
SubtleCrypto.sign() - Web APIs
taining 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: invalidaccess
error 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 algorithms — rsassa-pkcs1-v1_5, rsa-pss, and ecdsa — are public-key cryptosystems that us...
SubtleCrypto.verify() - Web APIs
d 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: invalidaccess
error 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 try the working examples out on github. rsassa-pkcs1-v1_5 this code uses a public key to ver...
SubtleCrypto.wrapKey() - Web APIs
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: invalidaccess
error 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. type
error raised when trying to use an invalid format. supported algorithms all algorithms that are usable for encryption are also usable for key wrapping, as long as the key has the "wrapkey" u...
SubtleCrypto - Web APIs
u get from window.crypto. warning: this api provides a number of low-level cryptographic primitives. it's very easy to misuse them, and the pitfalls involved can be very subtle. even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts.
errors in security system design and implementation can make the security of the system completely ineffective. if you're not sure you know what you are doing, you probably shouldn't be using this api. properties this interface doesn't inherit any properties, as it has no parent interface. methods this interface doesn't inherit any methods, as it has no parent interface. subtlecrypto.encrypt()...
TextDecoder.prototype.encoding - Web APIs
dings: 'gbk', 'gb18030', and 'hz-gb-2312'. the legacy multi-byte chinese (traditional) encoding: 'big5'. the legacy multi-byte japanese encodings: 'euc-jp', 'iso-2022-jp', and 'shift-jis'. the legacy multi-byte korean encodings: 'euc-kr', and 'iso-2022-kr'. the legacy miscelleanous encodings: 'utf-16be', 'utf-16le', and 'x-user-defined'. a special encoding, 'replacement', which only emits an
error and an eof code point. it is used to prevent attacks that mismatch encodings between the client and server. it can happen with iso-2022-cn and iso-2022-cn-ext. syntax var b = decoder.decoding; specifications specification status comment encodingthe definition of 'textdecoder.encoding' in that specification. living standard initial definition. ...
TextDecoder - Web APIs
r that will generate a code point stream with the decoding method specified in parameters. properties the textdecoder interface doesn't inherit any properties. textdecoder.prototype.encodingread only is a domstring containing the name of the decoder, that is a string describing the method the textdecoder will use. textdecoder.prototype.fatalread only is a boolean indicating whether the
error mode is fatal. textdecoder.prototype.ignorebomread only is a boolean indicating whether the byte order marker is ignored. methods the textdecoder interface doesn't inherit any method. textdecoder.prototype.decode() returns a domstring containing the text decoded with the method of the specific textdecoder object. specifications specification status comment ...
TextEncoder - Web APIs
/ trim off extra weight return resarr; }; textencoder.prototype.tostring = function(){return "[object textencoder]"}; try { // object.defineproperty only works on dom prototypes in ie8 object.defineproperty(textencoder.prototype,"encoding",{ get:function(){if(textencoder.prototype.isprototypeof(this)) return"utf-8"; else throw type
error("illegal invocation");} }); } catch(e) { /*ie6-8 fallback*/ textencoder.prototype.encoding = "utf-8"; } if(typeof symbol!=="undefined")textencoder.prototype[symbol.tostringtag]="textencoder"; } source: https://github.com/anonyco/fastestsmallesttextencoderdecoder specifications specification status comment encodingthe definition of 'textencoder' in t...
Multi-touch interaction - Web APIs
= move_handler; // use same handler for touchcancel and touchend el.ontouchcancel = end_handler; el.ontouchend = end_handler; } function init() { set_handlers("target1"); set_handlers("target2"); set_handlers("target3"); set_handlers("target4"); } move/pinch/zoom handler this function provides very basic support for 2-touch horizontal move/pinch/zoom handling. the code does not include
error handling, or vertical moving. note that the threshold for pinch and zoom movement detection is application specific (and device dependent). // this is a very basic 2-touch move/pinch/zoom handler that does not include //
error handling, only handles horizontal moves, etc. function handle_pinch_zoom(ev) { if (ev.targettouches.length == 2 && ev.changedtouches.length == 2) { // check if the tw...
TrackDefault.TrackDefault() - Web APIs
equence) of domstrings specifying default kinds for the sourcebuffer to use when an initialization segment does not contain kind information for a new track. bytestreamtrackid optional a domstring specifying the id of the specific track that the sourcebuffer should apply to. if not specified, this value will be an empty string and the sourcebuffer can contain any tracks of the specified type.
errors when this constructor is invoked, the following
errors can occur:
error explanation invalidaccess
error the supplied language is not a valid language code, e.g. en-us. type
error there are values specified in the kinds array that do not apply to the specified type. example tbd ...
TrackDefaultList.TrackDefault() - Web APIs
the trackdefault() getter method of the trackdefaultlist interface allows the trackdefault objects in the list to be accessed with an array operator (i.e. [].) syntax var mytrackdefault = trackdefaultlist[index]; parameters index the index position of the trackdefault object you want to return. returns a trackdefault object.
errors no specific
errors are returned, but if the supplied index is great than or equal to trackdefaultlist.length, the operation will return undefined. example tbd. ...
TransformStream - Web APIs
ray(chunk) && chunk.every(value => typeof value === 'number')) controller.enqueue(new uint8array(chunk)) else if ('function' === typeof chunk.valueof && chunk.valueof() !== chunk) this.transform(chunk.valueof(), controller) // hack else if ('tojson' in chunk) this.transform(json.stringify(chunk), controller) break case 'symbol': controller.
error("cannot send a symbol as a chunk part") break case 'undefined': controller.
error("cannot send undefined as a chunk part") default: controller.enqueue(this.textencoder.encode(string(chunk))) break }, flush() { /* do any destructor work here */ } } class anytou8stream extends transformstream { constructor() { super({...transformcontent, textenc...
ULongRange - Web APIs
l. properties max a numeric value in the range of signed 32-bit integers, specifying the largest permissible value of the property it describes. min a numeric value in the range of signed 32-bit integers, specifying the smallest permissible value of the property it describes. the specified min and/or and max values are required. if no match can be found that is within the given range, an
error will occur. specifications specification status comment media capture and streamsthe definition of 'ulongrange' in that specification. candidate recommendation initial definition ...
URL API - Web APIs
//mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news. you can also look up the values of individual parameters with the urlsearchparams object's get() method: let addr = new url("https://mysite.com/login?user=someguy&page=news"); try { loginuser(addr.searchparams.get("user")); gotopage(addr.searchparams.get("page")); } catch(err) { show
errormessage(err); } for example, in the above snippet, the username and target page are taken from the query and passed to appropriate functions that are used by the site's code to log in and route the user to their desired destination within the site. other functions within urlsearchparams let you change the value of keys, add and delete keys and their values, and even sort the list of parameters.
USBEndpoint - Web APIs
irection returns the direction in which this endpoint transfers data, one of: "in" - data is transferred from device to host. "out" - data is transferred from host to device. usbendpoint.type returns the type of this endpoint, one of: "bulk" - provides reliable data transfer for large payloads. data sent through a bulk endpoint is guaranteed to be delivered or generate an
error but may be preempted by other data traffic. "interrupt" - provides reliable data transfer for small payloads. data sent through an interrupt endpoint is guaranteed to be delivered or generate an
error and is also given dedicated bus time for transmission. "isochronous" - provides unreliable data transfer for payloads that must be delivered periodically. they are given dedicated bus ...
USBInTransferResult - Web APIs
sferresult() creates a new usbintransferresult object with the provided status and data fields. properties usbintransferresult.dataread only returns a dataview object containing the data received from the usb device, if any. usbintransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an
error by generating a stall condition on the endpoint. a stall on the control endpoint does not need to be cleared. a stall on a bulk or interrupt endpoint must be cleared by calling clearhalt() before transferin() can be called again. "babble" - the device responded with more data than was expected. specifications specification status comment webusbthe definition of 'u...
USBIsochronousInTransferPacket - Web APIs
th the provided status and data fields. properties usbisochronousintransferpacket.dataread only read only returns a dataview object containing the data received from the usb device in this packet, if any. usbisochronousintransferpacket.statusread only read only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an
error by generating a stall condition on the endpoint. a stall on an isochronous endpoint does not need to be cleared. "babble" - the device responded with more data than was expected. specifications specification status comment webusbthe definition of 'usbisochronousintransferpacket' in that specification. draft initial definition. ...
USBIsochronousOutTransferPacket - Web APIs
outtransferpacket object with the provided status and byteswritten fields. properties usbisochronousouttransferpacket.byteswrittenread only returns the number of bytes from the packet that were sent to the device. usbisochronousouttransferpacket.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an
error by generating a stall condition on the endpoint. a stall on an isochronous endpoint does not need to be cleared. specifications specification status comment webusbthe definition of 'usbisochronousouttransferpacket' in that specification. draft initial definition. ...
USBOutTransferResult - Web APIs
es a new usbouttransferresult object with the provided status and byteswritten fields. properties usbouttransferresult.byteswrittenread only returns the number of bytes from the transfer request that were sent to the device. usbouttransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an
error by generating a stall condition on the endpoint. a stall on a bulk or interrupt endpoint must be cleared by calling clearhalt() before transferout() can be called again. specifications specification status comment webusbthe definition of 'usbouttransferresult' in that specification. draft initial definition. ...
ValidityState.typeMismatch - Web APIs
put type="url" value="example.com"/> </label> </p> input:invalid { border: red solid 3px; } the above each produce a typemismatch because the email address is just a domain and the url has no protocol the typemismatch occurs when there is a disconnect between the value expected via the type attribute and the data that is actually present. the typemismatch is only one of the many possible
errors and is only relevant for the email and url types. when the value provided doesn't match the expected value based on the type for other input types, you get different
errors. for example, if the number input value is not a floating point number, the badinput is true. if the email is required but is empty, the valuemissing will be true. specifications specification status comment ...
ValidityState - Web APIs
ls 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. custom
error read only a boolean indicating whether the element's custom validity message has been set to a non-empty string by calling the element's setcustomvalidity() method. patternmismatch read only a boolean that is true if the value does not match the specified pattern, and false if it does match. if true, the element matches the :invalid css pseudo-class. rangeoverflow read only a boolean that...
WEBGL_lose_context.restoreContext() - Web APIs
the webgl_lose_context.restorecontext() method is part of the webgl api and allows you to simulate restoring the context of a webglrenderingcontext object. syntax gl.getextension('webgl_lose_context').restorecontext();
errors thrown invalid_operation if the context was not lost. examples with this method, you can simulate the webglcontextrestored event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').restorecontext(); specifications specification status comment webgl_lose_contextthe definition of 'webgl_lose_context.losecontext' in that specification. recommendation initial definition. ...
WakeLock.request() - Web APIs
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 notallowed
error 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 in a try...catch stat...
WebGL2RenderingContext.clientWaitSync() - Web APIs
return value a glenum indicating the sync object's status. gl.already_signaled: indicates that the sync object was signaled when this method was called. gl.timeout_expired: indicates that the timeout time passed and that the sync object did not become signaled. gl.condition_satisfied: indicates that the sync object was signaled before the timeout expired. gl.wait_failed: indicates that an
error occurred during the execution. examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); var status = gl.clientwaitsync(sync, 0, 0); specifications specification status comment webgl 2.0the definition of 'clientwaitsync' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glclientwaitsync' in th...
WebGL2RenderingContext.drawBuffers() - Web APIs
. 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 that specification. standard man page of the (similar) opengl api. ...
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
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 webgl 2.0the definition of 'drawelementsinstanced' in that sp...
WebGL2RenderingContext.drawRangeElements() - Web APIs
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.0the definition of 'drawrangeelements' in that specification. editor's...
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
the uniform block. gl.uniform_block_referenced_by_vertex_shader: returns a glboolean indicating whether the uniform block is referenced by the vertex shader. gl.uniform_block_referenced_by_fragment_shader: returns a glboolean indicating whether the uniform block is referenced by the fragment shader. return value depends on which information is requested using the pname parameter. if an
error occurs, null is returned. examples var blocksize = gl.getactiveuniformblockparameter(program, blockindex, gl.uniform_block_data_size); specifications specification status comment webgl 2.0the definition of 'getactiveuniformblockparameter' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition...
WebGL2RenderingContext.getBufferSubData() - Web APIs
ansfer 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.array_buffer, buffer); gl.bu...
WebGLContextEvent.statusMessage - Web APIs
the read-only webglcontextevent.statusmessage property contains additional event status information, or is an empty string if no additional information is available. examples the statusmessage property can contain a platform dependent string with details of an event. this can occur, for example, if the webglcontextcreation
error event is fired. var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextcreation
error', function(e) { console.log('webgl context creation failed:' + e.statusmessage || 'unknown
error'); }, false); specifications specification status comment webgl 1.0the definition of 'webglcontextevent.statusmessage' in that specification. recommendation initial definit...
WebGLProgram - Web APIs
configuration options, and finally draw something to the screen. // use the program gl.useprogram(program); // bind existing attribute data gl.bindbuffer(gl.array_buffer, buffer); gl.enablevertexattribarray(attributelocation); gl.vertexattribpointer(attributelocation, 3, gl.float, false, 0, 0); // draw a single triangle gl.drawarrays(gl.triangles, 0, 3); deleting the program if there is an
error linking the program or you wish to delete an existing program, then it is as simple as running webglrenderingcontext.deleteprogram(). this frees the memory of the linked program. gl.deleteprogram(program); specifications specification status comment webgl 1.0the definition of 'webglprogram' in that specification. recommendation initial definition. ...
WebGLRenderingContext.activeTexture() - Web APIs
ure 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_image_units constant. it is, per specification, at least 8. gl.getparameter(gl.max_...
WebGLRenderingContext.bindBuffer() - Web APIs
_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. examples binding a buffer to a target var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.creat...
WebGLRenderingContext.bindFramebuffer() - Web APIs
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, query the framebuffer_bindin...
WebGLRenderingContext.bindRenderbuffer() - Web APIs
derbuffer 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. gl.getparameter(gl.render...
WebGLRenderingContext.bindTexture() - Web APIs
ble 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.texture_binding_2d or gl.tex...
WebGLRenderingContext.blendEquation() - Web APIs
n_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.func_subtract, gl.func_reverse_subtract, or if the ext_blend_minmax is en...
WebGLRenderingContext.blendEquationSeparate() - Web APIs
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_minmax is enabled: ext.min_ext or ext.max_ext. gl.getparameter(gl.blend_equat...
WebGLRenderingContext.blendFunc() - Web APIs
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) = (sourcecolor * sfactor) + (destinationcolor * dfactor). the rbga values are between 0 and 1. ...
WebGLRenderingContext.blendFuncSeparate() - Web APIs
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 factors can be described like this (all rgba values are between 0 and 1): color(rgb) = (sourcecolor * srcrgb...
WebGLRenderingContext.bufferData() - Web APIs
ommands. 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(); gl.bindbuffer(gl.array_buffe...
WebGLRenderingContext.bufferSubData() - Web APIs
cifying 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.array_buffer, 1024, gl.stati...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
er 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. return value a glenum indicating the completeness status of the framebuffer or 0 if an
error occurs. possible enum return values: gl.framebuffer_complete: the framebuffer is ready to display. gl.framebuffer_incomplete_attachment: the attachment types are mismatched or not all framebuffer attachment points are framebuffer attachment complete. gl.framebuffer_incomplete_missing_attachment: there is no attachment. gl.framebuffer_incomplete_dimensions: height and width of the attachment...
WebGLRenderingContext.clear() - Web APIs
e 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.getparameter(gl.depth_clear_value); gl.getparameter(gl.stencil_clear_value); specific...
WebGLRenderingContext.drawArrays() - Web APIs
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. recommendation initial definition. opengl es 2.0the de...
WebGLRenderingContext.drawElements() - Web APIs
e 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 definition of 'drawelements' in that specification. recommendation in...
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
access the attribute, including vertexattribpointer(), vertexattrib*(), and getvertexattrib(). syntax void gl.enablevertexattribarray(index); parameters index a gluint specifying the index number that uniquely identifies the vertex attribute to enable. if you know the name of the attribute but not its index, you can get the index by calling getattriblocation(). return value undefined.
errors to check for
errors after calling enablevertexattribarray(), call get
error(). webglrenderingcontext.invalid_value the specified index is invalid; that is, it's greater than or equal to the maximum number of entries permitted in the context's vertex attribute list, as indicated by the value of webglrenderingcontext.max_vertex_attribs. example this code — a snippet taken from the full ex...
WebGLRenderingContext.framebufferRenderbuffer() - Web APIs
13_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); specifications specificatio...
WebGLRenderingContext.framebufferTexture2D() - Web APIs
ge 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.framebuffer, gl.color_attachmen...
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
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 comment webgl 1.0the defi...
WebGLRenderingContext.getShaderInfoLog() - Web APIs
on about the last compile operation. when a webglshader object is initially created, its information log will be a string of length 0. examples checking compilation messages /* load shader source code. */ gl.shadersource(shader, shadercode); /* compile shader source code. */ gl.compileshader(shader); var message = gl.getshaderinfolog(shader); if (message.length > 0) { /* message may be an
error or a warning */ throw message; } specifications specification status comment webgl 1.0the definition of 'getshaderinfolog' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgetshaderinfolog' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
ed shader numeric 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_sha...
WebGLRenderingContext.getTexParameter() - Web APIs
etail value any float values. gl.texture_min_lod glfloat texture minimum level-of-detail value any float values. gl.texture_wrap_r glenum wrapping function for texture coordinate r gl.repeat (default value), gl.clamp_to_edge, gl.mirrored_repeat. return value returns the requested texture information (as specified with pname). if an
error occurs, null is returned. examples gl.gettexparameter(gl.texture_2d, gl.texture_mag_filter); specifications specification status comment webgl 1.0the definition of 'gettexparameter' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glgettexparameter' in that specification. standard man page of the ...
WebGLRenderingContext.getUniformLocation() - Web APIs
is returned instead. the webgluniformlocation is an opaque value used to uniquely identify the location in the gpu's memory at which the uniform variable is located. with this value in hand, you can call other webgl methods to access the value of the uniform variable. the webgluniformlocation type is compatible with the glint type when specifying the index or location of a uniform attribute.
errors the following
errors may occur; to check for
errors after getuniformlocation() returns, call get
error(). gl_invalid_value the program parameter is not a value or object generated by webgl. gl_invalid_operation the program parameter doesn't correspond to a glsl program generated by webgl, or the specified program hasn't been linked successfully. example in this example, taken from the a...
WebGLRenderingContext.isContextLost() - Web APIs
heir graphics driver on an operating system that allows graphics drivers to be updated without restarting the system. examples for example, when checking for program linking success, you could also check if the context is not lost: gl.linkprogram(program); if (!gl.getprogramparameter(program, gl.link_status) && !gl.iscontextlost()) { var info = gl.getprograminfolog(program); console.log('
error linking program:\n' + info); } specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.iscontextlost' in that specification. recommendation initial definition. ...
WebGLRenderingContext.linkProgram() - Web APIs
gl.linkprogram(program); parameters program the webglprogram to link. return value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw new
error('could not compile webgl program. \n\n' + info); } specifications specification status comment webgl 1.0the definition of 'linkprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gllinkprogram' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.scissor() - Web APIs
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 test again gl.disable(gl.scissor_test); to get the current scissor box ...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
ssumed 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 shader (e.g. uvec4 or ivec4, ...
WebGLRenderingContext.viewport() - Web APIs
corner of the viewport origin. default value: 0. y a glint specifying the vertical coordinate for the lower left corner of the viewport origin. default value: 0. width a non-negative glsizei specifying the width of the viewport. default value: width of the canvas. height a non-negative glsizei specifying the height of the viewport. default value: height of the canvas. return value none.
errors thrown if either width or height is a negative value, a gl.invalid_value
error is thrown. examples when you first create a webgl context, the size of the viewport will match the size of the canvas. however, if you resize the canvas, you will need to tell the webgl context a new viewport setting. in this situation, you can use gl.viewport. gl.viewport(0, 0, canvas.width, canvas.height); the...
WebGLRenderingContext - Web APIs
ringcontext.disable() disables specific webgl capabilities for this context. webglrenderingcontext.enable() enables specific webgl capabilities for this context. webglrenderingcontext.frontface() specifies whether polygons are front- or back-facing by setting a winding orientation. webglrenderingcontext.getparameter() returns a value for the passed parameter name. webglrenderingcontext.get
error() returns
error information. webglrenderingcontext.hint() specifies hints for certain behaviors. the interpretation of these hints depend on the implementation. webglrenderingcontext.isenabled() tests whether a specific webgl capability is enabled or not for this context. webglrenderingcontext.linewidth() sets the line width of rasterized lines. webglrenderingcontext.pixelstorei() specif...
Hello GLSL - Web APIs
rogram(program); gl.detachshader(program, vertexshader); gl.detachshader(program, fragmentshader); gl.deleteshader(vertexshader); gl.deleteshader(fragmentshader); if (!gl.getprogramparameter(program, gl.link_status)) { var linkerrlog = gl.getprograminfolog(program); cleanup(); document.queryselector("p").innerhtml = "shader program did not link successfully. ...
Hello vertex attributes - Web APIs
rogram(program); gl.detachshader(program, vertexshader); gl.detachshader(program, fragmentshader); gl.deleteshader(vertexshader); gl.deleteshader(fragmentshader); if (!gl.getprogramparameter(program, gl.link_status)) { var linkerrlog = gl.getprograminfolog(program); cleanup(); document.queryselector("p").innerhtml = "shader program did not link successfully. ...
Textures from code - Web APIs
rogram(program); gl.detachshader(program, vertexshader); gl.detachshader(program, fragmentshader); gl.deleteshader(vertexshader); gl.deleteshader(fragmentshader); if (!gl.getprogramparameter(program, gl.link_status)) { var linkerrlog = gl.getprograminfolog(program); cleanup(); document.queryselector("p").innerhtml = "shader program did not link successfully. ...
Adding 2D content to a WebGL context - Web APIs
hader of the given type, uploads the source and // compiles it. // function loadshader(gl, type, source) { const shader = gl.createshader(type); // send the source to the shader object gl.shadersource(shader, source); // compile the shader program gl.compileshader(shader); // see if it compiled successfully if (!gl.getshaderparameter(shader, gl.compile_status)) { alert('an
error occurred compiling the shaders: ' + gl.getshaderinfolog(shader)); gl.deleteshader(shader); return null; } return shader; } the loadshader() function takes as input the webgl context, the shader type, and the source code, then creates and compiles the shader as follows: a new shader is created by calling gl.createshader(). the shader's source code is sent to the shader by callin...
Animating textures in WebGL - Web APIs
, true); video.src = url; video.play(); function checkready() { if (playing && timeupdate) { copyvideo = true; } } return video; } first we create a video element. we set it to autoplay, mute the sound, and loop the video. we then set up two events to make sure the video is playing and the time has been updated. we need both of these checks because it will produce an
error if you upload a video to webgl that has no data available yet. checking for both of these events guarantees there is data available and it's safe to start uploading video to a webgl texture. in the code above, we confirm whether we got both of those events; if so, we set a global variable, copyvideo, to true to indicate that it's safe to start copying the video to a texture. and finally, we set ...
WebGL: 2D and 3D graphics for the web - Web APIs
it is based on opengl es 3.0 and new features include: 3d textures, sampler objects, uniform buffer objects, sync objects, query objects, transform feedback objects, promoted extensions that are now core to webgl 2: vertex arr...
WebRTC connectivity - Web APIs
ad by watching for the icegatheringstate to change to complete, by watching for the icegatheringstatechange event. when things go wrong during negotiation, there will be times when things just don't work out. for example, when renegotiating a connection—for example, to adapt to changing hardware or network configurations—it's possible that negotiation could reach a dead end, or some form of
error might occur that prevents negotiation at all. there may be permissions issues or other problems as well, for that matter. ice rollbacks when renegotiating a connection that's already active and a situation arises in which the negotiation fails, you don't really want to kill the already-running call. after all, you were most likely just trying to upgrade or downgrade the connection, or to otherw...
Lifetime of a WebRTC session - Web APIs
device, and a response then output by that device to be returned on foot, and so forth, until the webrtc peer connection is open. it'd be very high latency but it could be done. information exchanged during signaling there are three basic types of information that need to be exchanged during signaling: control messages used to set up, open, and close the communication channel, and to handle
errors. information needed in order to set up the connection: the ip addressing and port information needed for the peers to be able to talk to one another. media capability negotiation: what codecs and media data formats can the peers understand? these need to be agreed upon before the webrtc session can begin. only once signaling has been successfully completed can the true process of opening the...
Using WebRTC data channels - Web APIs
r agents share the same underlying library for handling stream control transmission protocol (sctp) data, there can still be variations due to how the library is used. for example, both firefox and google chrome use the usrsctp library to implement sctp, but there are still situations in which data transfer on an rtcdatachannel can fail due to differences in how they call the library and react to
errors it returns. when two users running firefox are communicating on a data channel, the message size limit is much larger than when firefox and chrome are communicating because firefox implements a now deprecated technique for sending large messages in multiple sctp messages, which chrome does not. chrome will instead see a series of messages that it believes are complete, and will deliver them to ...
WebSocket() - Web APIs
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. syntax
error the url is invalid. specifications specification status comment html living standardthe definition of 'the websocket constructor' in that specification. living standard ...
Inputs and input sources - Web APIs
your 3d space and then triggers a select action, the following events are sent to the active xrsession: a selectstart event, indicating that the user has performed the activity that begins the primary action. this may be a gesture, depressing a button, or the like. if the primary action ends successfully (for example, due to the user releasing the button or trigger), rather than because of an
error, the select event is sent. after the select event is sent or if the controller on which the action is being performed is disconnected or otherwise becomes unavailable, the selectend event is sent. generally speaking, the selectstart and selectend events tell you when you might want to display something to the user indicating that the primary action is going on. this might be drawing a controll...
WebXR permissions and security - Web APIs
red 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 security
error 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 requestsession() call isn't comi...
Using the Web Animations API - Web APIs
ct, separated 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 notsupported
error 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: infi...
Background audio processing using AudioWorklet - Web APIs
; } note that when determining the number of sources to process and send through to the corresponding outputs, we use math.min() to ensure that we only process as many channels as we have room for in the output list. the same check is performed when determining how many channels to process in the current input; we only process as many as there are room for in the destination output. this avoids
errors due to overrunning these arrays. mixing inputs many nodes perform mixing operations, where the inputs are combined in some way into a single output. this is demonstrated in the following example. process(inputlist, outputlist, parameters) { const sourcelimit = math.min(inputlist.length, outputlist.length); for (let inputnum = 0; inputnum < sourcelimit; inputnum++) { let input = inpu...
Web Authentication API - Web APIs
google demo website and its source code. webauthn.org and its client source code and server source code specifications specification status comment web authentication: an api for accessing public key credentials level 1 recommendation initial definition. ...
Web Crypto API - Web APIs
cryptography. warning: the web crypto api provides a number of low-level cryptographic primitives. it's very easy to misuse them, and the pitfalls involved can be very subtle. even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts.
errors in security system design and implementation can make the security of the system completely ineffective. if you're not sure you know what you are doing, you probably shouldn't be using this api. interfaces some browsers implemented an interface called crypto without having it well defined or being cryptographically sound. in order to avoid confusion, methods and properties of this interface ...
The structured clone algorithm - Web APIs
rties 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 the default. the prototype chain is not walked or duplicated. note: native
error types can be cloned in chrome, and firefox is working on it. supported types object type notes all primitive types however, not symbols. boolean objects string objects date regexp lastindex is not preserved. blob file filelist arraybuffer arraybufferview ...
Web Workers API - Web APIs
and background sync apis. chrome workers are a firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to js-ctypes in your worker. see chromeworker for more details. audio workers provide the ability for direct scripted audio processing to be done inside a web worker context. note: as per the web workers spec, worker
error events should not bubble (see bug 1188141. this has been implemented in firefox 42. web worker interfaces abstractworker abstracts properties and methods common to all kind of workers (i.e. worker or sharedworker). worker represents a running worker thread, allowing you to pass messages to the running worker code. workerlocation defines the absolute location of the script executed by th...
Window.captureEvents() - Web APIs
the window.captureevents() method registers the window to capture all events of the specified type. syntax window.captureevents(eventtype) eventtype is a combination of the following values: event.abort, event.blur, event.click, event.change, event.dblclick, event.dragddrop, event.
error, event.focus, event.keydown, event.keypress, event.keyup, event.load, event.mousedown, event.mousemove, event.mouseout, event.mouseover, event.mouseup, event.move, event.reset, event.resize, event.select, event.submit, event.unload. example <!doctype html> <html lang="en"> <head> <!-- ... --> <script> function reg() { window.captureevents(event.click); window.onclick = page_click; } function page_click() { alert('page click event detected!'); } </script> </head> <body onload="reg();"> <p>click ...
Window.close() - Web APIs
note also that close() has no effect when called on window objects returned by htmliframeelement.contentwindow. ...
Window.console - Web APIs
the window.console property returns a reference to the console object, which provides methods for logging information to the browser's console. these methods are intended for debugging purposes only and should not be relied on for presenting information to end users. examples logging to console the first example logs text to the console. console.log("an
error occurred while loading the content"); the next example logs an object to the console, with the object's fields expandable using disclosure widgets: console.dir(someobject); see usage in console for more thorough examples. specifications specification status comment console api living standard initial definition. currently there are many implementation differences among browsers, but work...
Window.getSelection() - Web APIs
assed to the function. this can make the object appear to be a string when used with other functions when it is really an object with properties and methods. in the above example, selobj.tostring() is automatically called when it is passed to window.alert(). however, attempting to use a javascript string property or method such as length or substr directly on a selection object will result in an
error if it does not have that property or method and may return unexpected results if it does. to use a selection object as a string, call its tostring() method directly: var selectedtext = selobj.tostring(); selobj is a selection object. selectedtext is a string (selected text). related objects you can call document.getselection(), which works identically to window.getselection(). it is wort...
Window.localStorage - Web APIs
om 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 security
error 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 data item to it u...
Window.releaseEvents() - Web APIs
summary releases the window from trapping events of a specific type. syntax window.releaseevents(eventtype) eventtype is a combination of the following values: event.abort, event.blur, event.click, event.change, event.dblclick, event.dragddrop, event.
error, event.focus, event.keydown, event.keypress, event.keyup, event.load, event.mousedown, event.mousemove, event.mouseout, event.mouseover, event.mouseup, event.move, event.reset, event.resize, event.select, event.submit, event.unload. example window.releaseevents(event.keypress) notes note that you can pass a list of events to this method using the following syntax: window.releaseevents(event.keypress | event.keydown | event.keyup). see also window.captureevents ( ). specification this is not part of any specification. brows...
Window.sessionStorage - Web APIs
e 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 security
error 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 data to it with s...
Window: unload event - Web APIs
examples <!doctype html> <html> <head> <title>parent frame</title> <script> window.addeventlistener('beforeunload', function(event) { console.log('i am the 1st one.'); }); window.a...
WindowEventHandlers - Web APIs
handlers.onhashchange is an eventhandler representing the code to be called when the hashchange event is raised. windoweventhandlers.onlanguagechange is an eventhandler representing the code to be called when the languagechange event is raised. windoweventhandlers.onmessage is an eventhandler representing the code to be called when the message event is raised. windoweventhandlers.onmessage
error is an eventhandler representing the code to be called when the message
error event is raised. windoweventhandlers.onoffline is an eventhandler representing the code to be called when the offline event is raised. windoweventhandlers.ononline is an eventhandler representing the code to be called when the online event is raised. windoweventhandlers.onpagehide is an eventhandler representing th...
WindowOrWorkerGlobalScope.atob() - Web APIs
l 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 domexception (name: invalidcharacter
error) 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 specification status comment ...
Worker() - Web APIs
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 security
error 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 network
error is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntax
error is raised if aurl cannot be parsed. examples the following code snippet shows creation of a worker object using the worker() co...
Worker.prototype.postMessage() - Web APIs
ge method. syntax worker.postmessage(message, [transfer]); parameters message the object to deliver to the worker; this will be in the data field in the event delivered to the dedicatedworkerglobalscope.onmessage handler. this may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references. if the message parameter is not provided, a type
error will be thrown. if the data to be passed to the worker is unimportant, null or undefined can be passed explicitly. transfer optional an optional array of transferable objects to transfer ownership of. if the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to. transferable objects are inst...
WorkerGlobalScope.importScripts() - Web APIs
portscripts() 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 network
error 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() being ...
WorkerGlobalScope - Web APIs
sly access capabilities of indexed databases; returns an idbfactory object. windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false). windoworworkerglobalscope.origin read only returns the global object's origin, serialized as a string. (this does not yet appear to be implemented in any browser.) events
error fired when an
error occured. also available via the workerglobalscope.on
error property. offline fired when the browser has lost access to the network and the value of navigator.online switched to false. also available via the workerglobalscope.onoffline property. online fired when the browser has gained access to the network and the value of navigator.online switched to true. also availab...
Worklet.addModule() - Web APIs
s (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. abort
error the specified script is invalid or could not be loaded. syntax
error the specified moduleurl is invalid. examples audioworklet example const audioctx = new audiocontext(); const audioworklet = audioctx.audioworklet; await audioworklet.addmodule('modules/bypassfilter.js', { credentials: 'omit', }); paintworklet example css.paintworklet.addmodule(...
WritableStream.abort() - Web APIs
the abort() method of the writablestream interface aborts 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 type
error 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(); speci...
WritableStreamDefaultController - Web APIs
represents a controller allowing control of a writablestream's state. when constructing a writablestream, the underlying sink is given a corresponding writablestreamdefaultcontroller instance to manipulate. constructor none. writablestreamdefaultcontroller instances are created automatically during writablestream construction. properties none. methods writablestreamdefaultcontroller.
error() causes any future interactions with the associated stream to
error. examples const writablestream = new writablestream({ start(controller) { // do stuff with controller //
error stream if necessary controller.
error('my stream is broken'); }, write(chunk, controller) { ... }, close(controller) { ... }, abort(err) { ... } }); specifications ...
WritableStreamDefaultWriter.abort() - Web APIs
the abort() method of the writablestreamdefaultwriter interface aborts 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. if the writer 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 type
error the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new w...
WritableStreamDefaultWriter.closed - Web APIs
syntax var closed = writablestreamdefaultwriter.closed; value a promise. examples const writablestream = new writablestream({ start(controller) { }, write(chunk, controller) { ... }, close(controller) { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); .. ...
WritableStreamDefaultWriter.desiredSize - Web APIs
the desiredsize read-only property of the writablestreamdefaultwriter 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 type
error 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; ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
the xmlhttprequest method getallresponseheaders() returns all the response headers, separated by crlf, as a string, or returns null if no response has been received. if a network
error happened, an empty string is returned. note: for multipart requests, this returns the headers from the current part of the request, not from the original channel. syntax var headers = xmlhttprequest.getallresponseheaders(); parameters none. return value a bytestring representing all of the response's headers (except those whose field name is set-cookie or set-cookie2) separated by crlf, or null if no response has been received. if a network
error happened, an empty string is returned. an example of what a raw header string looks like: date: fri, 08 dec 2017 21:04:30 gmt\r\n content-encoding: gzip\r\n ...
XMLHttpRequest.multipart - Web APIs
ge in the future. obsolete since gecko 22 this gecko-only feature was removed in firefox/gecko 22. please use server-sent events, web sockets, or responsetext from progress events instead. this boolean indicates if the response is expected to be a stream of possibly multiple xml documents. if set to true, the content type of the initial response must be multipart/x-mixed-replace or an
error will occur. all requests must be asynchronous. this enables support for server push; for each xml document that's written to this request, a new xml dom document is created and the onload handler is called between documents. note: when this is set, the onload handler and other event handlers are not reset after the first xmldocument is loaded, and the onload handler is called after each part o...
XMLHttpRequest.overrideMimeType() - Web APIs
erver. if the server doesn't specify a type, xmlhttprequest assumes "text/xml". return value undefined. example this example specifies a mime type of "text/plain", overriding the server's stated type for the data being received. note: if the server doesn't provide a content-type header, xmlhttprequest assumes that the mime type is "text/xml". if the content isn't valid xml, an "xml parsing
error: not well-formed"
error occurs. you can avoid this by calling overridemimetype() to specify a different type. // interpret the received data as plain text req = new xmlhttprequest(); req.overridemimetype("text/plain"); req.addeventlistener("load", callback, false); req.open("get", url); req.send(); specifications specification status comment xmlhttprequestthe definit...
XMLHttpRequest.responseText - Web APIs
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 invalidstate
error 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 () { if (xhr.readysta...
XMLHttpRequest.responseType - Web APIs
t 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 invalidaccess
error 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 designed in part to he...
XMLHttpRequest.responseXML - Web APIs
n'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 invalidstate
error 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.status === 200) { con...
XMLHttpRequest.send() - Web APIs
pec 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 invalidstate
error send() has already been invoked for the request, and/or the request is complete. network
error 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 here. }; xhr.send(null); // xhr.send('string'); // xhr.send(new blo...
XMLHttpRequest.status - Web APIs
the read-only xmlhttprequest.status property returns the numerical http status code of the xmlhttprequest's response. before the request completes, the value of status is 0. browsers also report a status of 0 in case of xmlhttprequest
errors. example var xhr = new xmlhttprequest(); console.log('unsent: ', xhr.status); xhr.open('get', '/server'); console.log('opened: ', xhr.status); xhr.onprogress = function () { console.log('loading: ', xhr.status); }; xhr.onload = function () { console.log('done: ', xhr.status); }; xhr.send(); /** * outputs the following: * * unsent: 0 * opened: 0 * loading: 200 * done: 200 */ specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest: timeout event - Web APIs
the timeout event is fired when progression is terminated due to preset time expiring. bubbles no cancelable no interface progressevent event handler property ontimeout examples const client = new xmlhttprequest(); client.open('get', 'http://www.example.org/example.txt'); client.ontimeout = () => { console.
error('timeout!!') }; client.send(); you could also set up the event handler using the addeventlistener() method: client.addeventlistener('timeout', () => { console.
error("timeout!!"); }); specifications specification status comment xmlhttprequestthe definition of 'timeout event' in that specification. living standard ...
XMLHttpRequestEventTarget - Web APIs
ly="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">xmlhttprequesteventtarget</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties xmlhttprequesteventtarget.onabort contains the function to call when a request is aborted and the abort event is received by this object. xmlhttprequesteventtarget.on
error contains the function to call when a request encounters an
error and the
error event is received by this object. xmlhttprequesteventtarget.onload contains the function to call when an http request returns after successfully fetching content and the load event is received by this object. xmlhttprequesteventtarget.onloadstart contains the function that gets called when the http request first b...
XPathEvaluator.createExpression() - Web APIs
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 xpathexception of type invalid_expression_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a domexception of type namespace_
error is raised. example the following example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselect...
XPathEvaluator.evaluate() - Web APIs
expression is not legal according to the rules of the xpathevaluator, an xpathexception of type invalid_expression_err is raised. type_err in case result cannot be converted to the specified type, an xpathexception of type type_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a domexception 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 domexception of type wrong_document_err is raised. not_supported_err if the provided context node is not a type permitted as an xpath context node or the request type is not permitted by the xpathevaluator, a domexception of type not_supported_err is raised. example t...
XPathException.code - Web APIs
the code read-only property of the xpathexception 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 'xpathexception' in that specification. recommendation initial definition ...
XPathException - Web APIs
in the dom xpath api the xpathexception interface represents exception conditions that can be encountered while performing xpath operations. properties xpathexception.code read only returns a short that contains one of the
error code constants. 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. specifications specification status comment document object model (dom) level 3 xpath specificationth...
XPathExpression.evaluate() - Web APIs
expression is not legal according to the rules of the xpathevaluator, an xpathexception of type invalid_expression_err is raised. type_err in case result cannot be converted to the specified type, an xpathexception of type type_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a domexception 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 domexception of type wrong_document_err is raised. not_supported_err if the provided context node is not a type permitted as an xpath context node or the request type is not permitted by the xpathevaluator, a domexception of type not_supported_err is raised. example t...
XRBoundedReferenceSpace.boundsGeometry - Web APIs
aces with uneven floor levels using xrboundedreferencespace. the ground is always at y = 0. it's important that your content not be designed to require the user to exit the bounds specified by boundsgeometry. however, if the user's surroundings permit them to move in such a way as to exit the defined bounds, your content must be able to gracefully handle the situation, which is not considered an
error condition. although some samples render a mesh or other shape to display the bounds to the user, in a real-world application, you shouldn't do this. the browser, however, should provide appropriate warnings to the user about any risks (such as the risk that they might run into a physical wall if they keep moving). specifications specification status comment webxr device...
XRFrame.getViewerPose() - Web APIs
een 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 invalidstate
error a domexception indicating that getviewerpose() was not called within the context of a callback to a session's xrsession.requestanimationframe(). examples in this callback function for requestanimationframe(), the xrviewerpose describing the viewer's viewpoint on the world is obtained by calling getviewerpose() on the xrframe passed into the callback. viewerpose = xrframe.getviewerpose(xrrefe...
XRPermissionDescriptor - Web APIs
if permission is conditional based on prompting, we call a function promptandsetupxr() that would handle asking for permission before enabling and starting up the environment. and for any other returned state—which is almost certainly denied, which is the only other option as of this article's writing—we do nothing, since we can't use webxr. if the permission request promise is rejected, the
error is handled (currently by just dumping it to the console using domxref("console.log()")}}). if the permissions api isn't available at all, this example simply assumes that webxr will report an appropriate
error if permission isn't available, and tries to start up the webxr session using the same setupxr() function called by the granted case. let xrpermissiondesc = { name: "xr", mode: "immers...
XRPose.emulatedPosition - Web APIs
sition is computed as an offset from another object (such as by basing it off the model representing the user's body), then this value is true. this information is important because devices whose position is emulated are prone to their offset drifting relative to the real world space over time. this is because emulating a position based on accelerometer inputs and models tends to introduce minor
errors which accumulate over time. specifications specification status comment webxr device apithe definition of 'xrpose.emulatedposition' in that specification. working draft initial definition. ...
XRReferenceSpace: reset event - Web APIs
system). the tracking system has temporarily lost the user, then regained them, but not until after they had moved enough to leave the immediate vicinity of the last-known position. primarily an issue for unbounded reference spaces. the user is in an unbounded reference space and has moved far enough from the starting position (the reference space's origin) that floating-point or other forms of
error or drift are problematic. the coordinate system is thus reset with its new origin at or near the user's current position. the webxr infrastructure or hardware drivers detected that the device had temporarily lost tracking, causing the hardware and software to be out of sync on position and orientation. note: a reset event will not occur if the reference space is able to regain tracking of its...
XRRigidTransform() - Web APIs
fault 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 type
error 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("local-floor") .t...
XRSession.requestReferenceSpace() - Web APIs
or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace return value a promise that resolves with an xrreferencespace object. exceptions rather than throwing true exceptions, requestreferencespace() rejects the returned promise with a domexception whose name is found in the list below: notsupported
error the requested reference space is not supported. specifications specification status comment webxr device apithe definition of 'requestreferencespace()' in that specification. working draft initial definition. ...
XRSession.updateRenderState() - Web APIs
count 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. invalidstate
error this may occur for one of the following reasons: the xrsession has already ended, so you cannot change its render state. the baselayer specified in newstate was created by an xrsession other than the one on which updaterenderstate() was called. the inlineverticalfieldofview property was set, but the session is immersive and therefore does not allow this property to be used. exam...
XRSession - Web APIs
ed to identify the request for the purposes of canceling the callback using cancelanimationframe(). this method is comparable to the window.requestanimationframe() method. requestreferencespace() requests that a new xrreferencespace of the specified type be created. returns a promise which resolves with the xrreferencespace or xrboundedreferencespace which was requested, or throws a notsupported
error if the requested space type isn't supported by the device. updaterenderstate() updates the properties of the session's render state to match the values specified in the specified xrrenderstateinit dictionary. any properties not included in the given dictionary are left unchanged from their current values. events the following events are delivered to xrsession objects. event desc...
XRSystem: isSessionSupported() - Web APIs
nt) or immersive-vr for a fully-immersive virtual experience. return value a promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false. exceptions rather than throwing true exceptions, issessionsupported() rejects the returned promise, passing to the rejection handler a domexception whose name is one of the following strings. security
error 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 supports vr mode by checking to see if an immersive-vr session is supported. if it is, we set up a button to read "enter xr", to call a method onbuttonclicked(), and enable the button. if no session is alr...
XRWebGLLayer.getViewport() - Web APIs
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 invalidstate
error 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 is currently being re...
XSL Transformations in Mozilla FAQ - Web APIs
se cases we have seen are bad xml or bad xslt. and rss feeds. the latter is pretty much the only issue to us, and we're sorry that we can't support it. but mixing parsing with xslt is brittle and we rather not support d-o-e than either crash or be even slower. what about document.write? just like for xhtml, document.write is not supported during xslt transformations. sadly, current builds don't
error, but just give unexpected results, like crashes (bug 202765). in most cases, there is no need to actually use it, though. if you need platform dependent code or stylesheets, just do <xsl:if test="system-property('xsl:vendor')='transformiix'"> <!-- mozilla specific markup --> </xsl:if> <xsl:if test="system-property('xsl:vendor')='microsoft'"> <!-- ie specific mar...
msGetRegionContent - Web APIs
his 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 domexception with the invalidaccess
error 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 ...
msPutPropertyEnabled - Web APIs
abled or disabled. this proprietary method is specific to internet explorer and microsoft edge. syntax var retval = style.msputpropertyenabled(propertyname, true); parameters name[in]: name of the property. (string) boolean[in]: true = enable the property. false = disable the property. return value type = hresult: if this method succeeds, it returns s_ok. otherwise, it returns an hresult
error code. see also css style declaration microsoft api extensions ...
msWriteProfilerMark - Web APIs
the mswriteprofilermark method writes a profiling event. this proprietary method is specific to internet explorer and microsoft edge. syntax window.mswriteprofilermark("start-render"); parameters bstrprofilermarkname[in] an event name. type = string. this parameter may be null. return value type: hresult. if this method succeeds, it returns s_ok. otherwise, it returns an hresult
error code. notes mswriteprofilermark enables you to inject dom based performance markers in addition to existing javascript api to learn exactly when parts of the page are being rendered, building a waterfall view for every one of our impressions showing latency per object, which can be useful for more accurately debugging real users perf issues. internet explorer 10. this method is also available ...
ARIA guides - Accessibility
accessible rich internet applications (aria) defines ways to make the web more accessible to people with disabilities. a few guidelines to follow that ensure better accessibility, like using drag and drop for placement of the widgets.
error handling in forms labeling widgets labeling composite widgets and regions managing focus in composite widgets (aria-activedescendant vs roving tabindex) using landmark roles handling dynamic updates & live regions virtual vs. non virtual mode in at products using drag & drop notifying users of non-aria screen readers fixing structure with presentation role hiding layout tables managing modal and non modal dialogs using aria with html5 how to test aria aria on mobile devices ...
Using the alertdialog role - Accessibility
close or cancel button that can be used to move focus to. additionally, alert dialogs can have other interactive controls such as text fields, tabs or checkboxes. which particular control focus should be moved to depends on the purpose of the dialog. the tab order inside the alert dialog must wrap. the difference with regular dialogs is that the alertdialog role should only used when an alert,
error, or warning occurs. in other words, when a dialog's information and controls require the user's immediate attention alertdialog should be used instead of dialog. it is up to the developer to make this distinction though. because of its urgent nature, alert dialogs must always be modal. note: this role should only be used for alert messages that have associated interactive controls. if an alert ...
Using the aria-valuemax attribute - Accessibility
value of aria-valuemax must be greater than or equal to the value of aria-valuemin. aria-valuemax is a required attribute of role slider, scrollbar and spinbutton. value string representation of a number possible effects on user agents and assistive technology if the aria-valuemax is indeterminate, or if aria-valuemin is not less than or equal to the value of aria-valuemax, this creates an
error condition that will be handled by the assistive technology. note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: the snippet below shows a simple slider with a maximum value of 10. <div role="slider" aria-valuenow="4" aria-valuemin="1" aria-valuemax="10"> ...
Using the aria-valuemin attribute - Accessibility
rties for aria-valuemax and aria-valuemin.the value of aria-valuemin must be less than or equal to the value of aria-valuemax. aria-valuemin is a required attribute of role slider, scrollbar and spinbutton. value string representation of a number possible effects on user agents and assistive technology if aria-valuemin is not less than or equal to the value of aria-valuemax, this creates an
error condition that will be handled by the assistive technology. note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: the snippet below shows a simple slider with a minimum value of 1. <div role="slider" aria-valuenow="4" aria-valuemin="1" aria-valuemax="10"> ...
Using the log role - Accessibility
description this technique demonstrates how to use the log role and describes the effect it has on browsers and assistive technology. the log role is used to identify an element that creates a live region where new information is added in a meaningful order and old information may disappear. for example, chat logs, messaging history or an
error log. in contrast to other types of live region, this role is sequentially ordered and new information is only added to the end of the log. when this role is added to an element, the browser will send out an accessible log event to assistive technology products which can then notify the user about it. by default updates contain only the changes to the live region and these are announced when the user is idle. where the user needs to hear the en...
ARIA: alert role - Accessibility
setting role="alert" is equivalent to setting aria-live="assertive" and aria-atomic="true". they don't receive focus, and therefore focus does not need to be managed and no user interaction should be required. the most important thing to know about the alert role is that it is for dynamic content. it is perfect for situations such as when a user fills out a form and javascript is used to add an
error message - the alert would immediately read out the message. it should not be used on html where the user hasn't interacted with it. for example, if a page loads with multiple visible alerts scattered throughout, none would be read because they are not dynamically triggered. examples the most basic way to trigger an alert is by adding role="alert" to an element that has display: none; by defaul...
ARIA - Accessibility
to make web content and web applications (especially those developed with javascript) more accessible to people with disabilities. it supplements html so that interactions and widgets commonly used in applications can be passed to assistive technologies when there is not otherwise a mechanism. for example, aria enables accessible navigation landmarks in html4, javascript widgets, form hints and
error messages, live content updates, and more. many of these widgets were later incorporated into html5, and developers should prefer using the correct semantic html element over using aria, if such an element exists. for instance, native elements have built-in keyboard accessibility, roles and states. however, if you choose to use aria, you are responsible for mimicking (the equivalent) browser be...
Text labels and names - Accessibility
this includes the <embed> and <object> elements. these elements are often used for graphical content, much like the <img> element. a descriptive title helps users of assisti...
@document - CSS: Cascading Style Sheets
for example, a . (period) matches any character in regular expressions. to match a literal period, you would first need to escape it using regular expression rules (to \.), then escape that string using css rules (to \\.). @document is currently only supported in firefox; if you wanted to replicate using such functionality in your own non-firefox browser, you could try using this polyfill by @an-
error94, which uses a combination of a user script, data-* attributes, and attribute selectors. note: there is a -moz-prefixed version of this property — @-moz-document. this has been limited to use only in user and ua sheets in firefox 59 in nightly and beta — an experiment designed to mitigate potential css injection attacks (see bug 1035091). formal syntax @document [ <url> | url-prefix(<st...
Border-radius generator - CSS: Cascading Style Sheets
endchild(label); this.node = node; this.topic = topic; this.checkbox = checkbox; checkbox.addeventlistener('change', function(e) { notify.call(this); }.bind(this)); buttons[topic] = this; } var getnode = function getnode(topic) { return buttons[topic].node; } var setvalue = function setvalue(topic, value) { try { buttons[topic].checkbox.checked = value; } catch(
error) { console.log(
error); } } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i = 0; i < su...
Shapes From Images - CSS: Cascading Style Sheets
te should work, however if your images are hosted on a different domain such as on a cdn you should ensure that they are sending the correct headers to enable them to be used for shapes. due to this requirement for cors compatible images, if you are previewing your file locally without using a local web server, your shape will not work. is it a cors issue? devtools can help you to identify cors
errors. in chrome the console will alert you to cors problems. in firefox if you inspect the property you will be alerted to the fact that the image could not be loaded. this should alert you to the fact that your image cannot be used as the source of a shape due to cors. setting a threshold the shape-image-threshold property enables the creation of shapes from areas which are not fully transparent. ...
CSS reference - CSS: Cascading Style Sheets
ties-list] see the index of selectors, pseudo-classes, and pseudo-elements below. the syntax for each specified value depends on the data type defined for each specified property. style rule examples strong { color: red; } div.menu-bar li:hover > ul { display: block; } for a beginner-level introduction to the syntax of selectors, see our guide on css selectors. be aware that any syntax
error in a rule definition invalidates the entire rule. invalid rules are ignored by the browser. note that css rule definitions are entirely (ascii) text-based, whereas dom-css / cssom (the rule management system) is object-based. at-rule syntax as the structure of at-rules varies widely, please see at-rule to find the syntax of the specific one you want. keyword index note: the property names in...
Tools - CSS: Cascading Style Sheets
is not really yet a useful tool, but will be!linear-gradient generatorthis tool can be used to create custom css3 linear-gradient() backgrounds. other tools css animation - stylie to check the device display information (helpful in responsive web design) - mydevice.io css menus - cssmenumaker.com a mighty, modern css linter that helps you enforce consistent conventions and avoid
errors in your stylesheets - stylelint ...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
the property color is inheritable. yes, but <p> doesn't have any parent with color property. so move on to the next step. set the value to its default initial value, i.e., black. result the paragraph color will not be blue because invalid substitution is replaced by the initial value, not by the fallback. if you had written color: 16px without any variable substitutes, then it was a syntax
error. the previous declaration will then be used. note: while a syntax
error in a css property / value pair will lead to the line being ignored, using a cascaded value, invalid substitution -- using a custom property value that is invalid -- is not ignored, leading to the value to be inherited. values in javascript to use the values of custom properties in javascript, it is just like standard pro...
attr() - CSS: Cascading Style Sheets
ng and trailing spaces are stripped. currentcolor url <url> the attribute value is parsed as a string that is used inside a css url() function. relative url are resolved relatively to the original document, not relatively to the style sheet. leading and trailing spaces are stripped. the url about:invalid that points to a non-existent document with a generic
error condition. integer <integer> the attribute value is parsed as a css <integer>. if it is not valid, that is not an integer or out of the range accepted by the css property, the default value is used. leading and trailing spaces are stripped. 0, or, if 0 is not a valid value for the property, the property's minimum value. number <number> the attr...
calc() - CSS: Cascading Style Sheets
llowed by a negative length — an invalid expression — while calc(50% - 8px) is a percentage followed by a subtraction operator and a length. likewise, calc(8px + -50%) is treated as a length followed by an addition operator and a negative percentage. the * and / operators do not require whitespace, but adding it for consistency is both allowed and recommended. division by zero results in an
error being generated by the html parser. math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified. it is permitted to nest calc() functions, in which case the inner ones are treated as simple parentheses. formal syntax calc( <c...
<color> - CSS: Cascading Style Sheets
gb syntax variations this example shows the many ways in which a single color can be created with the various rgb color syntaxes. /* these syntax variations all specify the same color: a fully opaque hot pink. */ /* hexadecimal syntax */ #f09 #f09 #ff0099 #ff0099 /* functional syntax */ rgb(255,0,153) rgb(255, 0, 153) rgb(255, 0, 153.0) rgb(100%,0%,60%) rgb(100%, 0%, 60%) rgb(100%, 0, 60%) /*
error! don't mix numbers and percentages. */ rgb(255 0 153) /* hexadecimal syntax with alpha value */ #f09f #f09f #ff0099ff #ff0099ff /* functional syntax with alpha value */ rgb(255, 0, 153, 1) rgb(255, 0, 153, 100%) /* whitespace syntax */ rgb(255 0 153 / 1) rgb(255 0 153 / 100%) /* functional syntax with floats value */ rgb(255, 0, 153.6, 1) rgb(1e2, .5e1, .5e0, +.25e2%) rgb transparency varia...
shape-outside - CSS: Cascading Style Sheets
nel of the specified <image> as defined by shape-image-threshold. note: user agents must use the potentially cors-enabled fetch method defined by the html5 specification for all urls in a shape-outside value. when fetching, user agents must use "anonymous" mode, set the referrer source to the stylesheet's url, and set the origin to the url of the containing document. if this results in network
errors such that there is no valid fallback image, the effect is as if the value none had been specified. interpolation when animating between one <basic-shape> and a second, the rules below are applied. the values in the shape functions interpolate as a simple list. the list values interpolate as <length>, <percentage>, or calc() where possible. if list values are not one of those types but are i...
WAI ARIA Live Regions/API Support - Developer guides
ns] [removals] [text]" | "all" "additions text" what types of mutations are possibly relevant? see [#events_fired_for_web_page_mutations the mutation events list] to match the type of event with this attribute's value, to determine whether the author believed the event should be presented to the user or not. aria-relevant on ancestor element container-busy "true" | "false" | "
error" "false" the current changes are not yet complete. a state change event for the a11y api's busy state will be fired on the container object currently marked as busy, once it is no longer busy. this is especially important in atomic regions. the entire atomic region should be presented once when it is finally no longer busy. aria-busy on ancestor element container-atomic "true...
Cross-browser audio basics - Developer guides
rationchange > loadedmetadata > loadeddata > progress > canplay > canplaythrough loading interruption events we also have a few events available that will fire when there is some kind of interruption to the media loading process. suspend media data is no longer being fetched even though the file has not been entirely downloaded. abort media data download has been aborted but not due to an
error.
error an
error is encountered while media data is being download. emptied the media buffer has been emptied, possibly due to an
error or because the load() method was invoked to reload it. stalled media data is unexpectedly no longer available. media playing events we also have another set of events that are useful for reacting to the state of the media playback. timeupdate the timeup...
Media events - Developer guides
, when the media has loaded enough that the duration is known. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. encrypted the user agent has encountered initialization data in the media data. ended sent when playback completes.
error sent when an
error occurs. the element's
error attribute contains more information. see htmlmediaelement.
error for details. loadeddata the first frame of the media has finished loading. loadedmetadata the media's metadata has finished loading; all attributes now contain as much useful information as they're going to. loadstart sent when loading of the media...
Constraint validation - Developer guides
onstraints combining several fields, or constraints involving complex calculations. basically, the idea is to trigger javascript on some form field event (like onchange) to calculate whether the constraint is violated, and then to use the method field.setcustomvalidity() to set the result of the validation: an empty string means the constraint is satisfied, and any other string means there is an
error and this string is the
error message to display to the user. constraint combining several fields: postal code validation the postal code format varies from one country to another. not only do most countries allow an optional prefix with the country code (like d- in germany, f- in france or switzerland), but some countries have postal codes with only a fixed number of digits; others, like the u...
Introduction to HTML5 - Developer guides
ricts character sets to those compatible with ascii and using at least 8 bits. this was done to tighten security and prevent some types of attacks. using the new html5 parser the parsing rules of html5, which analyze the meaning of mark-up, have been more precisely defined in html5. until the introduction of html5, only the meaning of valid mark-up was defined, meaning that as soon as one small
error was made in the mark-up (most websites have at least one), the behavior was undefined. essentially, it meant that all browsers behaved differently, which is no longer the case. now, faced with
errors in the mark-up, all compliant browsers must behave exactly in the same way. this requirement helps web developers quite a bit. while it is true that all modern browsers now use these html5 parsing r...
Index - Developer guides
icode® bidirectional algorithm (also known as the bidi algorithm) is part of the unicode text standard that describes how the user agent should order characters while rendering unicode text. 41 the web open font format (woff) fonts, needsmobilebrowsercompatibility, woff woff (the web open font format) is a web font format developed by mozilla in concert with type supply, lett
error, and other organizations. it adds metadata and private-use data structures, including predefined fields allowing foundries and vendors to provide license information if desired. 42 user input and controls screen orientation, contenteditable, drag and drop, fullscreen, keyboard, mouse, pointer lock, touch, user input modern web user input goes beyond simple mouse and keyboard:...
The Web Open Font Format (WOFF) - Developer guides
it uses a compressed version of the same table-based sfnt structure used by truetype, opentype, and open font format, but adds metadata and private-use data structures, including predefined fields allowing foundries and vendors to provide license information if desired. there are three main benefits to using woff: the font data is compressed, so sites using woff will use less bandwidth and will load faster than if they used equivalent uncompressed truetype or opentype files. ...
HTML attribute: minlength - HTML: Hypertext Markup Language
ength, otherwise the value will never be valid, as it is impossible to meet both criteria. the input will fail constraint validation if the length of the text value of the field is less than minlength utf-16 code units long, with validitystate.tooshort returning true. constraint validation is only applied when the value is changed by the user. once submission fails, some browsers will display an
error message indicating the minimum length required and the current length. examples by adding minlength="5", the value must either be empty or five characters or longer to be valid. <label for="fruit">enter a fruit name that is at least 5 letters long</label> <input type="text" minlength="5" id="fruit"> we can use pseudoclasses to style the element based on whether the value is valid. the value w...
HTML attribute: pattern - HTML: Hypertext Markup Language
scouraged as many user agents do not expose the attribute in an accessible manner. some browsers show a tooltip when an element with a title is hovered, but that leaves out keyboard-only and touch-only users. this is one of the several reasons you must include information informing users how to fill out the the control to match the requirements. while titles are used by some browsers to populate
error messaging, because browsers sometimes also show the title as text on hover, it therefore shows in non-
error situations, so be careful not to word titles as if an
error has occurred. specifications specification status comment html living standardthe definition of 'pattern' in that specification. living standard html 5.1the definition of 'pattern' in that ...
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
ble of contents for a document automatically. avoid using heading tags to resize text. instead, use the css font-size property. headings use size to indicate their relative importance, but css is preferred for general-purpose resizing. avoid skipping heading levels: always start from <h1>, next use <h2> and so on. you should only use one <h1> per page. using more than one will not result in an
error, but using only one is seen as a best practice. it makes logical sense — <h1> is the most important heading, and tells you what the purpose of the overall page is. you wouldn't have a book with more than one title, or a movie with more than one name! having a single top-level title is also arguably better for screenreader users, and seo. examples all headings the following code shows all th...
<a>: The Anchor element - HTML: Hypertext Markup Language
t emulates how sighted users quickly scan pages. onclick events anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events . these bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when javascript is loading,
errors, or is disabled. they also convey incorrect semantics to assistive technologies, like screen readers. use a <button> instead. in general, you should only use a hyperlink for navigation to a real url. external links and linking to non-html resources links that open in a new tab/window via target="_blank", or links that point to a download file should indicate what will happen when the link is ...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
e notes: if you don't specify the controls attribute, the audio player won't include the browser's default controls. you can, however, create your own custom controls using javascript and the htmlmediaelement api. to allow precise control over your audio content, htmlmediaelements fire many different events. this also provides a way to monitor the audio's fetching process so you can watch for
errors or detect when enough is available to begin to play or manipulate it. you can also use the web audio api to directly generate and manipulate audio streams from javascript code rather than streaming pre-existing audio files. <audio> elements can't have subtitles or captions associated with them in the same way that <video> elements can. see webvtt and audio by ian devlin for some useful informa...
<body>: The Document Body element - HTML: Hypertext Markup Language
. this method is non-conforming, use css color property in conjunction with the :link pseudo-class instead. onafterprint function to call after the user has printed the document. onbeforeprint function to call when the user requests printing of the document. onbeforeunload function to call when the document is about to be unloaded. onblur function to call when the document loses focus. on
error function to call when the document fails to load properly. onfocus function to call when the document receives focus. onhashchange function to call when the fragment identifier part (starting with the hash ('#') character) of the document's current address has changed. onlanguagechange function to call when the preferred languages changed. onload function to call when the document has ...
<input type="image"> - HTML: Hypertext Markup Language
if provided, it must be a non-empty string appropriate as a label for the button. for example, if you have a graphical button that shows an image with an icon and/or image text "login now", you should also set the alt attribute to something like login now. important: while the alt a...
<input type="number"> - HTML: Hypertext Markup Language
the css applied to this example is as follows: div { margin-bottom: 10px; } input:invalid+span:after { content: '✖'; padding-left: 5px; } input:valid+span:after { content: '✓'; padding-left: 5px; } here we use the :invalid and :valid pseudo classes to display an appropriate invalid or valid icon as generated content on ...
<input type="search"> - HTML: Hypertext Markup Language
if you try to go beyond 8 characters in length, the browser won't let you. specifying a pattern you can use the pattern attribute to specify a regular expression that the inputted value must follow to be considered valid (see validating against a regular expression for a simple crash course). let's look at an example. say we wanted to provide a product...
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
then we update the html to use this class on the keys in the output to be presented: <p>you can also create a new document by pressing <kbd><kbd class="key">ctrl</kbd>+<kbd class="key">n</kbd></kbd>.</p> result the result is just what we want! echoed input nesting a <kbd> element inside a <samp> element represents input that has been echoed back to the user by the system. ...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
esheet" media="print"> <link href="mobile.css" rel="stylesheet" media="all"> <link href="desktop.css" rel="stylesheet" media="screen and (min-width: 600px)"> <link href="highres.css" rel="stylesheet" media="screen and (min-resolution: 300dpi)"> stylesheet load events you can determine when a style sheet has been loaded by watching for a load event to fire on it; similarly, you can detect if an
error has occurred while processing a style sheet by watching for an
error event: <script> var mystylesheet = document.queryselector('#my-stylesheet'); mystylesheet.onload = function() { // do something interesting; the sheet has been loaded } mystylesheet.on
error = function() { console.log("an
error occurred loading the stylesheet!"); } </script> <link rel="stylesheet" href="mystylesheet.css" ...
<source>: The Media or Image Source element - HTML: Hypertext Markup Language
sed on the web. examples video example this example demonstrates how to offer a video in ogg format for users whose browsers support ogg format, and a quicktime format video for users whose browsers support that. if the audio or video element is not supported by the browser, a notice is displayed instead. if the browser supports the element but does not support any of the specified formats, an
error event is raised and the default media controls (if enabled) will indicate an
error. be sure to reference our guide to media types and formats on the web for details on what media file formats you can use and how well they're supported by browsers. <video controls> <source src="foo.webm" type="video/webm"> <source src="foo.ogg" type="video/ogg"> <source src="foo.mov" type="video/quicktime">...
<title>: The Document Title element - HTML: Hypertext Markup Language
e and infer the content the page contains. this is because navigating into a page to determine its content can be a time consuming and potentially confusing process. example <title>menu - blue house chinese food - foodyum: online takeout today!</title> to help the user, update the page title value to reflect significant page state changes (such as form validation problems). example <title>2
errors - your order - blue house chinese food - foodyum: online takeout today!</title> mdn understanding wcag, guideline 2.4 explanations understanding success criterion 2.4.2 | w3c understanding wcag 2.0 specifications specification status comment html living standardthe definition of '<title>' in that specification. living standard html5the definiti...
HTML documentation index - HTML: Hypertext Markup Language
ute assigns a slot in a shadow dom shadow tree to an element: an element with a slot attribute is assigned to the slot created by the <slot> element whose name attribute's value matches that slot attribute's value. 29 spellcheck global attributes, html, reference the spellcheck global attribute is an enumerated attribute defines whether the element may be checked for spelling
errors. 30 style global attributes, html, reference the style global attribute contains css styling declarations to be applied to the element. note that it is recommended for styles to be defined in a separate file or files. this attribute and the <style> element have mainly the purpose of allowing for quick styling, for example for testing purposes. 31 tabindex glob...
Data URLs - HTTP
though firefox supports data urls of essentially unlimited length, browsers are not required to support any particular maximum length of data. for example, the opera 11 browser limited urls to 65535 characters long which limits data urls to 65529 characters (65529 characters being the length of the encoded data, not the source, if you use the plain data:, without specifying a mime type). lack of
error handling invalid parameters in media, or typos when specifying 'base64', are ignored, but no
error is provided. no support for query strings, etc. the data portion of a data url is opaque, so an attempt to use a query string (page-specific parameters, with the syntax <url>?parameter-data) with a data url will just include the query string in the data the url represents. security issues a...
Evolution of HTTP - HTTP
(not the url as both the protocol, server, and port are unnecessary once connected to the server). get /mypage.html the response is extremely simple too: it only consisted of the file itself. <html> a very simple html page </html> unlike subsequent evolutions, there were no http headers, meaning that only html files could be transmitted, but no other type of documents. there were no status or
error codes: in case of a problem, a specific html file was send back with the description of the problem contained in it, for human consumption. http/1.0 – building extensibility http/0.9 was very limited and both browsers and servers quickly extended it to be more versatile: versioning information is now sent within each request (http/1.0 is appended to the get line) a status code line is als...
Reason: CORS request did not succeed - HTTP
reason reason: cors request did not succeed what went wrong? the http request which makes use of cors failed because the http connection failed at either the network or protocol level. the
error is not directly related to cors, but is a fundamental network
error of some kind. in many cases, it is caused by a browser plugin (e.g. an ad blocker or privacy protector) blocking the request. other possible causes include: trying to access an https resource that has an invalid certificate will cause this
error. trying to access an http resource from a page with an https origin will also cause this
error. as of firefox 68, https pages are not permitted to access http://localhost, although this may be changed by bug 1488740. the server did not respond to the actual request (even if it respon...
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ - HTTP
ludes an access-control-allow-headers header which includes at least one invalid header name. the access-control-allow-headers header is sent by the server in response to a preflight request; it lets the client know which http headers are permitted in cors requests. if the client user agent finds among the comma-delineated values provided by the header any header name it does not recognize, this
error occurs. this is a problem that most likely can only be fixed on the server side, by modifying the server's configuration to no longer send the invalid or unknown header name with the access-control-allow-headers header. it may also be worth checking to ensure that the user agent or http library you're using on the client is up-to-date. ...
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Methods’ - HTTP
control-allow-methods header which includes at least one invalid method name. the access-control-allow-methods header is sent by the server to let the client know what http request methods it supports for cors requests. the header's value is a comma-delineated string of http method names, such as get, post, or head. if any of the specified values are not recognized by the client user agent, this
error occurs. this is a problem that most likely can only be fixed on the server side, by modifying the server's configuration to no longer send the invalid or unknown method name with the access-control-allow-methods header. it may also be worth checking to ensure that the user agent or http library you're using on the client is up-to-date. ...
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
use. to fix this problem on the client side, revise the code to not request the use of credentials. if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to true. if using server-sent events, make sure eventsource.withcredentials is false (it's the default value). if using the fetch api, make sure request.credentials is "omit". to eliminate this
error by changing the server's configuration, adjust the server's configuration to set the access-control-allow-credentials header's value to true. ...
Reason: missing token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel - HTTP
low-headers’ from cors preflight channel what went wrong? the access-control-allow-headers header is sent by the server to let the client know which headers it supports for cors requests. the value of access-control-allow-headers should be a comma-delineated list of header names, such as "x-custom-information" or any of the standard but non-basic header names (which are always allowed). this
error occurs when attempting to preflight a header that is not expressly allowed (that is, it's not included in the list specified by the access-control-allow-headers header sent by the server). to fix this, the server needs to be updated so that it allows the indicated header, or you need to avoid using that header. ...
HTTP caching - HTTP
e other methods. the primary cache key consists of the request method and target uri (oftentimes only the uri is used as only get requests are caching targets). common forms of caching entries are: successful results of a retrieval request: a 200 (ok) response to a get request containing a resource like html documents, images or files. permanent redirects: a 301 (moved permanently) response.
error responses: a 404 (not found) result page. incomplete results: a 206 (partial content) response. responses other than get if something suitable for use as a cache key is defined. a cache entry might also consist of multiple stored responses differentiated by a secondary key, if the request is target of content negotiation. for more details see the information about the vary header below. cont...
Feature Policy - HTTP
e or non-breaking way for web developers to detect or handle the case when the feature is disabled. newly introduced features may have an explicit api to signal the state. existing features that later integrate with feature policy will typically use existing mechanisms. some approaches include: return "permission denied" for javascript apis that require user permission grants. return false or
error from an existing javascript api that provides access to feature. change the default values or options that control the feature behavior. the current set of policy-controlled features fall into two broad categories: enforcing best practices for good user experiences. providing granular control over sensitive or powerful features. best practices for good user experiences there are several...
Accept-Charset - HTTP
gs, uses it, and informs the client of its choice within the content-type response header, usually in a charset= parameter. browsers usually don't send this header, as the default value for each resource is usually correct and transmitting it would allow fingerprinting. if the server cannot serve any character encoding from this request header, it can theoretically send back a 406 not acceptable
error code. but for a better user experience, this is rarely done and the accept-charset header is ignored. in early versions of http/1.1, a default character encoding was defined: iso-8859-1. this is no longer recommended, and now each content-type may have its own default. utf-8 is now well-supported and the overwhelmingly preferred character encoding. to guarantee better privacy through less conf...
Accept-Encoding - HTTP
t afford the computational overhead induced by the compression requirement. typically, microsoft recommends not to compress if a server uses more than 80% of its computational power. as long as the identity value, meaning no encoding, is not explicitly forbidden, by an identity;q=0 or a *;q=0 without another explicitly set value for identity, the server must never send back a 406 not acceptable
error. notes: an iana registry maintains a complete list of official content encodings. two others content encoding, bzip and bzip2, are sometimes used, though not standard. they implement the algorithm used by these two unix programs. note that the first one was discontinued due to patent licensing problems. header type request header forbidden header name yes ...
Accept-Language - HTTP
e server never overrides an explicit decision. the content of the accept-language is often out of the control of the user (like when traveling and using an internet cafe in a different country); the user may also want to visit a page in another language than the locale of their user interface. if the server cannot serve any matching language, it can theoretically send back a 406 (not acceptable)
error code. but, for a better user experience, this is rarely done and more common way is to ignore the accept-language header in this case. header type request header forbidden header name no cors-safelisted request header yes, with the additional restriction that values can only be 0-9, a-z, a-z, space or *,-.;=. syntax accept-language: <language> accept-l...
Access-Control-Allow-Headers - HTTP
specifications specification status comment fetchthe definition of 'access-control-allow-headers' in that specification. living standard initial definition. ...
Access-Control-Allow-Origin - HTTP
header name no syntax access-control-allow-origin: * access-control-allow-origin: <origin> access-control-allow-origin: null directives * for requests without credentials, the literal value "*" can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. attempting to use the wildcard with credentials will result in an
error. <origin> specifies an origin. only a single origin can be specified. if the server supports clients from multiple origins, it must return the origin for the specific client making the request. null specifies the origin "null". note: null should not be used: "it may seem safe to return access-control-allow-origin: "null", but the serialization of the origin of any resource that uses a non-hi...
CSP: base-uri - HTTP
.c> header set content-security-policy "base-uri 'self'"; </ifmodule> nginx configuration add_header content-security-policy "base-uri 'self';" violation case since your domain isn't example.com, a <base> element with its href set to https://example.com will result in a csp violation. <meta http-equiv="content-security-policy" content="base-uri 'self'"> <base href="https://example.com/"> //
error: refused to set the document's base uri to 'https://example.com/' // because it violates the following content security policy // directive: "base-uri 'self'" specifications specification status comment content security policy level 3the definition of 'base-uri' in that specification. working draft no changes. content security policy level 2the definition ...
CSP: child-src - HTTP
csp version 2 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. ...
CSP: form-action - HTTP
licy "form-action 'none';" violation case using a <form> element with an action set to inline javascript will result in a csp violation. <meta http-equiv="content-security-policy" content="form-action 'none'"> <form action="javascript:alert('foo')" id="form1" method="post"> <input type="text" name="fieldname" value="fieldvalue"> <input type="submit" id="submit" value="submit"> </form> //
error: refused to send form data because it violates the following // content security policy directive: "form-action 'none'". specifications specification status comment content security policy level 3the definition of 'form-action' in that specification. working draft no changes. content security policy level 2the definition of 'form-action' in that specificat...
CSP: prefetch-src - HTTP
r trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. example prefetch resources do not match header given a page with the following content security policy: content-security-policy: prefetch-src https://example.com/ fetches for the following code will return network
errors, as the urls provided do not match prefetch-src's source list: <link rel="prefetch" src="https://example.org/"></link> <link rel="prerender" src="https://example.org/"></link> specification specification status comment content security policy level 3the definition of 'prefetch-src' in that specification. working draft initial definition. ...
ETag - HTTP
o an etag in the response: etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" when saving changes to a wiki page (posting data), the post request will contain the if-match header containing the etag values to check freshness against. if-match: "33a64df551425fcc55e4d42a148795d9f25f89d4" if the hashes don't match, it means that the document has been edited in-between and a 412 precondition failed
error is thrown. caching of unchanged resources another typical use of the etag header is to cache resources that are unchanged. if a user visits a given url again (that has an etag set), and it is stale (too old to be considered usable), the client will send the value of its etag along in an if-none-match header field: if-none-match: "33a64df551425fcc55e4d42a148795d9f25f89d4" the server compares t...
Feature-Policy: camera - HTTP
syntax feature-policy: camera <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: 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: fullscreen - HTTP
by default, top-level documents and their same-origin child frames can request and enter fullscreen mode. this directive allows or prevents cross-origin frames from using fullscreen mode. this includes same-origin frames. if both this directive (i.e. ...
Feature-Policy: microphone - HTTP
syntax feature-policy: microphone <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: payment - HTTP
syntax feature-policy: payment <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: publickey-credentials-get - HTTP
the http feature-policy header publickey-credentials-get directive controls whether the current document is allowed to access web authentcation api to create new public-key credentials, i.e, via navigator.credentials.get({publickey: ..., ...}). when this policy is enabled, any attempt to query public key credentials will result in an
error. syntax feature-policy: publickey-credentials-get <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 a...
If-Unmodified-Since - HTTP
the if-unmodified-since request http header makes the request conditional: the server will send back the requested resource, or accept it in the case of a post or another non-safe method, only if it has not been last modified after the given date. if the resource has been modified after the given date, the response will be a 412 (precondition failed)
error. there are two common use cases: in conjunction with non-safe methods, like post, it can be used to implement an optimistic concurrency control, like done by some wikis: editions are rejected if the stored document has been modified since the original has been retrieved. in conjunction with a range request with a if-range header, it can be used to ensure that the new fragment requested comes from an unmodified document. heade...
NEL - HTTP
the http nel response header is used to configure network request logging. header type response header forbidden header name no syntax nel: { "report_to": "name_of_reporting_group", "max_age": 12345, "include_subdomains": false, "success_fraction": 0.0, "failure_fraction": 1.0 } specifications specification network
error logging ...
Range - HTTP
the range http request header indicates the part of a document that the server should return. several parts can be requested with one range header at once, and the server may send back these ranges in a multipart document. if the server sends back ranges, it uses the 206 partial content for the response. if the ranges are invalid, the server returns the 416 range not satisfiable
error. the server can also ignore the range header and return the whole document with a 200 status code. header type request header forbidden header name no syntax range: <unit>=<range-start>- range: <unit>=<range-start>-<range-end> range: <unit>=<range-start>-<range-end>, <range-start>-<range-end> range: <unit>=<range-start>-<range-end>, <range-start>-<range-end>, <range-start>-<range-...
Strict-Transport-Security - HTTP
hould never load a site using http and should automatically convert all attempts to access the site using http to https requests instead. note: the strict-transport-security header is ignored by the browser when your site is accessed using http; this is because an attacker may intercept http connections and inject the header or remove it. when your site is accessed over https with no certificate
errors, the browser knows your site is https capable and will honor the strict-transport-security header. an example scenario you log into a free wifi access point at an airport and start surfing the web, visiting your online banking service to check your balance and pay a couple of bills. unfortunately, the access point you're using is actually a hacker's laptop, and they're intercepting your origin...
Warning - HTTP
eted by a cache after deletion. 2xx warn-codes describe some aspect of the representation that is not rectified by a validation and won't be deleted by a cache after validation unless a full response is sent. <warn-agent> the name or pseudonym of the server or software adding the warning header (might be "-" when the agent is unknown). <warn-text> advisory text describing the
error. <warn-date> optional. if more than one warning header is sent, include a date that matches the date header. warning codes the http warn codes registry at iana.org defines the namespace for warn codes. code text description 110 response is stale a response provided by a cache is stale (the expiration time set for it has passed). 111 revalidation...
HTTP headers - HTTP
stination to a server. it is a structured header whose value is a token with possible values audio, audioworklet, document, embed, empty, font, image, manifest, object, paintworklet, report, script, serviceworker, sharedworker, style, track, video, worker, xslt, and nested-document. server-sent events last-event-id ... nel defines a mechanism that enables developers to declare a network
error reporting policy. ping-from ... ping-to ... report-to used to specify a server endpoint for the browser to send warning and
error reports to. transfer coding transfer-encoding specifies the form of encoding used to safely transfer the entity to the user. te specifies the transfer encodings the user agent is willing to accept. trailer allows the sender to include additional fields ...
An overview of HTTP - HTTP
e workflow, allowing session creation on each http request to share the same context, or the same state. http and connections a connection is controlled at the transport layer, and therefore fundamentally out of scope for http. though http doesn't require the underlying transport protocol to be connection-based; only requiring it to be reliable, or not lose messages (so at minimum presenting an
error). among the two most common transport protocols on the internet, tcp is reliable and udp isn't. http therefore relies on the tcp standard, which is connection-based. before a client and server can exchange an http request/response pair, they must establish a tcp connection, a process which requires several round-trips. the default behavior of http/1.0 is to open a separate tcp connection for eac...
Protocol upgrade mechanism - HTTP
e websocket protocol version the client wishes to use when communicating with the server. this number should be the most recent version possible listed in the iana websocket version number registry. the most recent final version of the websocket protocol is version 13. response header if the server can't communicate using the specified version of the websocket protocol, it will respond with an
error (such as 426 upgrade required) that includes in its headers a sec-websocket-version header with a comma-separated list of the supported protocol versions. if the server does support the requested protocol version, no sec-websocket-version header is included in the response. sec-websocket-version: supportedversions supportedversions a comma-delineated list of the websocket protocol versions s...
451 Unavailable For Legal Reasons - HTTP
status 451 unavailable for legal reasons example this example response is taken from the ietf rfc (see below) and contains a reference to monty python's life of brian. note: the link header might also contain a rel="blocked-by" relation identifying the entity and implementing blockage, not any other entity mandating it. ...
502 Bad Gateway - HTTP
the hypertext transfer protocol (http) 502 bad gateway server
error response code indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server. note: a gateway might refer to different things in networking and a 502
error is usually not something you can fix, but requires a fix by the web server or the proxies you are trying to get access through. status 502 bad gateway specifications specification title rfc 7231, section 6.6.3: 502 bad gateway hypertext transfer protocol (http/1.1): semantics and content ...
503 Service Unavailable - HTTP
common causes are a server that is down for maintenance or that is overloaded. this response should be used for temporary conditions and the retry-after http header should, if possible, contain the estimated time for the recovery of the service. note: together with this response, a user-friendly page explaining the problem should be sent. caching-related headers that are sent along with this response should be taken care of, as a 503 status is often a temporary condition and responses shouldn't usually be cached. ...
504 Gateway Timeout - HTTP
the hypertext transfer protocol (http) 504 gateway timeout server
error response code indicates that the server, while acting as a gateway or proxy, did not get a response in time from the upstream server that it needed in order to complete the request. note: a gateway might refer to different things in networking and a 504
error is usually not something you can fix, but requires a fix by the web server or the proxies you are trying to get access through. status 504 gateway timeout specifications specification title rfc 7231, section 6.6.5: 504 gateway timeout hypertext transfer protocol (http/1.1): semantics and content ...
506 Variant Also Negotiates - HTTP
the hypertext transfer protocol (http) 506 variant also negotiates response status code may be given in the context of transparent content negotiation (see rfc 2295). this protocol enables a client to retrieve the best variant of a given resource, where the server supports multiple variants. the variant also negotiates status code indicates an internal server configuration
error in which the chosen variant is itself configured to engage in content negotiation, so is not a proper negotiation endpoint. status 506 variant also negotiates specifications specification title rfc 2295, section 8.1: 506 variant also negotiates transparent content negotiation in http ...
HTTP
ttp message headers. http request methods the different operations that can be done with http: get, post, and also less common requests like options, delete, or trace. http status response codes http response codes 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...
JavaScript data types and data structures - JavaScript
st x = 2n ** 53n; 9007199254740992n > const y = x + 1n; 9007199254740993n you can use the operators +, *, -, **, and % with bigints—just like with numbers. a bigint is not strictly equal to a number, but it is loosely so. a bigint behaves like a number in cases where it is converted to boolean: if, ||, &&, boolean, !. bigints cannot be operated on interchangeably with numbers. instead a type
error will be thrown. string type javascript's string type is used to represent textual data. it is a set of "elements" of 16-bit unsigned integer values. each element in the string occupies a position in the string. the first element is at index 0, the next at index 1, and so on. the length of a string is the number of elements in it. unlike some programming languages (such as c), javascript string...
Equality comparisons and sameness - JavaScript
_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 equality similar to same-value equality, but +0 and -0 are considered equal. abstract equality, strict equality, and same value in the specification in es5, the ...
Details of the object model - JavaScript
r information). for now, these simple definitions demonstrate how the inheritance occurs. the following java and javascript employee definitions are similar. the only difference is that you need to specify the type for each property in java but not in javascript (this is due to java being a strongly typed language while javascript is a weakly typed language). ...
Functions - JavaScript
gram, if it is declared at the top level). note: this works only when defining the function using the above syntax (i.e. function funcname(){}). the code below will not work. this means that function hoisting only works with function declarations—not with function expressions. console.log(square) // square is hoisted with an initial value undefined. console.log(square(5)) // uncaught type
error: square is not a function const square = function(n) { return n * n; } the arguments of a function are not limited to strings and numbers. you can pass whole objects to a function. the show_props() function (defined in working with objects) is an example of a function that takes an object as an argument. a function can call itself. for example, here is a function that computes factorials re...
Regular expression syntax cheatsheet - JavaScript
e it with a backslash; for example, /a\*/ matches "a*". note that some characters like :, -, @, etc. neither have a special meaning when escaped nor when unescaped. escape sequences like \:, \-, \@ will be equivalent to their literal, unescaped character equivalents in regular expressions. however, in regular expressions with the unicode flag, these will cause an invalid identity escape
error. this is done to ensure backward compatibility with existing code that uses new escape sequences like \p or \k. to match this character literally, escape it with itself. in other words to search for \ use /\\/. assertions if you are looking to contribute to this document, please also edit the original article boundary-type assertions characters meaning ...
Regular expressions - JavaScript
phone number (with area code) and then click "check". <br> the expected format is like ###-###-####. </p> <form action="#"> <input id="phone"> <button onclick="testinfo(document.getelementbyid('phone'));">check</button> </form> javascript var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/; function testinfo(phoneinput) { var ok = re.exec(phoneinput.value); if (!ok) { console.
error(phoneinput.value + ' isn\'t a phone number with area code!'); } else { console.log('thanks, your phone number is ' + ok[0]);} } result tools regexr an online tool to learn, build, & test regular expressions. regex tester an online regex builder/debugger regex visualizer an online visual regex tester. specifications specification ecmascript (ecma-262)the de...
JavaScript technologies overview - JavaScript
e core language (ecmascript) the core language of javascript is standardized by the ecma tc39 committee as a language named ecmascript. this core language is also used in non-browser environments, for example in node.js. what falls under the ecmascript scope? among other things, ecmascript defines: language syntax (parsing rules, keywords, control flow, object literal initialization, ...)
error handling mechanisms (throw, try...catch, ability to create user-defined
error types) types (boolean, number, string, function, object, ...) the global object. in a browser, this global object is the window object, but ecmascript only defines the apis not specific to browsers, e.g. parseint, parsefloat, decodeuri, encodeuri... a prototype-based inheritance mechanism built-in objects and functi...
About the JavaScript reference - JavaScript
pan multiple lines. multiple statements may occur on a single line if each statement is separated by a semicolon. this isn't a keyword, but a group of keywords. expressions and operators this chapter documents all the javascript language operators, expressions and keywords. functions chapter about javascript functions. classes chapter about javascript classes introduced in ecmascript 2015.
errors chapter about specific
errors, exceptions and warnings thrown by javascript. new in javascript chapter about javascript version history. more reference pages deprecated and obsolete features lexical grammar data types and data structures ...
extends - JavaScript
alled polygon. this example is extracted from this live demo (source). class square extends polygon { constructor(length) { // here, it calls the parent class' constructor with lengths // provided for the polygon's width and height super(length, length); // note: in derived classes, super() must be called before you // can use 'this'. leaving this out will cause a reference
error. this.name = 'square'; } get area() { return this.height * this.width; } } using extends with built-in objects this example extends the built-in date object. this example is extracted from this live demo (source). class mydate extends date { getformatteddate() { var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; return t...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
javascript execution won't be halted. what went wrong? the non-standard generic string methods are deprecated and have been removed in firefox 68 and later. string generics provide string instance methods on the string object allowing string methods to be applied to any object. examples deprecated syntax var num = 15; string.replace(num, /5/, '2'); standard syntax var num = ...
Warning: expression closures are deprecated - JavaScript
the javascript warning "expression closures are deprecated" occurs when the non-standard expression closure syntax (shorthand function syntax) is used. message warning: expression closures are deprecated
error type warning. javascript execution won't be halted. what went wrong? the non-standard expression closure syntax (shorthand function syntax) is deprecated and shouldn't be used anymore. this syntax will be removed entirely in bug 1083458 and scripts using it will throw a syntax
error then. examples deprecated syntax expression closures omit curly braces or return statements from function declarations or from method definitions in objects. var x = function() 1; var obj = { count: function() 1 }; standard syntax to convert the non-standard expression closures syntax to stand...
Warning: unreachable code after return statement - JavaScript
the javascript warning "unreachable code after return statement" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after. message warning: unreachable code after return statement (firefox)
error type warning what went wrong? unreachable code after a return statement might occur in these situations: when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after. when an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. why should i have semicolons after return statements? in the case of semicolon-...
The arguments object - JavaScript
, or destructured parameters. that is, assigning new values to variables in the body of the function will not affect the arguments object. nor will assigning new variables to the arguments object affect the value of variables. note: you cannot write a "use strict"; directive in the body of a function definition that accepts rest, default, or destructured parameters. doing so will throw a syntax
error. non-strict functions that are passed only simple parameters (that is, not rest, default, or restructured parameters) will sync the value of variables new values in the body of the function with the arguments object, and vice versa: function func(a) { arguments[0] = 99; // updating arguments[0] also updates a console.log(a); } func(10); // 99 and also: function func(a) { a = 99; // up...
Array() constructor - JavaScript
onstructor, 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 range
error 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 arra...
Array.prototype.copyWithin() - JavaScript
its this value be an array object. the copywithin method is a mutable method. it does not alter the length of this, but it will change its content and create new properties, if necessary. polyfill if (!array.prototype.copywithin) { object.defineproperty(array.prototype, 'copywithin', { value: function(target, start/*, end*/) { // steps 1-2. if (this == null) { throw new type
error('this is null or not defined'); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-8. var relativetarget = target >> 0; var to = relativetarget < 0 ? math.max(len + relativetarget, 0) : math.min(relativetarget, len); // steps 9-11. var relativestart = start >> 0; var from = relativestart < 0 ? math.max(len + r...
Array.prototype.fill() - JavaScript
s value be an array object. fill is a mutator method: it will change the array itself and return it, not a copy of it. if the first parameter is an object, each slot in the array will reference that object. polyfill if (!array.prototype.fill) { object.defineproperty(array.prototype, 'fill', { value: function(value) { // steps 1-2. if (this == null) { throw new type
error('this is null or not defined'); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-7. var start = arguments[1]; var relativestart = start >> 0; // step 8. var k = relativestart < 0 ? math.max(len + relativestart, 0) : math.min(relativestart, len); // steps 9-10. var end = arguments[2]; ...
Array.prototype.filter() - JavaScript
valent to the one specified in ecma-262, 5th edition, assuming that fn.call evaluates to the original value of function.prototype.bind(), and that array.prototype.push() has its original value. ...
Array.prototype.find() - JavaScript
d may not be available in all javascript implementations yet. however, you can polyfill array.prototype.find with the following snippet: // https://tc39.github.io/ecma262/#sec-array.prototype.find if (!array.prototype.find) { object.defineproperty(array.prototype, 'find', { value: function(predicate) { // 1. let o be ? toobject(this value). if (this == null) { throw type
error('"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 type
error exception. if (typeof predicate !== 'function') { throw type
error('predicate must be a function'); } // 4. if thisarg was supplied, let t be thisar...
Array.prototype.findIndex() - JavaScript
the value at the time findindex() visits the element's index. elements that are deleted are still visited. polyfill // https://tc39.github.io/ecma262/#sec-array.prototype.findindex if (!array.prototype.findindex) { object.defineproperty(array.prototype, 'findindex', { value: function(predicate) { // 1. let o be ? toobject(this value). if (this == null) { throw new type
error('"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 type
error exception. if (typeof predicate !== 'function') { throw new type
error('predicate must be a function'); } // 4. if thisarg was supplied, let t be th...
Array.prototype.length - JavaScript
ive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the value of the length property is an integer with a positive sign and a value less than 2 to the 32nd power (232). var namelista = new array(4294967296); //2 to the 32nd power = 4294967296 var namelistc = new array(-100) //negative sign console.log(namelista.length); //range
error: invalid array length console.log(namelistc.length); //range
error: invalid array length var namelistb = []; namelistb.length = math.pow(2,32)-1; //set array length less than 2 to the 32nd power console.log(namelistb.length); //4294967295 you can set the length property to truncate an array at any time. when you extend an array by changing its length property, the number of actual elements i...
Array.prototype.toLocaleString() - JavaScript
e.tolocalestring(). return value a string representing the elements of the array. polyfill // https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring if (!array.prototype.tolocalestring) { object.defineproperty(array.prototype, 'tolocalestring', { value: function(locales, options) { // 1. let o be ? toobject(this value). if (this == null) { throw new type
error('"this" is null or not defined'); } var a = object(this); // 2. let len be ? tolength(? get(a, "length")). var len = a.length >>> 0; // 3. let separator be the string value for the // list-separator string appropriate for the // host environment's current locale (this is // derived in an implementation-defined way). // note: in thi...
Atomics.add() - JavaScript
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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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)the definition of 'atomi...
Atomics.and() - JavaScript
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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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, a bitwise and of 5 & ...
Atomics.compareExchange() - JavaScript
edarray 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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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 specification ecmascr...
Atomics.exchange() - JavaScript
omics.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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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 (ecma-262)the definition...
Atomics.load() - JavaScript
ctive-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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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' in that specification. ...
Atomics.notify() - JavaScript
d 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 type
error, if typedarray is not a int32array. throws a range
error, if index is out of bounds in the typedarray. examples using notify given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however, once the writing thread has s...
Atomics.or() - JavaScript
, 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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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 bitwise or of 5 & 1 resul...
Atomics.store() - JavaScript
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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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 specification. ...
Atomics.sub() - JavaScript
omics.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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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 (ecma-262)the definition o...
Atomics.wait() - JavaScript
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 type
error, if typedarray is not a shared int32array. throws a range
error, if index is out of bounds in the typedarray. examples using wait() given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however, once the writing threa...
Atomics.xor() - JavaScript
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 type
error, if typedarray is not one of the allowed integer types. throws a range
error, 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, a bitwise xor of 5 ^ 1 ...
Atomics - JavaScript
at the 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 atomic...
BigInt.prototype.toString() - JavaScript
ke 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 range
error if tostring() is given a radix less than 2 or greater than 36, a range
error 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, and attempts ...
DataView() constructor - JavaScript
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 range
error 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); var view = new d...
DataView.prototype.getBigInt64() - JavaScript
github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getbigint64(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to read the data from. littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a bigint.
errors thrown range
error thrown if the byteoffset is set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbigint64(0); // 0n specifications specification e...
DataView.prototype.getBigUint64() - JavaScript
ithub.com/mdn/interactive-examples and send us a pull request. syntax dataview.getbiguint64(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to read the data from. littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a bigint.
errors thrown range
error thrown if the byteoffset is set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbiguint64(0); // 0n specifications specification ...
DataView.prototype.getFloat32() - JavaScript
ctive-examples and send us a pull request. syntax dataview.getfloat32(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 32-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 32-bit float number.
errors thrown range
error thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat32(1); // 0 specifications specification ecmasc...
DataView.prototype.getFloat64() - JavaScript
ctive-examples and send us a pull request. syntax dataview.getfloat64(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 64-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 64-bit float number.
errors thrown range
error thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat64(0); // 0 specifications specification ecmasc...
DataView.prototype.getInt16() - JavaScript
ractive-examples and send us a pull request. syntax dataview.getint16(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 16-bit integer number.
errors thrown range
error thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint16(1); // 0 specifications specification ecmascript...
DataView.prototype.getInt32() - JavaScript
active-examples and send us a pull request. syntax dataview.getint32(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view where to read the data. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 32-bit integer number.
errors thrown range
error thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint32(1); // 0 specifications specification ecmascript...
DataView.prototype.getInt8() - JavaScript
e for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getint8(byteoffset) parameters byteoffset the offset, in byte, from the start of the view where to read the data. return value a signed 8-bit integer number.
errors thrown range
error thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint8(1); // 0 specifications specification ecmascript (...
DataView.prototype.getUint16() - JavaScript
ive-examples and send us a pull request. syntax dataview.getuint16(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value an unsigned 16-bit integer number.
errors thrown range
error thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint16(1); // 0 specifications specification ecmascri...
DataView.prototype.getUint32() - JavaScript
ive-examples and send us a pull request. syntax dataview.getuint32(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value an unsigned 32-bit integer number.
errors thrown range
error thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint32(1); // 0 specifications specification ecmascri...
DataView.prototype.getUint8() - JavaScript
r 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 dataview.getuint8(byteoffset) parameters byteoffset the offset, in byte, from the start of the view where to read the data. return value an unsigned 8-bit integer number.
errors thrown range
error thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint8(1); // 0 specifications specification ecmascript...
DataView.prototype.setBigInt64() - JavaScript
a from. value the value to set as a bigint. the highest possible value that fits in a signed 64-bit integer is 2n ** (64n -1n) - 1n (9223372036854775807n). upon overflow, it will be negative (-9223372036854775808n). littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined.
errors thrown range
error thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbigint64(0, 3n); dataview.getbigint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbigint6...
DataView.prototype.setBigUint64() - JavaScript
the view to store the data from. value the value to set as a bigint. the highest possible value that fits in an unsigned 64-bit integer is 2n ** 64n - 1n (18446744073709551615n). upon overflow, it will be zero (0n). littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined.
errors thrown range
error thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbiguint64(0, 3n); dataview.getbiguint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbigu...
DataView.prototype.setFloat32() - JavaScript
send us a pull request. syntax dataview.setfloat32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 32-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined.
errors thrown range
error thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat32(1, 3); dataview.getfloat32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat32' in th...
DataView.prototype.setFloat64() - JavaScript
send us a pull request. syntax dataview.setfloat64(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 64-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined.
errors thrown range
error thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat64(0, 3); dataview.getfloat64(0); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat64' in th...
DataView.prototype.setInt16() - JavaScript
and send us a pull request. syntax dataview.setint16(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined.
errors thrown range
error thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint16(1, 3); dataview.getint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint16' in that speci...
DataView.prototype.setInt32() - JavaScript
and send us a pull request. syntax dataview.setint32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined.
errors thrown range
error thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint32(1, 3); dataview.getint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint32' in that speci...
DataView.prototype.setInt8() - JavaScript
eractive 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 dataview.setint8(byteoffset, value) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. return value undefined.
errors thrown range
error thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint8(1, 3); dataview.getint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint8' in that specifica...
DataView.prototype.setUint16() - JavaScript
and send us a pull request. syntax dataview.setuint16(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined.
errors thrown range
error thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint16(1, 3); dataview.getuint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint16' in that s...
DataView.prototype.setUint32() - JavaScript
and send us a pull request. syntax dataview.setuint32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined.
errors thrown range
error thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint32(1, 3); dataview.getuint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint32' in that s...
DataView.prototype.setUint8() - JavaScript
ractive 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 dataview.setuint8(byteoffset, value) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. return value undefined.
errors thrown range
error thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint8(1, 3); dataview.getuint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint8' in that speci...
Date.prototype[@@toPrimitive] - JavaScript
r a string or a number. description the [@@toprimitive]() method of the date object returns a primitive value, that is either of type number or of type string. if hint is "string" or "default", [@@toprimitive]() tries to call the tostring method. if the tostring property does not exist, it tries to call the valueof method and if the valueof does not exist either, [@@toprimitive]() throws a type
error. if hint is "number", [@@toprimitive]() first tries to call valueof, and if that fails, it calls tostring. javascript calls the [@@toprimitive]() method to convert an object to a primitive value. you rarely need to invoke the [@@toprimitive]() method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. examples returning date primitive...
Date.parse() - JavaScript
with invalid date values new date('23/25/2014'); will be treated as a local date of 25 november, 2015 in firefox 30 and an invalid date in safari 7. however, if the string is recognized as an iso format string and it contains invalid values, it will return nan in all browsers compliant with es5 and later: // iso string with invalid values new date('2014-25-23').toisostring(); // throws "range
error: invalid date" in all es5-compliant browsers spidermonkey's implementation-specific heuristic can be found in jsdate.cpp. the string "10 06 2014" is an example of a non-conforming iso format and thus falls back to a custom routine. see also this rough outline on how the parsing works. new date('10 06 2014'); will be treated as a local date of 6 october, 2014, and not 10 june, 2014. other ex...
Date.prototype.toLocaleDateString() - JavaScript
lt time zone console.log(date.tolocaledatestring()); // → "12/11/2012" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a range
error exception: function tolocaledatestringsupportslocales() { try { new date().tolocaledatestring('i'); } catch (e) { return e.name === 'range
error'; } 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 p...
Date.prototype.toLocaleString() - JavaScript
zone console.log(date.tolocalestring()); // → "12/11/2012, 7:00:00 pm" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a range
error exception: function tolocalestringsupportslocales() { try { new date().tolocalestring('i'); } catch (e) { return e instanceof range
error; } 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 ...
Date.prototype.toLocaleTimeString() - JavaScript
lt time zone console.log(date.tolocaletimestring()); // → "7:00:00 pm" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a range
error exception: function tolocaletimestringsupportslocales() { try { new date().tolocaletimestring('i'); } catch (e) { return e.name === 'range
error'; } 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 (an...
Date.prototype.toString() - JavaScript
w date()), or when a date is used in a string concatenation, such as var today = 'today is ' + new date(). tostring() is a generic method, it does not require that its this is a date instance. however, it must have an internal [[timevalue]] property that can't be constructed using native javascript, so it's effectively limited to use with date instances. if called on a non–date instance, a type
error is thrown. examples using tostring() the following assigns the tostring() value of a date object to myvar: var x = new date(); var myvar = x.tostring(); // assigns a string value to myvar in the same format as: // mon sep 08 1998 14:36:22 gmt-0700 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tostring' ...
Function.displayName - JavaScript
popup'; console.log(popup.displayname); // "show popup" defining a displayname in function expressions you can define a function with a display name in a function expression: var object = { somemethod: function() {} }; object.somemethod.displayname = 'somemethod'; console.log(object.somemethod.displayname); // logs "somemethod" try { somemethod } catch(e) { console.log(e); } // reference
error: somemethod is not defined changing displayname dynamically you can dynamically change the displayname of a function: var object = { // anonymous somemethod: function(value) { arguments.callee.displayname = 'somemethod (' + value + ')'; } }; console.log(object.somemethod.displayname); // "undefined" object.somemethod('123') console.log(object.somemethod.displayname); // "somemetho...
Function.name - JavaScript
let object = { // anonymous somemethod: function() {} }; object.somemethod.name = 'othermethod'; console.log(object.somemethod.name); // somemethod to change it, u...
Function - JavaScript
this is because the top-level scope in node is not the global scope, and x will be local to the module. specifications specification ecmascript (ecma-262)the definition of 'function' in that specification. ...
Generator - JavaScript
instead, a generator instance can be returned from a generator function: function* generator() { yield 1; yield 2; yield 3; } const gen = generator(); // "generator { }" instance methods generator.prototype.next() returns a value yielded by the yield expression. generator.prototype.return() returns the given value and finishes the generator. generator.prototype.throw() throws an
error to a generator (also finishes the generator, unless caught from within that generator). examples an infinite iterator function* infinite() { let index = 0; while (true) { yield index++; } } const generator = infinite(); // "generator { }" console.log(generator.next().value); // 0 console.log(generator.next().value); // 1 console.log(generator.next().value); // 2 // ... ...
Intl.getCanonicalLocales() - JavaScript
equest. syntax intl.getcanonicallocales(locales) parameters locales a list of string values for which to get the canonical locale names. return value an array containing the canonical locale names. examples using getcanonicallocales intl.getcanonicallocales('en-us'); // ["en-us"] intl.getcanonicallocales(['en-us', 'fr']); // ["en-us", "fr"] intl.getcanonicallocales('en_us'); // range
error:'en_us' is not a structurally valid language tag specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.getcanonicallocales' in that specification. ...
Math.ceil() - 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 math.ceil(x) parameters x a number. return value the smallest integer greater than or equal to the given number. ...
Number.NEGATIVE_INFINITY - JavaScript
an. nan multiplied by negative_infinity is nan. negative_infinity, divided by any negative value except negative_infinity, is positive_infinity. negative_infinity, divided by any positive value except positive_infinity, is negative_infinity. negative_infinity, divided by either negative_infinity or positive_infinity, is nan. you might use the number.negative_infinity property to indicate an
error condition that returns a finite number in case of success. note, however, that isfinite would be more appropriate in such a case. because negative_infinity is a static property of number, you always use it as number.negative_infinity, rather than as a property of a number object you created. examples using negative_infinity in the following example, the variable smallnumber is assigned a val...
Number.POSITIVE_INFINITY - JavaScript
an. nan multiplied by positive_infinity is nan. positive_infinity, divided by any negative value except negative_infinity, is negative_infinity. positive_infinity, divided by any positive value except positive_infinity, is positive_infinity. positive_infinity, divided by either negative_infinity or positive_infinity, is nan. you might use the number.positive_infinity property to indicate an
error condition that returns a finite number in case of success. note, however, that isfinite would be more appropriate in such a case. because positive_infinity is a static property of number, you always use it as number.positive_infinity, rather than as a property of a number object you created. examples using positive_infinity in the following example, the variable bignumber is assigned a value...
Number.prototype.toExponential() - JavaScript
tial([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 range
error if fractiondigits is too small or too large. values between 0 and 20, inclusive, will not cause a range
error. implementations are allowed to support larger and smaller values as well. type
error 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 of digits neces...
Number.prototype.toFixed() - JavaScript
equest. 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 range
error if digits is too small or too large. values between 0 and 100, inclusive, will not cause a range
error. implementations are allowed to support larger and smaller values as chosen. type
error 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 digits after the ...
Number.prototype.toLocaleString() - JavaScript
and with 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 range
error exception can be used: function tolocalestringsupportslocales() { var number = 0; try { number.tolocalestring('i'); } catch (e) { return e.name === 'range
error'; } 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 p...
Number.prototype.toPrecision() - JavaScript
ect 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 range
error if precision is not between 1 and 100 (inclusive), a range
error 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' console.log(numobj...
Number.prototype.toString() - 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 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 range
error if tostring() is given a radix less than 2 or greater than 36, a range
error 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 argument, and attempt...
Object.getOwnPropertyNames() - JavaScript
ct obj. the ordering of the enumerable properties in the array is consistent with the ordering exposed by a for...in loop (or by object.keys()) over the properties of the object. the ordering of the non-enumerable properties in the array and the ordering among the enumerable properties is not defined. in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. in es2015, a non-object argument will be coerced to an object. object.getownpropertynames('foo'); // type
error: "foo" is not an object (es5 code) object.getownpropertynames('foo'); // ["0", "1", "2", "length"] (es2015 code) examples using object.getownpropertynames() var arr = ['a', 'b', 'c']; console.log(object.getownpropertynames(arr).sort()); // .sort() is an array method. // logs ["0"...
Object.isExtensible() - JavaScript
le(empty); // === false // sealed objects are by definition non-extensible. var sealed = object.seal({}); object.isextensible(sealed); // === false // frozen objects are also by definition non-extensible. var frozen = object.freeze({}); object.isextensible(frozen); // === false non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. object.isextensible(1); // type
error: 1 is not an object (es5 code) object.isextensible(1); // false (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.isextensible' in that specification. ...
Object.isFrozen() - JavaScript
bject.isfrozen(frozen); // === false object.freeze(frozen); object.isfrozen(frozen); // === true // by definition, a frozen object is non-extensible. object.isextensible(frozen); // === false // also by definition, a frozen object is sealed. object.issealed(frozen); // === true non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a type
error. in es2015, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. object.isfrozen(1); // type
error: 1 is not an object (es5 code) object.isfrozen(1); // true (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.isfrozen' in that specification. ...
Object.prototype.isPrototypeOf() - JavaScript
anceof operator. in the expression "object instanceof afunction", the object prototype chain is checked against afunction.prototype, not against afunction itself. syntax prototypeobj.isprototypeof(object) parameters object the object whose prototype chain will be searched. return value a boolean indicating whether the calling object lies in the prototype chain of the specified object.
errors thrown type
error a type
error is thrown if prototypeobj is undefined or null. description the isprototypeof() method allows you to check whether or not an object exists within another object's prototype chain. examples using isprototypeof this example demonstrates that baz.prototype, bar.prototype, foo.prototype and object.prototype exist in the prototype chain for object baz: function...
Object.prototype.__proto__ - JavaScript
w fun, where fun is a function defined in a script, this value is the value of fun.prototype. (that is, if the constructor didn't return an other object explicitly, or the fun.prototype has been reassigned since the instance was created.) the __proto__ setter allows the [[prototype]] of an object to be mutated. the object must be extensible according to object.isextensible(): if it is not, a type
error is thrown. the value provided must be an object or null. providing any other value will do nothing. to understand how prototypes are used for inheritance, see guide article inheritance and the prototype chain. the __proto__ property is a simple accessor property on object.prototype consisting of a getter and setter function. a property access for __proto__ that eventually consults object.protot...
Promise.allSettled() - JavaScript
object, a status string is present. if the status is fulfilled, then a value is present. if the status is rejected, then a reason is present. the value (or reason) reflects what value each promise was fulfilled (or rejected) with. examples using promise.allsettled promise.allsettled([ promise.resolve(33), new promise(resolve => settimeout(() => resolve(66), 0)), 99, promise.reject(new
error('an
error')) ]) .then(values => console.log(values)); // [ // {status: "fulfilled", value: 33}, // {status: "fulfilled", value: 66}, // {status: "fulfilled", value: 99}, // {status: "rejected", reason:
error: an
error} // ] specifications specification ecmascript (ecma-262)the definition of 'promise.allsettled' in that specification. ...
Promise.prototype.finally() - JavaScript
rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw. examples using finally let isloading = true; fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { return response.json(); } throw new type
error("oops, we haven't got json!"); }) .then(function(json) { /* process your json further */ }) .catch(function(
error) { console.
error(
error); /* this line can also throw, e.g. when console = {} */ }) .finally(function() { isloading = false; }); please do not add polyfills on mdn pages. for more details, refer to: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-di...
Promise.reject() - JavaScript
to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax promise.reject(reason); parameters reason reason why this promise rejected. return value a promise that is rejected with the given reason. description the static promise.reject function returns a promise that is rejected. for debugging purposes and selective
error catching, it is useful to make reason an instanceof
error. examples using the static promise.reject() method promise.reject(new
error('fail')).then(function() { // not called }, function(
error) { console.
error(
error); // stacktrace }); specifications specification ecmascript (ecma-262)the definition of 'promise.reject' in that specification. ...
handler.apply() - JavaScript
the list of arguments for the call. return value the apply() method can return any value. description the handler.apply() method is a trap for a function call. interceptions this trap can intercept these operations: proxy(...args) function.prototype.apply() and function.prototype.call() reflect.apply() invariants if the following invariants are violated, the proxy will throw a type
error. the target must be a callable itself. that is, it must be a function object. examples trapping a function call the following code traps a function call. const p = new proxy(function() {}, { apply: function(target, thisarg, argumentslist) { console.log('called: ' + argumentslist.join(', ')); return argumentslist[0] + argumentslist[1] + argumentslist[2]; } }); console.log(p(1, 2,...
handler.deleteProperty() - JavaScript
return a boolean indicating whether or not the property has been successfully deleted. description the handler.deleteproperty() method is a trap for the delete operator. interceptions this trap can intercept these operations: property deletion: delete proxy[foo] and delete proxy.foo reflect.deleteproperty() invariants if the following invariants are violated, the proxy will throw a type
error: a property cannot be deleted, if it exists as a non-configurable own property of the target object. examples trapping the delete operator the following code traps the delete operator. const p = new proxy({}, { deleteproperty: function(target, prop) { if (prop in target){ delete target[prop] console.log('property removed: ' + prop) return true } else { ...
Reflect.apply() - JavaScript
ax 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 type
error, 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.apply...
Reflect.construct() - JavaScript
n 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 type
error, 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 reflect, objects cou...
Reflect.deleteProperty() - JavaScript
tive 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 type
error, 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
yntax 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 type
error, 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, { get(t, k, r) { ...
Reflect.has() - JavaScript
ontribute 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 type
error, 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 method obj = new pr...
Reflect.ownKeys() - JavaScript
s 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 type
error, 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([]) // ["length"] let sym =...
Reflect.set() - JavaScript
lect.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 type
error, if target is not an object. description the reflect.set method allows you to set a property on an object. it does property assignment and is like the property accessor syntax as a function. examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // array let arr = ['duck', 'duck', 'duck'] reflect.set(arr, 2, 'goose') // true arr[...
Reflect.setPrototypeOf() - JavaScript
ctive 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 type
error, if target is not an object or if prototype is neither an object nor null. description the reflect.setprototypeof method changes the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. examples using reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null. reflect.setprototypeof(...
RegExp.lastMatch ($&) - JavaScript
rty is static, it is not a property of an individual regular expression object. instead, you always use it as regexp.lastmatch or regexp['$&']. the value of the lastmatch property is read-only and modified whenever a successful match is made. you can not use the shorthand alias with the dot property accessor (regexp.$&), because the parser expects an expression with "&" in that case and a syntax
error is thrown. use the bracket notation for property access. examples using lastmatch and $& var re = /hi/g; re.test('hi there!'); regexp.lastmatch; // "hi" regexp['$&']; // "hi" specifications specification legacy regexp features in javascript ...
RegExp.lastParen ($+) - JavaScript
rty is static, it is not a property of an individual regular expression object. instead, you always use it as regexp.lastparen or regexp['$+']. the value of the lastparen property is read-only and modified whenever a successful match is made. you can not use the shorthand alias with the dot property accessor (regexp.$+), because the parser expects an expression with "+" in that case and a syntax
error is thrown. use the bracket notation for property access. examples using lastparen and $+ var re = /(hi)/g; re.test('hi there!'); regexp.lastparen; // "hi" regexp['$+']; // "hi" specifications specification legacy regexp features in javascript ...
RegExp.leftContext ($`) - JavaScript
tatic, it is not a property of an individual regular expression object. instead, you always use it as regexp.leftcontext or regexp['$`']. the value of the leftcontext property is read-only and modified whenever a successful match is made. you can not use the shorthand alias with the dot property accessor (regexp.$`), because the parser expects a starting template string in that case and a syntax
error is thrown. use the bracket notation for property access. examples using leftcontext and $` var re = /world/g; re.test('hello world!'); regexp.leftcontext; // "hello " regexp['$`']; // "hello " specifications specification legacy regexp features in javascript ...
RegExp.rightContext ($') - JavaScript
ty is static, it is not a property of an individual regular expression object. instead, you always use it as regexp.rightcontext or regexp["$'"]. the value of the rightcontext property is read-only and modified whenever a successful match is made. you can not use the shorthand alias with the dot property accessor (regexp.$'), because the parser expects a starting string in that case and a syntax
error is thrown. use the bracket notation for property access. examples using rightcontext and $' var re = /hello/g; re.test('hello world!'); regexp.rightcontext; // " world!" regexp["$'"]; // " world!" specifications specification legacy regexp features in javascript ...
RegExp - JavaScript
the regular expression object—for example, new regexp('ab+c')—results in runtime compilation of the regular expression. use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and obtain it from another source, such as user input. flags in constructor starting with ecmascript 6, new regexp(/ab+c/, 'i') no longer throws a type
error ("can't supply flags when constructing one regexp from another") when the first argument is a regexp and the second flags argument is present. a new regexp from the arguments is created instead. when using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. for example, the following are equivalent: let re = /\...
SharedArrayBuffer() constructor - JavaScript
length the size, in bytes, of the array buffer to create. return value a new sharedarraybuffer object of the specified size. its contents are initialized to 0. examples always use the new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a new operator. calling a sharedarraybuffer constructor as a function without new will throw a type
error. var sab = sharedarraybuffer(1024); // type
error: calling a builtin sharedarraybuffer constructor // without new is forbidden var sab = new sharedarraybuffer(1024); specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer constructor' in that specification. ...
SharedArrayBuffer - JavaScript
// post sharedarraybuffer } else { // do something else } see also planned changes to shared memory which is starting to roll out to browsers (firefox 79, for example.) always use the new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a new operator. calling a sharedarraybuffer constructor as a function without new will throw a type
error. var sab = sharedarraybuffer(1024); // type
error: calling a builtin sharedarraybuffer constructor // without new is forbidden var sab = new sharedarraybuffer(1024); constructor sharedarraybuffer() creates a new sharedarraybuffer object. instance properties sharedarraybuffer.prototype.bytelength the size, in bytes, of the array. this is established when the array is constructed and ca...
String.prototype.includes() - JavaScript
: 'blue whale'.includes('blue') // returns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. ...
String.prototype.localeCompare() - JavaScript
) => a.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 range
error exception: function localecomparesupportslocales() { try { 'foo'.localecompare('bar', 'i'); } catch (e) { return e.name === 'range
error'; } 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 s...
String.prototype.normalize() - JavaScript
if omitted or undefined, "nfc" is used. these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, followed by canonical composition. "nfkd" compatibility decomposition. return value a string containing the unicode normalization form of the given string.
errors thrown range
error a range
error is thrown if form isn't one of the values specified above. description unicode assigns a unique numerical value, called a code point, to each character. for example, the code point for "a" is given as u+0041. however, sometimes more than one code point, or sequence of code points, can represent the same abstract character — the character "ñ" for example c...
String.raw() - JavaScript
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 type
error a type
error 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. it works just ...
String.prototype.toLocaleLowerCase() - JavaScript
dicates 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 range
error ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. a type
error ("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 the value of the ...
String.prototype.toLocaleUpperCase() - JavaScript
dicates 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 range
error ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. a type
error ("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 the value of the ...
String.prototype.toUpperCase() - JavaScript
e 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 type
error 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-string this v...
Symbol() constructor - JavaScript
te symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols. note that symbol("foo") does not coerce the string "foo" into a symbol. it creates a new symbol each time: symbol('foo') === symbol('foo') // false new symbol(...) the following syntax with the new operator will throw a type
error: let sym = new symbol() // type
error this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number). if you really want to create a symbol wrapper object, you can use the object() function: l...
Symbol.prototype.toString() - JavaScript
he specified symbol object. description the symbol object overrides the tostring method of the object object; it does not inherit object.prototype.tostring(). for symbol objects, the tostring method returns a string representation of the object. no string concatenation while you can call tostring() on symbols, you cannot use string concatenation with them: symbol('foo') + 'bar' // type
error: can't convert symbol to string examples using tostring symbol('desc').tostring() // "symbol(desc)" // well-known symbols symbol.iterator.tostring() // "symbol(symbol.iterator) // global symbols symbol.for('foo').tostring() // "symbol(foo)" specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.tostring' in that specification. ...
TypedArray.of() - JavaScript
pedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters elementn elements of which to create the typed array. return value a new typedarray instance. description some subtle distinctions between array.of() and typedarray.of(): if the this value passed to typedarray.of is not a constructor, typedarray.of will throw a type
error, where array.of defaults to creating a new array. typedarray.of uses [[put]] where array.of uses [[defineproperty]]. hence, when working with proxy objects, it calls handler.set to create new elements rather than handler.defineproperty. examples using of uint8array.of(1); // uint8array [ 1 ] int8array.of('1', '2', '3'); // int8array [ 1, 2, 3 ] float32array.of(1, 2, 3); // floa...
TypedArray.prototype.reduce() - JavaScript
two values. if initialvalue is provided in the call to reduce, then previousvalue will be equal to initialvalue and currentvalue will be equal to the first value in the typed array. if no initialvalue was provided, then previousvalue will be equal to the first value in the typed array and currentvalue will be equal to the second. if the typed array is empty and no initialvalue was provided, type
error would be thrown. if the typed array has only one element (regardless of position) and no initialvalue was provided, or if initialvalue is provided but the typed array is empty, the solo value would be returned without calling callback. polyfill this method uses the same algorithm as array.prototype.reduce(), so the same polyfill can be used here: simply replace array.prototype.reduce with typed...
TypedArray.prototype.reduceRight() - JavaScript
itialvalue was provided in the call to reduceright, then previousvalue will be equal to initialvalue and currentvalue will be equal to the last value in the typed array. if no initialvalue was provided, then previousvalue will be equal to the last value in the typed array and currentvalue will be equal to the second-to-last value. if the typed array is empty and no initialvalue was provided, type
error would be thrown. if the typed array has only one element (regardless of position) and no initialvalue was provided, or if initialvalue is provided but the typed array is empty, the solo value would be returned without calling callback. examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduceright(function(a, b) { return a + b; }); // total == 6 specificati...
TypedArray.prototype.set() - JavaScript
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 range
error, 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 that specificat...
WeakSet.prototype.add() - JavaScript
ub.com/mdn/interactive-examples and send us a pull request. syntax ws.add(value); parameters value required. the object to add to the weakset collection. return value the weakset object. examples using add var ws = new weakset(); ws.add(window); // add the window object to the weakset ws.has(window); // true // weakset only takes objects as arguments ws.add(1); // results in "type
error: invalid value used in weak set" in chrome // and "type
error: 1 is not a non-null object" in firefox specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.add' in that specification. ...
WebAssembly.Instance() constructor - JavaScript
e used at all other times. new webassembly.instance(module, importobject); parameters module the webassembly.module object to be instantiated. importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of module or else a webassembly.link
error is thrown. examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes =...
WebAssembly.Memory() constructor - JavaScript
tion 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 type
error is thrown. if maximum is specified and is smaller than initial, a range
error 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 (640kib), and a maximum size of 100 pages (6.4mib). its buffer p...
WebAssembly.Module.customSections() - JavaScript
ustomsections(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 type
error 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 normal sections ("known sections") and custom sections are distinguished.
WebAssembly.Module.exports() - JavaScript
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 type
error 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(mo...
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 type
error 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", n...
WebAssembly.Table() constructor - JavaScript
ollowing 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 type
error is thrown. if maximum is specified and is smaller than initial, a range
error 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 the two indexes (retrieved via table.prototype.get() to sh...
WebAssembly.Table.prototype.get() - JavaScript
ly.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 range
error 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) { var tbl = obj.instance.exports.tbl; con...
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 range
error 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 specificat...
WebAssembly.Table.prototype.set() - JavaScript
dex 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 range
error is thrown. if value is not an exported webassembly function or null, a type
error 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 the two indexes (retrieved via table.prototype.get()) to show that the length ...
WebAssembly.compile() - JavaScript
stantiate() 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 type
error is thrown. if compilation fails, the promise rejects with a webassembly.compile
error. 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 => response.arraybuffer() ).then(bytes => webassembly.com...
WebAssembly.compileStreaming() - JavaScript
x 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 type
error is thrown. if compilation fails, the promise rejects with a webassembly.compile
error. 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 compilestreaming() function accepts a promise for a response object,...
WebAssembly.validate() - JavaScript
ng 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 type
error 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(bytes) { var valid = webassembly.validate(bytes); console.log("the...
encodeURIComponent() - JavaScript
'() console.log(encodeuri(set3)); // # console.log(encodeuri(set4)); // abc%20abc%20123 (the space gets encoded as %20) console.log(encodeuricomponent(set1)); // %3b%2c%2f%3f%3a%40%26%3d%2b%24 console.log(encodeuricomponent(set2)); // -_.!~*'() console.log(encodeuricomponent(set3)); // %23 console.log(encodeuricomponent(set4)); // abc%20abc%20123 (the space gets encoded as %20) note that a uri
error will be thrown if one attempts to encode a surrogate which is not part of a high-low pair, e.g., // high-low pair ok console.log(encodeuricomponent('\ud800\udfff')); // lone high surrogate throws "uri
error: malformed uri sequence" console.log(encodeuricomponent('\ud800')); // lone low surrogate throws "uri
error: malformed uri sequence" console.log(encodeuricomponent('\udfff')); use encodeuri...
eval() - JavaScript
bal functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called. function test() { var x = 2, y = 4; console.log(eval('x + y')); // direct call, uses local scope, result is 6 var geval = eval; // equivalent to calling eval in the global scope console.log(geval('x + y')); // indirect call, uses global scope, throws reference
error because `x` is undefined (0, eval)('x + y'); // another example of indirect call } never use eval()! eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. if you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. mor...
globalThis - JavaScript
s-platform way to get the global object for an environment was function('return this')(). ...
null - JavaScript
with a literal: null. null is not an identifier for a property of the global object, like undefined can be. instead, null expresses a lack of identification, indicating that a variable points to no object. in apis, null is often retrieved in a place where an object can be expected but no object is relevant. // foo does not exist. it is not defined and has never been initialized: foo; //reference
error: foo is not defined // foo is known to exist now but it has no type or value: var foo = null; foo; //null examples difference between null and undefined when checking for null or undefined, beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion. typeof null // "object" (not "null" for legacy reasons) typeof undefined ...
Destructuring assignment - JavaScript
sole.log(a); // 1 console.log(b); // 3 const [c] = f(); console.log(c); // 1 you can also ignore all returned values: [,,] = f(); assigning the rest of an array to a variable when destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern: const [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3] be aware that a syntax
error will be thrown if a trailing comma is used on the left-hand side with a rest element: const [a, ...b,] = [1, 2, 3]; // syntax
error: rest element may not have a trailing comma // always consider using rest operator as the last element unpacking values from a regular expression match when the regular expression exec() method finds a match, it returns an array containing first the entire match...
Exponentiation (**) - JavaScript
ce 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 syntax
error. -2 ** 2; // 4 in bash, -4 in other languages. // this is invalid in javascript, as the operation is ambiguous. -(2 ** 2); // -4 in javascript and the author's intention is unambiguous. note that some programming languages use the caret symbol ^ for exponentiation, but javascript uses that symbol for the bitwise logical xor operator. examples basic exponentiation 2 ** 3 // 8 3 ** 2 //...
Property accessors - JavaScript
(in the ecmascript standard, the names of properties are technically "identifiernames", not "identifiers", so reserved words can be used but are not recommended). for example, object.$1 is valid, while object.1 is not. const variable = object.property_name; object.property_name = value; const object = {}; object.$1 = 'foo'; console.log(object.$1); // 'foo' object.1 = 'bar'; // syntax
error console.log(object.1); // syntax
error here, the method named createelement is retrieved from document and is called. document.createelement('pre') if you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point. 77 .toexpo...
await - JavaScript
enable); // resolved! } f2(); conversion to promise if the value is not a promise, it converts the value to a resolved promise, and waits for it. async function f3() { var y = await 20; console.log(y); // 20 } f3(); promise rejection if the promise is rejected, the rejected value is thrown. async function f4() { try { var z = await promise.reject(30); } catch(e) { console.
error(e); // 30 } } f4(); handling rejected promises handle rejected promise without try block. var response = await promisedfunction().catch((err) => { console.
error(err); }); // response will be undefined if the promise is rejected specifications specification ecmascript (ecma-262)the definition of 'async functions' in that specification. ...
in operator - JavaScript
make: 'honda', model: 'accord', year: 1998} 'make' in mycar // returns true 'model' in mycar // returns true you must specify an object on the right side of the in operator. for example, you can specify a string created with the string constructor, but you cannot specify a string literal. let color1 = new string('green') 'length' in color1 // returns true let color2 = 'coral' // generates an
error (color2 is not a string object) 'length' in color2 using in with deleted or undefined properties if you delete a property with the delete operator, the in operator returns false for that property. let mycar = {make: 'honda', model: 'accord', year: 1998} delete mycar.make 'make' in mycar // returns false let trees = new array('redwood', 'bay', 'cedar', 'oak', 'maple') delete trees[3] 3 in t...
void operator - JavaScript
urns undefined examples immediately invoked function expressions when using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. void function iife() { console.log("executed!"); }(); // output: "executed!" executing the above function without the void keyword will result in an uncaught syntax
error. javascript uris when a browser follows a javascript: uri, it evaluates the code in the uri and then replaces the contents of the page with the returned value, unless the returned value is undefined. the void operator can be used to return undefined. for example: <a href="javascript:void(0);"> click here to do nothing </a> <a href="javascript:void(document.body.style.backgroundcolor='green'...
block - JavaScript
ot use them. block scoping rules with let, const or function declaration in strict mode by contrast, identifiers declared with let and const do have block scope: let x = 1; { let x = 2; } console.log(x); // logs 1 the x = 2 is limited in scope to the block in which it was defined. the same is true of const: const c = 1; { const c = 2; } console.log(c); // logs 1 and does not throw syntax
error... note that the block-scoped const c = 2 does not throw a syntax
error: identifier 'c' has already been declared because it can be declared uniquely within the block. in strict mode, starting with es2015, functions inside blocks are scoped to that block. prior to es2015, block-level functions were forbidden in strict mode. specifications specification ecmascript (ecma-26...
export - JavaScript
ptions = { color:'blue', thickness:'3px' }; graph.draw(); console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888 it is important to note the following: you need to include this script in your html with a <script> element of type="module", so that it gets recognised as a module and dealt with appropriately. you can't run js modules via a file:// url — you'll get cors
errors. you need to run it via an http server. using the default export if we want to export a single value or to have a fallback value for your module, you could use a default export: // module "my-module.js" export default function cube(x) { return x * x * x; } then, in another script, it is straightforward to import the default export: import cube from './my-module.js'; console.log(cube(3)...
function declaration - JavaScript
fined // // in safari: // 'foo' name is hoisted. typeof foo is function function declaration hoisting function declarations in javascript are hoisted to the top of the enclosing function or global scope. you can use the function before you declared it: hoisted(); // logs "foo" function hoisted() { console.log('foo'); } note that function expressions are not hoisted: nothoisted(); // type
error: nothoisted is not a function var nothoisted = function() { console.log('bar'); }; examples using function the following code declares a function that returns the total amount of sales, when given the number of units sold of products a, b, and c. function calc_sales(units_a, units_b, units_c) { return units_a * 79 + units_b * 129 + units_c * 699; } specifications specifica...
JavaScript
javascript typed arrays provide a mechanism for accessing raw binary data. memory management memory life cycle and garbage collection in javascript. concurrency model and event loop javascript has a concurrency model based on an "event loop". reference browse the complete javascript reference documentation. standard objects get to know standard built-in objects array, boolean, date,
error, function, json, math, number, object, regexp, string, map, set, weakmap, weakset, and others. expressions and operators learn more about the behavior of javascript's operators instanceof, typeof, new, this, the operator precedence, and more. statements and declarations learn how do-while, for-in, for-of, try-catch, let, var, const, if-else, switch, and more javascript statements and keywords...
Authoring MathML - MathML
yntax to mathml. pros: writing mathematical expressions may only require a standard text editor. many tools are available, some of them are compatible with the classical latex-to-pdf workflow. this gives access to advanced features of latex like macros. cons: this may be harder to use: people must learn a syntax, typos in the code may easily lead to parsing or rendering
errors etc the interface is not user-friendly: only code editor without immediate display of the mathematical expression. none of the syntax has been standardized, making cross-compatibility between converters difficult. even the popular latex language keeps having new packages added. client-side conversion in a web environment, the most obvious method to convert a simple syntax into a do...
<mmultiscripts> - MathML
to a base expression: <mmultiscripts> base (subscript superscript)* [ <mprescripts/> (presubscript presuperscript)* ] </mmultiscripts> after the base expression you can specify a postsubscript and a postsuperscript. prescripts are optional and are separated by the empty tag <mprescripts/> (only one <mprescripts /> element is allowed, otherwise you will get an duplicatemprescripts
error in the
error console and "invalid-markup" in your rendering). in addition you are able to use <none/> as a placeholder for empty scripts (not for the base). see the examples section for a correct usage. attributes class, id, style provided for use with stylesheets. href used to set a hyperlink to a specified uri. mathbackground the background color. you can use #rgb, #rrggbb and html col...
<semantics> - MathML
essions understandable to computer algebra systems. the mathml elements <semantics>, <annotation> and <annotation-xml> are used to combine presentation and content markup and to provide both, layout information and semantic meaning of mathematical expressions. the <semantics> element acts as a container element associating annotations and must have child elements (it will raise an invalid markup
error otherwise). the <annotation> element is the container element containing semantic information in a non-xml format, whereas the <annotation-xml> element contains content in an xml format, e.g. content mathml or openmath. the rules of determining the visible child in a <semantics> element are the following: if no rule other rule applies: by default only the first child is rendered, which is sup...
Web video codec guide - Web media technologies
of these options on the encoded video. compression artifacts artifacts are side effects of a lossy encoding process in which the lost or rearranged data results in visibly negative effects. once an artifact has appeared, it may linger for a while, because of how video is displayed. each frame of video is presented by applying a set of changes to the currently-visible frame. this means that any
errors or artifacts will compound over time, resulting in glitches or otherwise strange or unexpected deviations in the image that linger for a time. to resolve this, and to improve seek time through the video data, periodic key frames (also known as intra-frames or i-frames) are placed into the video file. the key frames are full frames, which are used to repair any damage or artifact residue that's ...
Codecs used by WebRTC - Web media technologies
eiver), specifying the type of media as the input parameter. for example, to determine the supported codecs for video, you can do this: codeclist = rtcrtpsender.getcapabilities("video").codecs; now codeclist is an array of rtcrtpcodeccapability objects, each describing one codec configuration. also present in the list will be entries for retransmission (rtx), redundant coding (red), and forward
error correction (fec). if the connection is in the process of starting up, you can use the icegatheringstatechange event to watch for the completion of ice candidate gathering, then fetch the list. let codeclist = null; peerconnection.addeventlistener("icegatheringstatechange", (event) => { if (peerconnection.icegatheringstate === "complete") { const senders = peerconnection.getsenders(); ...
Guide to streaming audio and video - Web media technologies
streaming https live streaming (hls) is a protocol developed by apple and supported by safari on all of their platforms. hls may also be supported in other environments, although in some cases this support is conditional. for example, because many web sites' mobile-specific content assume that mobile browsers support hls, firefox for android does as well, in order to avoid strange compatibility
errors from occurring due to this assumption being incorrect. the desktop version of android, however, does not support hls. hls uses playlists to allow the user to not only select the media to stream, but also to choose among versions or forms of the same media. for example, hls lets the server stream a video with multiple audio streams which the user can choose from, in order to hear their own langu...
Performance budgets - Web Performance
hthouse score). their primary goal is to prevent regressions, but they can provide insights to forecast trends (i.e. on september, 50% of the budget was spent in a week). additionally, it can uncover development needs (i.e. a large library with smaller alternatives is often picked to solve a common problem). how do i define a performance budget? a budget should include 2 levels: warning.
error. the warning level allows you to be proactive and plan any tech debt, while not blocking development or deploys. the
error level is an upper bound limit, where changes will have a negative and noticeable impact. in order to begin, you need to first measure the devices and connection speeds where your users are coming from (e.g. a ~$200 android device over a 3g connection), using multiple tool...
The building blocks of responsive design - Progressive web apps (PWAs)
or app that changes its user interface depending on the browser or device accessing the site to provide an optimized experience. one approach to this is to create different versions of your site/app for different platforms or browsers and serve them appropriately after detecting which browser or platform is looking at your site. but this is increasingly inefficient: browser sniffing is inherently
error prone, and maintaining multiple copies of your code can turn out to be a nightmare. it is usually much better to create a single version of your code which doesn't care about what browser or platform is accessing the site, but instead uses feature tests to find out what code features the browser supports or what the values of certain browser features are, and then adjusts the code appropriately.
begin - SVG: Scalable Vector Graphics
for that element. all valid events (not necessarily supported by all elements) are defined by the dom and html specifications. those are: focus, blur, focusin, focusout, activate, auxclick, click, dblclick, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, wheel, beforeinput, input, keydown, keyup, compositionstart, compositionupdate, compositionend, load, unload, abort,
error, select, resize, scroll, beginevent, endevent, and repeatevent. an optional offset value as defined in <offset-value> can be appended. <repeat-value> this value defines a qualified repeat event. the element animation start time is defined relative to the time that the repeat event is raised with the specified iteration value. a valid repeat value consists of an element id followed by a dot and...
end - SVG: Scalable Vector Graphics
or that element. all valid events (not necessarily supported by all elements) are defined by the dom and html specifications. those are: focus, blur, focusin, focusout, activate, auxclick, click, dblclick, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, wheel, beforeinput, input, keydown, keyup, compositionstart, compositionupdate, compositionend, load, unload, abort,
error, select, resize, scroll, beginevent, endevent, and repeatevent . an optional offset value as defined in <offset-value> can be appended. <repeat-value> this value defines a qualified repeat event. the element animation end time is defined relative to the time that the repeat event is raised with the specified iteration value. a valid repeat value consists of an element id followed by a dot and ...
keyPoints - SVG: Scalable Vector Graphics
by the path attribute. each progress value in the list corresponds to a value in the keytimes attribute list. if a list of key points is specified, there must be exactly as many values in the keypoints list as in the keytimes list. if there's a semicolon at the end of the value, optionally followed by white space, both the semicolon and the trailing white space are ignored. if there are any
errors in the value specification (i.e. bad values, too many or too few values), then thatʼs an
error. specifications specification status comment svg animations level 2the definition of 'keypoints' in that specification. editor's draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'keypoints' in that specification. re...
keySplines - SVG: Scalable Vector Graphics
the keysplines attribute defines a set of bézier curve control points associated with the keytimes list, defining a cubic bézier function that controls interval pacing. this attribute is ignored unless the calcmode attribute is set to spline. if there are any
errors in the keysplines specification (bad values, too many or too few values), the animation will not occur. four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <circle cx="60" cy="10" r="10"> <animate attributename="cx" dur="4s" calcmode="spline" repeatcount="indefinite" values="60 ; 110 ; 60 ; 10 ; 60" keytimes="0 ; 0.25 ; 0.5 ; 0.75 ; 1" keyspline...
markerHeight - SVG: Scalable Vector Graphics
able yes <length-percentage> this value defines either an absolute or a relative height of the marker. relative values refer to the height specified via the viewbox and preserveaspectratio attributes. <number> this value defines the height of the marker in the units defined by the markerunits attribute. a value of zero disables rendering of the element and negative values are an
error. specifications specification status comment scalable vector graphics (svg) 2the definition of 'markerheight' in that specification. candidate recommendation allowed percentage and number values. scalable vector graphics (svg) 1.1 (second edition)the definition of 'markerheight' in that specification. recommendation initial definition ...
markerWidth - SVG: Scalable Vector Graphics
matable yes <length-percentage> this value defines either an absolute or a relative width of the marker. relative values refer to the width specified via the viewbox and preserveaspectratio attributes. <number> this value defines the width of the marker in the units defined by the markerunits attribute. a value of zero disables rendering of the element and negative values are an
error. specifications specification status comment scalable vector graphics (svg) 2the definition of 'markerwidth' in that specification. candidate recommendation allowed percentage and number values. scalable vector graphics (svg) 1.1 (second edition)the definition of 'markerwidth' in that specification. recommendation initial definition ...
requiredFeatures - SVG: Scalable Vector Graphics
//www.w3.org/tr/svg11/feature#basicfilter the browser supports the <filter>, <feblend>, <fecolormatrix>, <fecomponenttransfer>, <fecomposite>, <feflood>, <fegaussianblur>, <feimage>, <femerge>, <femergenode>, <feoffset>, <fetile>, <fefuncr>, <fefuncg>, <fefuncb> and <fefunca> elements http://www.w3.org/tr/svg11/feature#documenteventsattribute the browser supports the onunload, onabort, on
error, onresize, onscroll and onzoom attributes http://www.w3.org/tr/svg11/feature#graphicaleventsattribute the browser supports the onfocusin, onfocusout, onactivate, onclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout and onload attributes http://www.w3.org/tr/svg11/feature#animationeventsattribute the browser supports the onbegin, onend, onrepeat and onload attributes ...
stemh - SVG: Scalable Vector Graphics
e stemh attribute indicates the horizontal stem width of the font. the stem width refers to the dominant stem of the font. there may be two or more designed widths. for example, the main vertical stems of roman characters will differ from the thin stems on serifed "m" and "n", plus there may be different widths for uppercase and lowercase characters in the same font. also, either by design or by
error, all stems may have slightly different widths. if this attribute is used, the units-per-em must also be used. only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the horizontal stem width of the font. specifications specification status co...
SVG Attribute reference - SVG: Scalable Vector Graphics
tetype, attributename animation timing attributes begin, dur, end, min, max, restart, repeatcount, repeatdur, fill animation value attributes calcmode, values, keytimes, keysplines, from, to, by, autoreverse, accelerate, decelerate animation addition attributes additive, accumulate event attributes animation event attributes onbegin, onend, onrepeat document event attributes onabort, on
error, onresize, onscroll, onunload global event attributes oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncuechange, ondblclick, ondrag, ondragend, ondragenter, ondragexit, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, on
error, onfocus, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onload, onloadeddata, onloadedmetadata, onloadstart, ...
<a> - SVG: Scalable Vector Graphics
ke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes most notably: xlink:title aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<circle> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<ellipse> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<foreignObject> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<g> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<line> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<marker> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<path> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<polygon> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<polyline> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<rect> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<svg> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<symbol> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<text> - SVG: Scalable Vector Graphics
sharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<textPath> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<tspan> - SVG: Scalable Vector Graphics
sharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
<use> - SVG: Scalable Vector Graphics
ke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-
errormessage, aria-expanded, aria-flowto, aria-grabbed, aria-haspopup, aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan,...
SVG documentation index - SVG: Scalable Vector Graphics
the keypoints attribute indicates the simple duration of an animation. 120 keysplines svg, svg attribute the keysplines attribute defines a set of bézier curve control points associated with the keytimes list, defining a cubic bézier function that controls interval pacing. this attribute is ignored unless the calcmode attribute is set to spline. if there are any
errors in the keysplines specification (bad values, too many or too few values), the animation will not occur. 121 keytimes svg, svg attribute the keytimes attribute represents a list of time values used to control the pacing of the animation. each time in the list corresponds to a value in the values attribute list, and defines when the value is used in the animation. 122 ...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
eet not implemented clipping, masking, and compositing change notes overflow respected on outermost <svg> elements inline in html implementation status unknown interactivity change notes tabindex attribute implemented (bug 778654) bounding-box on pointer-events not implemented (bug 945187) load, abort,
error, and unload instead of svgload, svgabort, svg
error, and svgunload not implemented (bug 620002) only structurally external elements and outermost <svg> element fire load events implementation status unknown resize and scroll instead of svgresize and svgscroll implementation status unknown domactivate removed implementation status unknown focusin and ...
Mixed content - Web security
ould use content security policy (csp) to report issues. you could also use an online crawler like ssl-check or missing padlock that will check your website recursively and find links to insecure content. starting in firefox 23, mixed active content is blocked by default (and mixed display content can be blocked by setting a preference). to make it easier for web developers to find mixed content
errors, all blocked mixed content requests are logged to the security pane of the web console, as seen below: to fix this type of
error, all requests to http content should be removed and replaced with content served over https. some common examples of mixed content include javascript files, stylesheets, images, videos, and other media. note: since firefox 55, the loading of mixed content is allow...
Subresource Integrity - Web security
he document in which it’s embedded, browsers additionally check the resource using cross-origin resource sharing (cors), to ensure the origin serving the resource allows it to be shared with the requesting origin. if the script or stylesheet doesn’t match its associated integrity value, the browser must refuse to execute the script or apply the stylesheet, and must instead return a network
error indicating that fetching of that script or stylesheet failed. specifications specification status comment subresource integrity recommendation fetch living standard ...
Transport Layer Security - Web security
mechanisms are in the process of being developed, which will also support http/2. retiring old tls versions to help with working towards a more modern, more secure web, tls 1.0 and 1.1 support will be removed from all major browsers in q1 2020. you'll need to make sure your web server supports tls 1.2 or 1.3 going forward. from version 74 onwards, firefox will return a secure connection failed
error when connecting to servers using the older tls versions (bug 1606734). tls handshake timeout values if the tls handshake starts to become slow or unresponsive for some reason, the user's experience can be affected significantly. to mitigate this problem, modern browsers have implemented handshake timeouts: since version 58, firefox implements a tls handshake timeout with a default value of 3...
Types of attacks - Web security
ers. the victim then retrieves this malicious script from the server when the browser sends a request for data. reflected xss attacks when a user is tricked into clicking a malicious link, submitting a specially crafted form, or browsing to a malicious site, the injected code travels to the vulnerable website. the web server reflects the injected script back to the user's browser, such as in an
error message, search result, or any other response that includes data sent to the server as part of the request. the browser executes the code because it assumes the response is from a "trusted" server which the user has already interacted with. dom-based xss attacks the payload is executed as a result of modifying the dom environment (in the victim’s browser) used by the original client-side scri...
Index - XSLT: Extensible Stylesheet Language Transformations
slt functions, xpath functions, xpath axes found 54 pages: # page tags and summary 1 xslt: extensible stylesheet language transformations landing, web, xslt extensible stylesheet language transformations (xslt) is an xml-based language used, in conjunction with specialized processing software, for the transformation of xml documents. 2 common xslt
errors xslt your server needs to send both the source and the stylesheet with a xml mime type, text/xml or application/xml. to find out the current type, load the file in mozilla and look at the page info. or use a download tool, those usually tell the mime type. 3 index index, reference, xslt found 54 pages: 4 pi parameters xslt no summary! 5 ...
XSLT: Extensible Stylesheet Language Transformations
of xslt concepts, syntax, and programming. xslt tutorial this w3schools tutorial teaches the reader how to use xslt to transform xml documents into other formats, like xhtml. what is xslt? this extensive introduction to xslt and xpath assumes no prior knowledge of the technologies and guides the reader through background, context, structure, concepts and introductory terminology. common xslt
errors this article lists some common problems using xslt in firefox. xslt 2.0 (new) view all... community view mozilla forums... mailing list newsgroup rss feed related topics xml, xpath, xquery ...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
2+ and chrome 57+/latest opera (you can also run wasm code in firefox 47+ by enabling the javascript.options.wasm flag in about:config, or chrome (51+) and opera (38+) by going to chrome://flags and enabling the experimental webassembly flag.) note: if you try to open generated html file (hello.html) directly from your local hard drive (e.g. file://your_path/hello.html), you will end up with an
error message along the lines of both async and sync fetching of the wasm failed. you need to run your html file through an http server (http://) — see how do you set up a local testing server? for more information. if everything has worked as planned, you should see "hello world" output in the emscripten console appearing on the web page, and your browser’s javascript console. congratulations, y...