Search completed in 1.07 seconds.
763 results for "scope":
Your results are loading. Please wait...
Gyroscope.Gyroscope() - Web APIs
a whole number or decimal may be used, the latter for frequencies less than a second. ...
...a whole number or decimal may be used, the latter for frequencies less than a second. ...
...a whole number or decimal may be used, the latter for frequencies less than a second. ...
...mal 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 defines sensors in general. gyroscopethe definition of 'gyroscope' in that specification. candidate recommendation ...
Rhino scopes and contexts
both are required to execute scripts, but they play different roles. simple embeddings of rhino probably won't need any of the information here, but more complicated embeddings can gain performance and flexibility from the techniques described below. contexts the rhino context object is used to store thread-specific information about the execution environment. there should be one and only one context associated with each thread that will be executing javascript. ...
... simply exit the context: context.exit(); these calls will work properly even if there is already a context associated with the current thread. that context will be returned and an internal counter incremented. only when the counter reaches zero will it be disassociated from the thread. remember to put the exit() call in a finally block if you're executing code that could throw an exception. ...
...it the context: context.exit(); these calls will work properly even if there is already a context associated with the current thread. that context will be returned and an internal counter incremented. only when the counter reaches zero will it be disassociated from the thread. remember to put the exit() call in a finally block if you're executing code that could throw an exception. ...
...And 25 more matches
WorkerGlobalScope - Web APIs
the workerglobalscope interface of the web workers api is an interface representing the scope of any worker. workers have no browsing context; this scope contains the information usually conveyed by window objects — in this case event handlers, the console or the associated workernavigator object. each workerglobalscope has its own event loop. this interface is usually specialized by each worker type: dedicatedworkerglobalscope for dedicated workers, sharedworkerglobalscope for shared workers, and serviceworkerglobalscope for serviceworker. the self property returns the specialized scope for each context. properties this interface inherits properties from the eventtarget interface and windoworworkerglobalscope and windoweventhandlers mixins. ...
...ach worker type: dedicatedworkerglobalscope for dedicated workers, sharedworkerglobalscope for shared workers, and serviceworkerglobalscope for serviceworker. the self property returns the specialized scope for each context. properties this interface inherits properties from the eventtarget interface and windoworworkerglobalscope and windoweventhandlers mixins. standard properties workerglobalscope.navigator read only returns the workernavigator associated with the worker. it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. workerglobalscope.self read only returns a reference to the workerglobalscope itself. ...
...globalscope and windoweventhandlers mixins. standard properties workerglobalscope.navigator read only returns the workernavigator associated with the worker. it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. workerglobalscope.self read only returns a reference to the workerglobalscope itself. most of the time it is a specific scope like dedicatedworkerglobalscope, sharedworkerglobalscope or serviceworkerglobalscope. workerglobalscope.location read only returns the workerlocation associated with the worker. it is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. ...
...And 14 more matches
DedicatedWorkerGlobalScope - Web APIs
the dedicatedworkerglobalscope object (the worker global scope) is accessible through the self keyword. some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the javascript reference. see also: functions available to workers. properties this interface inherits properties from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.name read only the name that the worker was (optionally) given when it was created using the worker() constructor. this is mainly useful for debugging purposes. ...
...erties from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.name read only the name that the worker was (optionally) given when it was created using the worker() constructor. this is mainly useful for debugging purposes. properties inherited from workerglobalscope workerglobalscope.self returns an object reference to the dedicatedworkerglobalscope object itself. workerglobalscope.console read only returns the console associated with the worker. workerglobalscope.location read only returns the workerlocation associated with the worker. ...
...from workerglobalscope workerglobalscope.self returns an object reference to the dedicatedworkerglobalscope object itself. workerglobalscope.console read only returns the console associated with the worker. workerglobalscope.location read only returns the workerlocation associated with the worker. workerlocation is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. workerglobalscope.navigator read only returns the workernavigator associated with the worker. workernavigator is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. ...
...And 10 more matches
ServiceWorkerGlobalScope - Web APIs
additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the fetch() method, can be used. ...
...that the serviceworker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state. once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. ...
...persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state. once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the fetch() method, can be used. this interface inherits from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. <div id="interfacediagram" ...
...And 10 more matches
itemscope - HTML: Hypertext Markup Language
itemscope is a boolean global attribute that defines the scope of associated metadata. specifying the itemscope attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element. a related attribute, itemtype, is used to specify the valid url of a vocabulary (such as schema.org) that describes the item and its properties context. in each of the following examples, the vocabulary is from schema.org. every html element may have an itemscope attribute specified. an itemscope element that does not have an associated itemtype must have an associated itemref. note: find more about itemtype attributes at http://schema.org/thing simple example html the following example specifies the itemscope attribute. the example specifies the ite...
...mscope attribute specified. an itemscope element that does not have an associated itemtype must have an associated itemref. note: find more about itemtype attributes at http://schema.org/thing simple example html the following example specifies the itemscope attribute. the example specifies the itemtype as "http://schema.org/movie", and specifies three related itemprop attributes. <div itemscope itemtype="http://schema.org/movie"> <h1 itemprop="name">avatar</h1> <span>director: <span itemprop="director">james cameron</span> (born august 16, 1954)</span> <span itemprop="genre">science fiction</span> <a href="https://youtu.be/0ay1xikx7by" itemprop="trailer">trailer</a> </div> structured data the following table shows the structured data from the preceding example. item...
... itemtype="http://schema.org/movie"> <h1 itemprop="name">avatar</h1> <span>director: <span itemprop="director">james cameron</span> (born august 16, 1954)</span> <span itemprop="genre">science fiction</span> <a href="https://youtu.be/0ay1xikx7by" itemprop="trailer">trailer</a> </div> structured data the following table shows the structured data from the preceding example. itemscope itemtype movie itemprop (itemprop name) (itemprop value) itemprop director james cameron itemprop genre science fiction itemprop name avatar itemprop https://youtu.be/0ay1xikx7by trailer itemscope id attributes when you specify the itemscope attribute for an element, a new item is created. the item consists o...
...And 10 more matches
SharedWorkerGlobalScope - Web APIs
the sharedworkerglobalscope object (the sharedworker global scope) is accessible through the self keyword. some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the javascript reference. see the complete list of functions available to workers. properties this interface inherits properties from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.name read only the name that the sharedworker was (optionally) given when it was created using the sharedworker() constructor. this is mainly useful for debugging purposes. ...
...nherits properties from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.name read only the name that the sharedworker was (optionally) given when it was created using the sharedworker() constructor. this is mainly useful for debugging purposes. sharedworkerglobalscope.applicationcache read only this property returns the applicationcache object for the worker (see using the application cache). properties inherited from workerglobalscope workerglobalscope.self returns an object reference to the dedicatedworkerglobalscope object itself. ...
...ng the sharedworker() constructor. this is mainly useful for debugging purposes. sharedworkerglobalscope.applicationcache read only this property returns the applicationcache object for the worker (see using the application cache). properties inherited from workerglobalscope workerglobalscope.self returns an object reference to the dedicatedworkerglobalscope object itself. workerglobalscope.console read only returns the console associated with the worker. workerglobalscope.location read only returns the workerlocation associated with the worker. workerlocation is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. workerglobalscope.navigator read only returns the workernavigator associated with the worker. workernavigator ...
...And 7 more matches
:scope - CSS: Cascading Style Sheets
Web › CSS › :scope
the :scope css pseudo-class represents elements that are a reference point for selectors to match against. /* selects a scoped element */ :scope { background-color: lime; } currently, when used in a stylesheet, :scope is the same as :root, since there is not at this time a way to explicitly establish a scoped element. when used from a dom api such as queryselector(), queryselectorall(), matches(), or element.closest(), :scope matches the element on which the method was called. syntax :scope examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's called. javascript let paragraph = document.getelementbyid("para"); let output = document.getelementbyid("output"); if (paragraph.
...t.closest(), :scope matches the element on which the method was called. syntax :scope examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's called. javascript let paragraph = document.getelementbyid("para"); let output = document.getelementbyid("output"); if (paragraph.matches(":scope")) { output.innertext = "yep, the element is its own scope as expected!"; } html <p id="para"> this is a paragraph. it is not an interesting paragraph. sorry about that. </p> <p id="output"></p> result direct children a situation where the :scope pseudo-class prove to be useful is when you need to get direct descendant of an already retrieved element. javascript var context = documen...
...ed!"; } html <p id="para"> this is a paragraph. it is not an interesting paragraph. sorry about that. </p> <p id="output"></p> result direct children a situation where the :scope pseudo-class prove to be useful is when you need to get direct descendant of an already retrieved element. ...
...And 6 more matches
JS_GetScopeChain
obsolete since javascript 1.8.7this 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. retrieves the scope chain for the javascript code currently running in a given context. js_getscopechain has been removed in spidermonkey 1.8.7 with no identical replacement. when you only used this function to retrieve the scope chain's global, then you can use the function js_getglobalforscopechain. syntax jsobject * js_getscopechain(jscontext *cx); name type description cx jscontext * the context to query. description js_getscopechain returns the first jsobject on the scope chain for the javascript code currently running in the given context, cx. the...
...n js_getglobalforscopechain. syntax jsobject * js_getscopechain(jscontext *cx); name type description cx jscontext * the context to query. description js_getscopechain returns the first jsobject on the scope chain for the javascript code currently running in the given context, cx. the ecmascript standard, ecma 262-3 §10, describes execution contexts and scope chains. a scope chain is a sequence of objects whose properties are searched whenever a script or function refers to a variable. ...
.... description js_getscopechain returns the first jsobject on the scope chain for the javascript code currently running in the given context, cx. the ecmascript standard, ecma 262-3 §10, describes execution contexts and scope chains. a scope chain is a sequence of objects whose properties are searched whenever a script or function refers to a variable. these objects represent the lexical scope of the currently executing statement or expression, not the call stack, so they include: the variable objects of any enclosing functions or let statements or expressions, and any objects selected by enclosing with statements, in order from the most-nested scope outward; lastly the global object against which the function was created. note that cx's current global object, as set by js_setglo...
...And 5 more matches
WindowOrWorkerGlobalScope - Web APIs
the windoworworkerglobalscope mixin describes several features common to the window and workerglobalscope interfaces. each of these interfaces can, of course, add more features in addition to the ones listed below. note: windoworworkerglobalscope is a mixin and not an interface; you can't actually create an object of type windoworworkerglobalscope. properties these properties are defined on the windoworworkerglobalscope mixin, and implemented by window and workerglobalscope. windoworworkerglobalscope.caches read only returns the cachestorage object associated with the current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. ...
...balscope. properties these properties are defined on the windoworworkerglobalscope mixin, and implemented by window and workerglobalscope. windoworworkerglobalscope.caches read only returns the cachestorage object associated with the current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. windoworworkerglobalscope.crossoriginisolated read only returns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage() call. windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object. ...
... custom responses to requests. windoworworkerglobalscope.crossoriginisolated read only returns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage() call. windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously 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 origin of the global scope, serialized as a string. ...
...And 4 more matches
Gyroscope - Web APIs
Web › API › Gyroscope
the gyroscope interface of the sensor apis provides on each reading the angular velocity of the device along all three axes. to use this sensor, the user must grant permission to the 'gyroscope' device sensor through the permissions api. 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. constructor gyroscope.gyroscope() creates a new gyroscope object. properties gyroscope.x read only returns a double, containing the angular velocity of the device along the device's x axis. gyroscope.y read only returns a double, containing the angular velocity of the device along the device's y axis. ...
...ever be shown to a user. see feature-policy for implementation instructions. constructor gyroscope.gyroscope() creates a new gyroscope object. properties gyroscope.x read only returns a double, containing the angular velocity of the device along the device's x axis. gyroscope.y read only returns a double, containing the angular velocity of the device along the device's y axis. gyroscope.z read only returns a double, containing the angular velocity of the device along the device's z axis. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...the device's x axis. gyroscope.y read only returns a double, containing the angular velocity of the device along the device's y axis. gyroscope.z read only returns a double, containing the angular velocity of the device along the device's z axis. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...And 3 more matches
PRThreadScope
global threads are scheduled by the host os and compete with all other threads on the host os for resources. ...
... global threads are scheduled by the host os and compete with all other threads on the host os for resources. ...
... global threads are scheduled by the host os and compete with all other threads on the host os for resources. ...
...And 2 more matches
JS_EnterLocalRootScope
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. enter a local root scope. syntax jsbool js_enterlocalrootscope(jscontext *cx); name type description cx jscontext * pointer to the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description scoped local root management allows native functions, getter/setters, etc. ...
...quest. in a js_threadsafe build, the caller must be in a request on this jscontext. description scoped local root management allows native functions, getter/setters, etc. to avoid calling js_addroot and js_removeroot to manage global roots temporarily. js_addroot roots a variable, ensuring that whatever the variable points to at any given moment is protected from gc. by contrast, local root scopes protect newly-created objects, doubles, and strings. there is no need to tell the js engine about each variable that may point to such a value. calling js_enterlocalrootscope and js_leavelocalrootscope around the body of the native hook protects each object, double, and string created using the same jscontext from gc. for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsv...
...s. there is no need to tell the js engine about each variable that may point to such a value. calling js_enterlocalrootscope and js_leavelocalrootscope around the body of the native hook protects each object, double, and string created using the same jscontext from gc. for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) return js_false; // this function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx. even if js_gc is // called, these new values will not be collected. ...
...And 2 more matches
DedicatedWorkerGlobalScope.onmessage - Web APIs
when a message is sent to the worker using the worker.postmessage method. syntax self.onmessage = function() { ... }; example the following code snippet shows creation of a worker object using the worker() constructor. messages are passed to the worker when the value inside the form input first changes. a worker.onmessage handler is also present, to deal with messages are passed back from the worker. ...
... present, to deal with messages are passed back from the worker. ...
... living standard ...
...And 2 more matches
Gyroscope.x - Web APIs
Web › API › Gyroscope › x
the x read-only property of the gyroscope interface returns a double precision integer containing the angular velocity of the device along the its x axis. 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. syntax var x = gyroscope.x value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...s 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. syntax var x = gyroscope.x value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...re 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. syntax var x = gyroscope.x value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...And 2 more matches
Gyroscope.y - Web APIs
Web › API › Gyroscope › y
the y read-only property of the gyroscope interface returns a double precision integer containing the angular velocity of the device along the its y axis. 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. syntax var y = gyroscope.y value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...s 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. syntax var y = gyroscope.y value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...re 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. syntax var y = gyroscope.y value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...And 2 more matches
Gyroscope.z - Web APIs
Web › API › Gyroscope › z
the z read-only property of the gyroscope interface returns a double precision integer containing the angular velocity of the device along the its z axis. 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. syntax var z = gyroscope.z value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...s 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. syntax var z = gyroscope.z value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...re 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. syntax var z = gyroscope.z value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
...And 2 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
the setinterval() method, offered on the window and worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. it returns an interval id which uniquely identifies the interval, so you can remove it later by calling clearinterval(). this method is defined by the windoworworkerglobalscope mixin. syntax var intervalid = scope.setinterval(func, [delay, arg1, arg2, ...]); var intervalid = scope.setinterval(function[, delay]); var intervalid = scope.setinterval(code, [delay]); parameters func a function to be executed every delay milliseconds. the function is not passed any arguments, and no return value is expected. code an optional syntax allows you to include a string instead of a function, which is compiled and executed every d...
... arguments to setinterval() in the first syntax does not work in internet explorer 9 and earlier. if you want to enable this functionality on that browser, you must use a polyfill (see the callback arguments section). return value the returned intervalid is a numeric, non-zero value which identifies the timer created by the call to setinterval(); this value can be passed to windoworworkerglobalscope.clearinterval() to cancel the timeout. it may be helpful to be aware that setinterval() and settimeout() share the same pool of ids, and that clearinterval() and cleartimeout() can technically be used interchangeably. for clarity, however, you should try to always match them to avoid confusion when maintaining your code. note: the delay argument is converted to a signed 32-bit integer. this eff...
...ty = bbackwards ? 'hidden' : 'visible'; } } var fadeinout = new minidaemon(document.getelementbyid('sample_div'), opacity, 300, 8); </script> </body> </html> view this example in action usage notes the setinterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. you can cancel the interval using windoworworkerglobalscope.clearinterval(). if you wish to have your function called once after the specified delay, use windoworworkerglobalscope.settimeout(). delay restrictions it's possible for intervals to be nested; that is, the callback for setinterval() can in turn call setinterval() to start another interval running, even though the first one is still going. to mitigate the potential impact this can have on per...
...And 2 more matches
WorkerGlobalScope.self - Web APIs
the self read-only property of the workerglobalscope interface returns a reference to the workerglobalscope itself. most of the time it is a specific scope like dedicatedworkerglobalscope, sharedworkerglobalscope, or serviceworkerglobalscope. syntax var selfref = self; value a global scope object (differs depending on the type of worker you are dealing with, as indicated above). ...
...ence to the workerglobalscope itself. most of the time it is a specific scope like dedicatedworkerglobalscope, sharedworkerglobalscope, or serviceworkerglobalscope. syntax var selfref = self; value a global scope object (differs depending on the type of worker you are dealing with, as indicated above). ...
...globalscope, or serviceworkerglobalscope. syntax var selfref = self; value a global scope object (differs depending on the type of worker you are dealing with, as indicated above). ...
...And 2 more matches
nsIWorkerScope
onmessage nsidomeventlistener a listener object to be called when a message is posted on the port. ...
... onmessage nsidomeventlistener a listener object to be called when a message is posted on the port. ...
...hen the worker stops running. onmessage nsidomeventlistener a listener object to be called when a message is posted on the port. the message is in the event's data member. methods close() allows the worker to terminate itself. if a listener has been established by setting the value of the onclose attribute, it gets called. void close(); parameters none. postmessage() posts a message to the scope's parent worker object. void postmessage( in domstring amessage, in nsiworkermessageport amessageport optional ); parameters amessage the message to post. it will be stored as the data member in the event. amessageport optional specifies the message port onto which to post the message; if not specified, the default port is used. see also using web workers nsiworkermessageevent nsiworkerme...
...void postmessage( in domstring amessage, in nsiworkermessageport amessageport optional ); parameters amessage the message to post. it will be stored as the data member in the event. amessageport optional specifies the message port onto which to post the message; if not specified, the default port is used. see also using web workers nsiworkermessageevent nsiworkermessageport nsiworkerglobalscope nsiabstractworker nsiworker ...
DedicatedWorkerGlobalScope.close() - Web APIs
note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
... note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
... note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
... note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
ServiceWorkerGlobalScope: install event - Web APIs
the install event of the serviceworkerglobalscope interface is fired when a serviceworkerregistration acquires a new serviceworkerregistration.installing worker. ...
... the install event of the serviceworkerglobalscope interface is fired when a serviceworkerregistration acquires a new serviceworkerregistration.installing worker. ...
...}; specifications specification status comment service workersthe definition of 'install' in that specification. working draft ...
...}; specifications specification status comment service workersthe definition of 'install' in that specification. working draft ...
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
} self.addeventlistener('pushsubscriptionchange', function() { ... ...
...} self.addeventlistener('pushsubscriptionchange', function() { ... ...
...owser refresh the push subscription. previously, it was defined as the event interface that is fired whenever a push subscription has been invalidated (or is about to become so). this offers an opportunity to resubscribe in order to continue receiving push messages, if desired. this might happen if, for example, the push service sets an expiration time a subscription. syntax serviceworkerglobalscope.onpushsubscriptionchange = function() { ... } self.addeventlistener('pushsubscriptionchange', function() { ... }) example self.addeventlistener('pushsubscriptionchange', function() { // do something, usually resubscribe to push and // send the new subscription details back to the // server via xhr or fetch }); specifications specification status comment push api...
...something, usually resubscribe to push and // send the new subscription details back to the // server via xhr or fetch }); specifications specification status comment push apithe definition of 'onpushsubscriptionchange' in that specification. working draft initial definition (note: this event is specified in the push api, but accessed through serviceworkerglobalscope.) ...
ServiceWorkerRegistration.scope - Web APIs
working draft initial definition. ...
... working draft initial definition. ...
... working draft initial definition. ...
...ace returns a unique identifier for a service worker registration. the service worker must be on the same origin as the document that registers the serviceworker. note: this feature is available in web workers. syntax var swscope = serviceworkerregistration.scope; specifications specification status comment service workersthe definition of 'serviceworkerregistration.scope' in that specification. working draft initial definition. ...
SharedWorkerGlobalScope.close() - Web APIs
note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
... note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
... note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
... note: there is also a way to stop the worker from the main thread: the worker.terminate method. specifications specification status comment html living standardthe definition of 'close()' in that specification. ...
WindowOrWorkerGlobalScope.fetch() - Web APIs
a fetch() promise only rejects when a network error is encountered (which is usually when there’s a permissions issue or similar). ...
... a fetch() promise only rejects when a network error is encountered (which is usually when there’s a permissions issue or similar). a fetch() promise does not reject on http errors (404, etc.). ...
...hing 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. windoworworkerglobalscope is implemented by both window and workerglobalscope, which means that the fetch() method is available in pretty much any context in which you might want to fetch resources. a fetch() promise only rejects when a network error is encountered (which is usually when there’s a permissions issue or similar). a fetch() promise does not reject on http errors (404, etc.). instead, a then() handler must check the response.ok and/or response.status proper...
...n object literal as headers in init. const myinit = { method: 'get', headers: { 'content-type': 'image/jpeg' }, mode: 'cors', cache: 'default' }; let myrequest = new request('flowers.jpg', myinit); specifications specification status comment fetchthe definition of 'fetch()' in that specification. living standard defined in a windoworworkerglobalscope partial in the newest spec. fetchthe definition of 'fetch()' in that specification. living standard initial definition credential management level 1 working draft adds federatedcredential or passwordcredential instance as a possible value for init.credentials. ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
code an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. this syntax is not recommended for the same reasons that make using eval() a security risk. ...
... code an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. this syntax is not recommended for the same reasons that make using eval() a security risk. ...
... code an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. this syntax is not recommended for the same reasons that make using eval() a security risk. ...
...ers including internet explorer, chrome, safari, and firefox store the delay as a 32-bit signed integer internally. this causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.settimeout()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html living standardthe definition of 'windowtimers.settimeout()' in that specification. living standard initial definition (dom level 0) ...
WorkerGlobalScope.performance - Web APIs
the performance read-only property of the workerglobalscope interface returns a performance object to be used on the worker. not all performance properties and methods are available to web workers. this property is read only . syntax var perfobj = self.performance; return value a performance object. ...
...to be used on the worker. not all performance properties and methods are available to web workers. this property is read only . syntax var perfobj = self.performance; return value a performance object. ...
...properties and methods are available to web workers. this property is read only . syntax var perfobj = self.performance; return value a performance object. ...
... ...
Global scope - MDN Web Docs Glossary: Definitions of Web-related terms
in a programming environment, the global scope is the scope that contains, and is visible in, all other scopes. in client-side javascript, the global scope is generally the web page inside which all the code is being executed. ...
... in a programming environment, the global scope is the scope that contains, and is visible in, all other scopes. in client-side javascript, the global scope is generally the web page inside which all the code is being executed. ...
... in a programming environment, the global scope is the scope that contains, and is visible in, all other scopes. in client-side javascript, the global scope is generally the web page inside which all the code is being executed. ...
JS_LeaveLocalRootScopeWithResult
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. leave a local root scope, transferring the result value to the next enclosing root scope. syntax void js_leavelocalrootscopewithresult(jscontext *cx, jsval rval); name type description cx jscontext * pointer to the context. this must be the same context that was passed to js_enterlocalrootscope. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. rval jsval the result value that should remain protected from garbage collection. description see js_enterlocalrootscope for an explanation of local root scopes. the pro...
...otherwise, the value is stored in an internal per-jscontext slot. this slot is rooted, but the value will eventually be overwritten by some other operation, and it is very difficult to figure out exactly when this will happen—or more to the point, guarantee that it won't happen in the time it takes some specific chunk of code to run. ...
...rwise, the value is stored in an internal per-jscontext slot. this slot is rooted, but the value will eventually be overwritten by some other operation, and it is very difficult to figure out exactly when this will happen—or more to the point, guarantee that it won't happen in the time it takes some specific chunk of code to run. in any case, all other newborn values protected by the local root scope, aside from rval, become subject to garbage collection. see also bug 519949 bug 803907 ...
nsIWorkerGlobalScope
ook up information about itself, as well as to control itself. ...
...itself, as well as to control itself. ...
...pports 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. ...
Using the Debugger map scopes feature - Firefox Developer Tools
this feature is useful when debugging source-mapped code. it enables you to see the variables from the original source. it’s also possible to inspect variables from the generated scopes (e.g., a bundle file with all concatenated module files). let's take a look at how this works. if you want to follow along, use this example. open the example page and then open the debugger using tools > web developer > debugger (or press ctrl + i and then select the debugger). select the "bundle.js" file in the sources panel on the left and then set a breakpoint at line 102 in the increment function. ...
... > web developer > debugger (or press ctrl + i and then select the debugger). select the "bundle.js" file in the sources panel on the left and then set a breakpoint at line 102 in the increment function. when you click the increment button on the page and hit the breakpoint, an additional section is added to the right-hand panel below the call stack to display variables mapped from the original scope, like this: as useful as this is, it would be even nicer if you could view the original code (before it was packages into the "bundle.js" file. right-click on the source code and the context menu now includes an option to jump to original location as shown below. click jump to original location. the debugger opens the file "increment.js" so you can view the original code. notice t...
...ight-click on the source code and the context menu now includes an option to jump to original location as shown below. click jump to original location. the debugger opens the file "increment.js" so you can view the original code. notice that your breakpoint is set here in the original code as it was in the corresponding line in the "bundle.js" file. and, since map has been checked in the scopes panel, you also see variable symbols from the original code. using this feature is expensive in terms of resources, but it certainly makes your life easier when you have to debug source code that has been packaged webpack or a similar tool. ...
AudioWorkletGlobalScope.registerProcessor - Web APIs
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. ...
...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. ...
...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. ...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
syntax postmessage(amessage, transferlist); parameters amessage the object to deliver to the main thread; this will be in the data field in the event delivered to the worker.onmessage handler. ...
... syntax postmessage(amessage, transferlist); parameters amessage the object to deliver to the main thread; this will be in the data field in the event delivered to the worker.onmessage handler. ...
... onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); console.log('posting message back to main script'); postmessage(workerresult); } in the main script, onmessage would have to be called on a worker object, whereas inside the worker script you just need onmessage because the worker is effectively the global scope (dedicatedworkerglobalscope). for a full example, see ourbasic dedicated worker example (run dedicated worker). note: postmessage() can only send a single object at once. as seen above, if you want to pass multiple values you can send an array. specifications specification status comment html living standardthe definition of 'dedicatedworkerglobalscope.postmessage()'...
HTMLStyleElement.scoped - Web APIs
the htmlstyleelement.scoped property is a boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true). by default it contains the value of the scoped content attribute. ...
... the htmlstyleelement.scoped property is a boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true). by default it contains the value of the scoped content attribute. ...
... the htmlstyleelement.scoped property is a boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true). by default it contains the value of the scoped content attribute. ...
ServiceWorkerGlobalScope: activate event - Web APIs
the activate event of the serviceworkerglobalscope interface is fired when a serviceworkerregistration acquires a new serviceworkerregistration.active worker. bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.onactivate examples the following snippet shows how you could use an activate event handler to upgrade a cache. ...
...orkerglobalscope interface is fired when a serviceworkerregistration acquires a new serviceworkerregistration.active worker. bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.onactivate examples the following snippet shows how you could use an activate event handler to upgrade a cache. ...
...ould use an activate event handler to upgrade a cache. globalscope.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); you can also set up the event handler using the serviceworkerglobalscope.onactivate property: globalscope.onactivate = function(event) { ... }; specifications specification status comment service workersthe definition of 'activate' in that specification. working draft ...
ServiceWorkerGlobalScope.onpush - Web APIs
} self.addeventlistener('push', function(pushevent) { ... }) example the following example takes data from a pushevent and displays it on all of the service worker's clients. ...
...} self.addeventlistener('push', function(pushevent) { ... }) example the following example takes data from a pushevent and displays it on all of the service worker's clients. ...
... ...
ServiceWorkerGlobalScope.onsync - Web APIs
} self.addeventlistener('sync', function(syncevent) { ... ...
...} self.addeventlistener('sync', function(syncevent) { ... ...
...} self.addeventlistener('sync', function(syncevent) { ... ...
WindowOrWorkerGlobalScope.atob() - Web APIs
return value an ascii string containing decoded data from encodeddata. ...
...n use the btoa() method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the atob() method to decode the data again. for example, you can encode, transmit, and decode control characters such as ascii values 0 through 31. for use with unicode or utf-8 strings, see the note on "unicode strings" in the page for btoa(). syntax var decodeddata = scope.atob(encodeddata); parameters encodeddata a binary string contains an base64 encoded data. return value an ascii string containing decoded data from encodeddata. exceptions domexception (name: invalidcharactererror) throws if encodeddata is not valid base64. example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); //...
... 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 html living standardthe definition of 'windoworworkerglobalscope.atob()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html 5.1the definition of 'windowbase64.atob()' in that specification. recommendation snapshot of html living standard. no change. html5the definition of 'windowbase64.atob()' in that specification. recommendation snapshot of html living standa...
WindowOrWorkerGlobalScope.btoa() - Web APIs
return value an ascii string containing the base64 representation of stringtoencode. exceptions invalidcharactererror the string contained a character that did not fit in a single byte. ...
...d ascii string from a binary string (i.e., a string object in which each character in the string is treated as a byte of binary data). you can use this method to encode data which may otherwise cause communication problems, transmit it, then use the atob() method to decode the data again. for example, you can encode control characters such as ascii values 0 through 31. syntax var encodeddata = scope.btoa(stringtoencode); parameters stringtoencode the binary string to encode. return value an ascii string containing the base64 representation of stringtoencode. exceptions invalidcharactererror the string contained a character that did not fit in a single byte. see "unicode strings" below for more detail. example const encodeddata = window.btoa('hello, world'); // encode a string...
...st decoded = atob(encoded); const original = frombinary(decoded); console.log(original); // ☸☹☺☻☼☾☿ polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.btoa()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html 5.1the definition of 'windowbase64.btoa()' in that specification. recommendation snapshot of html living standard. no change. html5the definition of 'windowbase64.btoa()' in that specification. recommendation snapshot of html living standa...
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
this id was returned by the corresponding call to settimeout(). it's worth noting that the pool of ids used by settimeout() and setinterval() are shared, which means you can technically use cleartimeout() and clearinterval() interchangeably. however, for clarity, you should avoid doing so. example run the script below in the context of a web page and click on the page once. you'll see a message popping up in a second. ...
... html living standardthe definition of 'cleartimeout()' in that specification. living standard ...
...eoutid); } }; window.onclick = function() { alarm.setup(); }; notes passing an invalid id to cleartimeout() silently does nothing; no exception is thrown. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.cleartimeout()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html living standardthe definition of 'cleartimeout()' in that specification. living standard ...
WorkerGlobalScope.location - Web APIs
the location read-only property of the workerglobalscope interface returns the workerlocation associated with the worker. it is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. syntax var locationobj = self.location; value a workerlocation object. ...
...ion object, mostly a subset of the location for browsing scopes, but adapted to workers. syntax var locationobj = self.location; value a workerlocation object. ...
...browsing scopes, but adapted to workers. syntax var locationobj = self.location; value a workerlocation object. ...
WorkerGlobalScope.navigator - Web APIs
the navigator read-only property of the workerglobalscope interface returns the workernavigator associated with the worker. it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. syntax var navigatorobj = self.navigator; value a workernavigator object. ...
...the worker. it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. syntax var navigatorobj = self.navigator; value a workernavigator object. ...
...ostly a subset of the navigator for browsing scopes, but adapted to workers. syntax var navigatorobj = self.navigator; value a workernavigator object. ...
Feature-Policy: gyroscope - HTTP
'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
... 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. ...
scope - Web app manifests
type string mandatory no the scope member is a string that defines the navigation scope of this web application's application context. it restricts what web pages can be viewed while the manifest is applied. if the user navigates outside the scope, it reverts to a normal web page inside a browser tab or window. if the scope is a relative url, the base url will be the url of the manifest. ...
...y no the scope member is a string that defines the navigation scope of this web application's application context. it restricts what web pages can be viewed while the manifest is applied. if the user navigates outside the scope, it reverts to a normal web page inside a browser tab or window. if the scope is a relative url, the base url will be the url of the manifest. ...
...navigation scope of this web application's application context. it restricts what web pages can be viewed while the manifest is applied. if the user navigates outside the scope, it reverts to a normal web page inside a browser tab or window. if the scope is a relative url, the base url will be the url of the manifest. examples if the scope is relative, the manifest url is used as a base url: "scope": "/app/" the following scope limits navigation to the current site: "scope": "https://example.com/" finally, the following example limits navigation to a subdirectory of the current site: "scope": "https://example.com/subdirectory/" specification specification status comment feedback web app manifestthe definition of 'scope' in that specification. ...
Local scope - MDN Web Docs Glossary: Definitions of Web-related terms
local scope is a characteristic of variables that makes them local (i.e., the variable name is only bound to its value within a scope which is not the global scope). ...
... local scope is a characteristic of variables that makes them local (i.e., the variable name is only bound to its value within a scope which is not the global scope). ...
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
the current context of execution. the context in which values and expressions are "visible" or can be referenced. if a variable or other expression is not "in the current scope," then it is unavailable for use. scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa. a function serves as a closure in javascript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions. for instance, the following is invalid: function examplefunction() { var x = "declared inside function"; // x can only be used in examplefunction console.log("inside function"); console.log(x); } console.log(x); // causes error however, ...
... console.log(x); } console.log(x); // causes error however, the following code is valid due to the variable being declared outside the function, making it global: var x = "declared outside function"; examplefunction(); function examplefunction() { console.log("inside function"); console.log(x); } console.log("outside function"); console.log(x); learn more general knowledge scope (computer science) on wikipedia ...
JS_GetGlobalForScopeChain
obsolete since jsapi 25this 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 article covers features introduced in spidermonkey 1.8.5 returns the global object for the active function on the context. renamed to js::currentglobalornull. syntax jsobject * js_getglobalforscopechain(jscontext *cx); name type description cx jscontext * the context for which to return the global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_getglobalforscopechain() returns the global object for whatever function is currently running on the context. in other words, it returns the glob...
... name type description cx jscontext * the context for which to return the global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_getglobalforscopechain() returns the global object for whatever function is currently running on the context. in other words, it returns the global object on the current scope chain. if there is no javascript running on the context, this returns the context's global, i.e., js_getglobalobject(cx). note that js_getglobalobject() and context globals are becoming obsolete. see also js_getglobalforobject js::currentglobalornull bug 899245 ...
JS_LeaveLocalRootScope
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. leave a local root scope. syntax void js_leavelocalrootscope(jscontext *cx); name type description cx jscontext * pointer to the context. this must be the same context passed to js_enterlocalrootscope(). requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description see js_enterlocalrootscope for an explanation of local root scopes. leaving a nested local root scope causes all objects created since the matching js_enterlocalrootscope call to become subject to garbage collection. that is, they are not transferred to the enclosi...
...cope(). requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description see js_enterlocalrootscope for an explanation of local root scopes. leaving a nested local root scope causes all objects created since the matching js_enterlocalrootscope call to become subject to garbage collection. that is, they are not transferred to the enclosing local root scope. however, js_leavelocalrootscopewithresult provides a way to transfer one value to the enclosing local root scope. see also bug 519949 bug 803907 ...
nsMsgSearchScope
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl [scriptable, uuid(6e893e59-af98-4f62-a326-0f00f32147cd)] interface nsmsgsearchscope { const nsmsgsearchscopevalue offlinemail = 0; const nsmsgsearchscopevalue offlinemailfilter = 1; const nsmsgsearchscopevalue onlinemail = 2; const nsmsgsearchscopevalue onlinemailfilter = 3; /// offline news, base table, no body or junk const nsmsgsearchscopevalue localnews = 4; const nsmsgsearchscopevalue news = 5; const nsmsgsearchscopevalue newsex = 6; const nsmsgsearchscopevalue ldap = 7; const nsmsgsearchscopevalue localab = 8; const nsmsgsearchscopevalue allsearchablegroups = 9; const nsmsgsearchscopevalue newsfilter = 10; const nsmsgsearchscopevalue localaband = 11; const nsmsgsearchscopeval...
...lue news = 5; const nsmsgsearchscopevalue newsex = 6; const nsmsgsearchscopevalue ldap = 7; const nsmsgsearchscopevalue localab = 8; const nsmsgsearchscopevalue allsearchablegroups = 9; const nsmsgsearchscopevalue newsfilter = 10; const nsmsgsearchscopevalue localaband = 11; const nsmsgsearchscopevalue ldapand = 12; // imap and news, searched using local headers const nsmsgsearchscopevalue onlinemanual = 13; /// local news + junk const nsmsgsearchscopevalue localnewsjunk = 14; /// local news + body const nsmsgsearchscopevalue localnewsbody = 15; /// local news + junk + body const nsmsgsearchscopevalue localnewsjunkbody = 16; }; ...
AudioWorkletGlobalScope - Web APIs
as the global execution context is shared across the current baseaudiocontext, it's possible to define any other variables and perform any actions allowed in worklets — apart from defining audioworkletprocessor-derived classes. properties currentframe read only returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. ...
... working draft ...
ServiceWorkerGlobalScope: contentdelete event - Web APIs
the contentdelete event of the serviceworkerglobalscope interface is fired when an item is removed from the indexed content via the user agent. bubbles no cancelable no interface contentindexevent event handler property oncontentdelete examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item. ...
... event handler to remove cached content related to the deleted index item. self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { return promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); you can also set up the event handler using the serviceworkerglobalscope.ondelete property: self.oncontentdelete = (event) => { ... }; specifications specification status comment unknownthe definition of 'contentdelete' in that specification. unknown initial definition. ...
ServiceWorkerGlobalScope.onactivate - Web APIs
}; examples the following snippet shows how you could use an activate event handler to upgrade a cache. ...
...}; examples the following snippet shows how you could use an activate event handler to upgrade a cache. ...
ServiceWorkerGlobalScope.oncontentdelete - Web APIs
}; examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item. ...
...}; examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item. ...
ServiceWorkerGlobalScope.onfetch - Web APIs
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. ...
...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. ...
ServiceWorkerGlobalScope.onnotificationclick - Web APIs
the serviceworkerglobalscope.onnotificationclick property is an event handler called whenever the notificationclick event is dispatched on the serviceworkerglobalscope object, that is when a user clicks on a displayed notification spawned by serviceworkerregistration.shownotification(). 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: ',...
... ...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
example while self.skipwaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state. ...
... example while self.skipwaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state. ...
SharedWorkerGlobalScope: connect event - Web APIs
the event object is a messageevent. ...
...the event object is a messageevent. ...
WindowOrWorkerGlobalScope.caches - Web APIs
this object enables functionality such as storing assets for offline use, and generating custom responses to requests. syntax var mycachestorage = self.caches; // or just caches value a cachestorage object. example the following example shows how you'd use a cache in a service worker context to store assets offline. ...
... service workers working draft initial definition. ...
WindowOrWorkerGlobalScope.clearInterval() - Web APIs
the clearinterval() method of the windoworworkerglobalscope mixin cancels a timed, repeating action which was previously established by a call to setinterval(). syntax scope.clearinterval(intervalid) parameters intervalid the identifier of the repeated action you want to cancel. this id was returned by the corresponding call to setinterval(). it's worth noting that the pool of ids used by setinterval() and settimeout() are shared, which means you can technically use clearinterval() and cleartimeout() interchangeably. however, for clarity, you should avoid doing so. return value undefined example see the setinterval() examples. ...
...the pool of ids used by setinterval() and settimeout() are shared, which means you can technically use clearinterval() and cleartimeout() interchangeably. however, for clarity, you should avoid doing so. return value undefined example see the setinterval() examples. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.clearinterval()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html living standardthe definition of 'clearinterval()' in that specification. living standard ...
WindowOrWorkerGlobalScope.indexedDB - Web APIs
the indexeddb read-only property of the windoworworkerglobalscope mixin provides a mechanism for applications to asynchronously access the capabilities of indexed databases. syntax var idbfactory = self.indexeddb; value an idbfactory object. example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open('todolist'); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; } } specifications specification status comment indexed database api draftthe definition of 'indexeddb' in that specification. ...
... indexed database api 2.0the definition of 'indexeddb' in that specification. recommendation initial definition. ...
WorkerGlobalScope.console - Web APIs
the console read-only property of the workerglobalscope interface returns a console object providing access to the browser console for the worker. syntax var consoleobj = self.console; value a console object. example this property allows you to have access to a browser console for debugging purposes, inside a worker. so for example you could call console.log('test'); inside a worker (which would basically be the equivalent of self.console.log('test');, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), to return a test message out to the browser console. if you are calling console.log() from a dedicatedworkerglobalscope or other worker scope that acts on a single loaded window, that tab's web console will receive the logs. however, i...
...t');, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), to return a test message out to the browser console. if you are calling console.log() from a dedicatedworkerglobalscope or other worker scope that acts on a single loaded window, that tab's web console will receive the logs. however, if you are calling console.log() from a sharedworkerglobalscope, the global browser console will receive the logs. specifications not yet part of any specification. ...
WorkerGlobalScope.importScripts() - Web APIs
syntax self.importscripts('foo.js'); self.importscripts('foo.js', 'bar.js', ...); parameters a comma-separated list of domstring objects representing the scripts to be imported. these paths are relative to html document base url. return value none. exceptions networkerror imported scripts were not served with a valid javascript mime type (i.e. text/javascript). ...
...h 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 called from inside the worker's inner scope. specifications specification status comment html living standardthe definition of 'importscripts()' in that specification. living standard ...
PR_GetThreadScope
gets the scoping of the current thread. syntax #include <prthread.h> prthreadscope pr_getthreadscope(void); returns a value of type prthreadscope indicating whether the thread is local or global. ...
JS_ClearScope
obsolete since jsapi 18this 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. remove all properties associated with an object. syntax void js_clearscope(jscontext *cx, jsobject *obj); name type description cx jscontext * the context in which to clear the object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object from which to delete all properties. description js_clearscope removes all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. properties belonging to objects on obj's prototype chain are not affected. to remove a s...
nsIMsgSearchScopeTerm
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchscopeterm.idl [scriptable, uuid(934672c3-9b8f-488a-935d-87b4023fa0be)] interface nsimsgsearchscopeterm : nsisupports { nsiinputstream getinputstream(in nsimsgdbhdr ahdr); void closeinputstream(); readonly attribute nsimsgfolder folder; readonly attribute nsimsgsearchsession searchsession; }; ...
DedicatedWorkerGlobalScope: message event - Web APIs
when the parent sends a message using worker.postmessage()). ...
DedicatedWorkerGlobalScope: messageerror event - Web APIs
the messageerror event is fired on a dedicatedworkerglobalscope object when it receives a message that can't be deserialized. bubbles no cancelable no interface messageevent event handler property onmessageerror examples listen for messageerror using addeventlistener(): // inside worker.js self.addeventlistener('messageerror', (event) => { self.postmessage('error receiving message'); console.error(event); }); the same, but using the onmessageerror event handler property: // inside worker.js self.onmessageerror = (event) => { self.postmessage('error receiving message'); console.error(event); }; specifications specification status html living standard living standard ...
DedicatedWorkerGlobalScope.name - Web APIs
the name read-only property of the dedicatedworkerglobalscope interface returns the name that the worker was (optionally) given when it was created. this is the name that the worker() constructor can pass to get a reference to the dedicatedworkerglobalscope. syntax var nameobj = self.name; value a domstring. example if a worker is created using a constructor with a name option: var myworker = new worker("worker.js", { name : "myworker" }); the dedicatedworkerglobalscope will now have a name of "myworker", returnable by running self.name from inside the worker. specifications specification status comment html living standardthe definition of 'name' in that specification. living standard ...
DedicatedWorkerGlobalScope.onmessageerror - Web APIs
note: this feature is available in web workers. syntax onmessageerror = function() { ... ...
ServiceWorkerGlobalScope.caches - Web APIs
the caches read-only property of the serviceworkerglobalscope interface returns the cachestorage object associated with the service worker. syntax var mycachestorage = self.caches; value a cachestorage object. specifications specification status comment service workersthe definition of 'serviceworkerglobalscope.caches' in that specification. working draft initial definition. ...
ServiceWorkerGlobalScope.clients - Web APIs
syntax swclients = self.clients value the clients object associated with the specific worker. ...
ServiceWorkerGlobalScope: message event - Web APIs
controlled pages can use the serviceworker.postmessage() method to send messages to service workers. the service worker can optionally send a response back via the client.postmessage(), corresponding to the controlled page. bubbles no cancelable no interface extendablemessageevent event handler property onmessage examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function. ...
ServiceWorkerGlobalScope.oninstall - Web APIs
the oninstall property of the serviceworkerglobalscope interface is an event handler fired whenever an install event occurs (when the service worker installs). this happens before activation. syntax serviceworkerglobalscope.oninstall = function(event) { ... }; examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery...
ServiceWorkerGlobalScope.onmessage - Web APIs
the onmessage property of the serviceworkerglobalscope interface is an event handler fired whenever a message event occurs — when incoming messages are received. note: service workers define the extendable event to allow extending the lifetime of the event. for the message event, service workers use the extendablemessageevent interface which extends the extendableevent interface. note: messages received from service worker contexts (e.g. as the event object of onmessage) are represented by messageevent objects in modern browsers, for consistency with other web messaging features. (they used to be represented by serviceworkermessageevent objects, which have now been deprecated.) syntax serviceworkerglobalscope.onmessage = function(extendablemessageevent) { ... }; example self.addeve...
ServiceWorkerGlobalScope: push event - Web APIs
bubbles no cancelable no interface pushevent event handler property onpush example this example sets up a handler for push events that takes json data, parses it, and dispatches the message for handling based on information contained within the message. ...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
this may occur if the subscription was refreshed by the browser, but it may also happen if the subscription has been revoked or lost. bubbles no cancelable no interface pushsubscriptionchangeevent event handler property onpushsubscriptionchange usage notes although examples demonstrating how to share subscription related information with the application server tend to use fetch(), this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example. ...
ServiceWorkerGlobalScope.registration - Web APIs
the registration read-only property of the serviceworkerglobalscope interface returns a reference to the serviceworkerregistration object, which represents the service worker's registration. syntax serviceworkerregistration = self.registration value a serviceworkerregistration object. specifications specification status comment service workersthe definition of 'serviceworkerglobalscope.registration' in that specification. working draft initial definition. ...
SharedWorkerGlobalScope.applicationCache - Web APIs
important: application cache is deprecated as of firefox 44, and is no longer available in insecure contexts from firefox 60 onwards (bug 1354175, currently nightly/beta only). don't use it to make offline websites — consider using service workers instead. the applicationcache read-only property of the sharedworkerglobalscope interface returns the applicationcache object for the worker (see using the application cache). syntax var nameobj = self.applicationcache; value an applicationcache. example if a shared worker has an appcache associated with it, you can return a reference to the cache using self.applicationcache from inside the shared worker. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the dat...
SharedWorkerGlobalScope.name - Web APIs
the name read-only property of the sharedworkerglobalscope interface returns the name that the sharedworker was (optionally) given when it was created. this is the name that the sharedworker() constructor can pass to get a reference to the sharedworkerglobalscope. syntax var nameobj = self.name; value a domstring. example if a shared worker is created using a constructor with a name option: var myworker = new sharedworker("worker.js", { name : "mysharedworker" }); the sharedworkerglobalscope will now have a name of "mysharedworker", returnable by running self.name from inside the shared worker. specifications specification status comment html living standardthe definition of 'name' in that specification. living standard ...
SharedWorkerGlobalScope.onconnect - Web APIs
syntax onconnect = function() { ... }; examples this example shows a shared worker file — when a connection to the worker occurs from a main thread via a messageport, the onconnect event handler fires. the event object is a messageevent. ...
WindowOrWorkerGlobalScope.crossOriginIsolated - Web APIs
this value is dependant on any cross-origin-opener-policy and cross-origin-embedder-policy headers present in the response. ...
WindowOrWorkerGlobalScope.isSecureContext - Web APIs
the issecurecontext read-only property of the windoworworkerglobalscope interface returns a boolean indicating whether the current context is secure (true) or not (false). syntax var isitsecure = self.issecurecontext; // or just issecurecontext value a boolean. specifications specification status comment secure contextsthe definition of 'windoworworkerglobalscope.issecurecontext' in that specification. candidate recommendation initial definition. ...
WindowOrWorkerGlobalScope.origin - Web APIs
the origin read-only property of the windoworworkerglobalscope interface returns the origin of the global scope, serialized as a string. syntax var myorigin = self.origin; // or just origin value a usvstring. examples executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message onmessage = function() { console.log(self.origin); }; if the origin is not a scheme/host/port tuple (say you are trying to run it locally, i.e. via file:// url), origin will return the string "null". specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.origin' in that specification. living standard initial definition. ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
in our microtask guide. the importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. see using microtasks in javascript with queuemicrotask() for more details. microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. queuemicrotask() is exposed on the windoworworkerglobalscope mixin. syntax scope.queuemicrotask(function); parameters function a function to be executed when the browser engine determines it is safe to call your code. enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. return value undefined. examples self.queuemicrotask(() => { // function contents here }) taken f...
WorkerGlobalScope.close() - Web APIs
the close() method of the workerglobalscope interface discards any tasks queued in the workerglobalscope's event loop, effectively closing this particular scope. syntax self.close(); example if you wanted to close your worker instance from inside the worker itself, you could call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope. note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
WorkerGlobalScope.dump() - Web APIs
in your terminal, in firefox only. this is the same as firefox's window.dump, but for workers. syntax dump('my message\n'); parameters a domstring containing the message you want to send. returns void. example to write an output from your worker to your computer's terminal, you first have to run an instance of firefox started from your command line/terminal. for example, on mac os x you'd run it using something like this (assuming you are inside the applications folder): ./firefox.app/contents/macos/firefox-bin -profile /tmp -no-remote now go into about:config and enable the browser.dom.window.dump.enabled pref. ...
WorkerGlobalScope: languagechange event - Web APIs
the languagechange event is fired at the global scope object when the user's preferred language changes. bubbles no cancelable no interface event event handler onlanguagechange examples you can use the languagechange event in an addeventlistener method: worker.addeventlistener('languagechange', function() { console.log('languagechange event detected!'); }); or use the onlanguagechange event handler property: worker.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; specification specification status html living standardthe definition of 'languagechange' in that specification. living standard ...
WorkerGlobalScope.onclose - Web APIs
this non-standard event handler was only implemented by a few browsers and has been removed from all or nearly all of them. syntax self.onclose = function() { ... ...
WorkerGlobalScope.onerror - Web APIs
the onerror property of the workerglobalscope interface represents an eventhandler to be called when the error event occurs and bubbles through the worker. syntax self.onerror = function() { ... }; example the following code snippet shows an onerror handler set inside a worker: self.onerror = function() { console.log('there is an error inside your worker!'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onerror' in that specification. living standard ...
WorkerGlobalScope.onlanguagechange - Web APIs
the onlanguagechange property of the workerglobalscope interface represents an eventhandler to be called when the languagechange event occurs and bubbles through the worker. syntax self.onlanguagechange = function() { ... }; example the following code snippet shows an onlanguagechange handler set inside a worker: self.onlanguagechange = function() { console.log('your preferred language settings have been changed'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onlanguagechange' in that specification. living standard ...
WorkerGlobalScope.onoffline - Web APIs
the onoffline property of the workerglobalscope interface represents an eventhandler to be called when the offline event occurs and bubbles through the worker. syntax self.onoffline = function() { ... }; example the following code snippet shows an onoffline handler set inside a worker: self.onoffline = function() { console.log('your worker is now offline'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onoffline' in that specification. living standard ...
WorkerGlobalScope.ononline - Web APIs
the ononline property of the workerglobalscope interface represents an eventhandler to be called when the online event occurs and bubbles through the worker. syntax self.ononline = function() { ... }; example the following code snippet shows an ononline handler set inside a worker: self.ononline = function() { console.log('your worker is now online'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.ononline' in that specification. living standard ...
Index - Web APIs
Web › API › Index
diotracklist: removetrack event event the removetrack event is fired when a track is removed from an audiotracklist. 202 audioworklet api, audio, audioworklet, experimental, interface, reference, web audio api, worklet the audioworklet interface of the web audio api is used to supply custom audio processing scripts. ...
...dioworklet, experimental, interface, reference, web audio api, worklet the audioworklet interface of the web audio api is used to supply custom audio processing scripts. user-supplied code is run in the audioworkletglobalscope global execution context in a separate web audio rendering thread along with other nodes, allowing for zero-latency audio processing. 203 audioworkletglobalscope api, audioworkletglobalscope, experimental, interface, reference, web audio api the audioworkletglobalscope interface of the web audio api represents a global execution context for user-supplied code, which defines custom audioworkletprocessor-derived classes. each baseaudiocontext has a single audioworklet available under the audioworklet property, which runs its code in a single audio...
...ioworkletglobalscope, experimental, interface, reference, web audio api the audioworkletglobalscope interface of the web audio api represents a global execution context for user-supplied code, which defines custom audioworkletprocessor-derived classes. each baseaudiocontext has a single audioworklet available under the audioworklet property, which runs its code in a single audioworkletglobalscope. 204 audioworkletglobalscope.registerprocessor api, audio, audioworkletglobalscope, audioworkletprocessor, method, reference, web audio api the registerprocessor method of the audioworkletglobalscope interface registers a class constructor derived from audioworkletprocessor interface under a specified name. 205 audioworkletnode api, audio, audioworkletnode, exp...
...And 117 more matches
filter - CSS: Cascading Style Sheets
Web › CSS › filter
efines the value of the standard deviation to the gaussian function, or how many pixels on the screen blend into each other, so a larger value will create more blur. the lacuna value for interpolation is 0. the parameter is specified as a css length, but does not accept percentage values. ...
... or how many pixels on the screen blend into each other, so a larger value will create more blur. the lacuna value for interpolation is 0. the parameter is specified as a css length, but does not accept percentage values. ...
...er value will create more blur. the lacuna value for interpolation is 0. the parameter is specified as a css length, but does not accept percentage values. ...
...And 31 more matches
nsIXPConnect
obsolete since gecko 2...
... obsolete since gecko 2.0 jsval getxowforobject(in jscontextptr ajscontext, in jsobjectptr aparent, in jsobjectptr awrappedobj); native code only! obsolete since gecko 2...
... obsolete since gecko 2.0 jsval getxowforobject(in jscontextptr ajscontext, in jsobjectptr aparent, in jsobjectptr awrappedobj); native code only! ...
...And 29 more matches
Bytecode Descriptions
or. 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 referenceerror. 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 referenceerror 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 call .tostring()/.va...
...ing concatenation, while ++ always does numeric addition. more fundamentally, the result of evaluating x-- is tonumeric(old value of x), a value that the sequence getlocal "x"; one; sub; setlocal "x" does not give us. format: jof_ic other expressions globalthis stack: ⇒ this push the global this value. not to be confused with the globalthis property on the global. this must be used only in scopes where this refers to the global this. newtarget stack: ⇒ new.target push the value of new.target. the result is a constructor or undefined. this must be used only in scripts where new.target is allowed: non-arrow function scripts and other scripts that have a non-arrow function script on the scope chain. implements: getnewtarget. dynamicimport stack: moduleid ⇒ promise dynamic import o...
...ion. implements: instantiatefunctionobject, evaluation for functionexpression, and so on. format: jof_object lambdaarrow operands: (uint32_t funcindex) stack: newtarget ⇒ arrowfn push a new arrow function. newtarget matters only if the arrow function uses the expression new.target. it should be the current value of new.target, so that the arrow function inherits new.target from the enclosing scope. (if new.target is illegal here, the value doesn't matter; use null.) the function indicated by funcindex must be an arrow function. format: jof_object setfunname operands: (functionprefixkind prefixkind) stack: fun, name ⇒ fun set the name of a function. fun must be a function object. name must be a string, int32 value, or symbol (like the result of jsop::toid). implements: setfunctionname,...
...And 18 more matches
itemprop - HTML: Hypertext Markup Language
perties forms an item. property values are either a string or a url and can be associated with a very wide range of elements including <audio>, <embed>, <iframe>, <img>, <link>, <object>, <source> , <track>, and <video>. examples the example below shows the source for a set of elements marked up with itemprop attributes, followed by a table showing the resulting structured data. ...
... itemprop trailer ../movies/avatar-theatrical-trailer.html properties properties have values that are either a string or a url. when a string value is a url, it is expressed using the <a> element and its href attribute, the <img> element and its src attribute, or other elements that link to or embed external resources. ...
... its src attribute, or other elements that link to or embed external resources. three properties with values that are strings <div itemscope> <p>my name is <span itemprop="name">neil</span>.</p> <p>my band is called <span itemprop="band">four parts water</span>.</p> <p>i am <span itemprop="nationality">british</span>.</p> </div> one property, "image", whose value is a url <div itemscope> <img itemprop="image" src="google-logo.png" alt="google"> </div> when a string value can't be easily read and understood by a person (e.g., a long string of numbers and letters), it can be displayed using the value attribute of the data element, with the more easily-understood-by-a human-version given in the element's contents (which is not part of the structured data - see example below). ...
...And 17 more matches
nsIMsgSearchSession
the nsimsgsearchsession interface allows you to create and manipulate search sessions within thunderbird. to create an instance, use: var searchsession = components.classes["@mozilla.org/messenger/searchsession;1"] .createinstance(components.interfaces.nsimsgsearchsession); to use the instance append search terms, set the scope, and then call search(). ...
...gsearchsession interface allows you to create and manipulate search sessions within thunderbird. to create an instance, use: var searchsession = components.classes["@mozilla.org/messenger/searchsession;1"] .createinstance(components.interfaces.nsimsgsearchsession); to use the instance append search terms, set the scope, and then call search(). ...
...te and manipulate search sessions within thunderbird. to create an instance, use: var searchsession = components.classes["@mozilla.org/messenger/searchsession;1"] .createinstance(components.interfaces.nsimsgsearchsession); to use the instance append search terms, set the scope, and then call search(). ...
...And 15 more matches
Anonymous Content - Archive of obsolete content
no knowledge of their anonymous children. the anonymous content is not accessible via the childnodes list for the bound element, nor is it accessible using firstchild/nextsibling to iterate over the children of the bound element. the anonymous content is accessible only through special methods like getanonymousnodes and getanonymouselementbyattribute. ...
...cessible only through special methods like getanonymousnodes and getanonymouselementbyattribute. anonymous content introduces the concept of scope to nodes within a document. because anonymous content elements can also have bindings attached that generate their own anonymous content, this scoping can be taken to an arbitrary level of nesting. explicit content is said to be at the document-level scope. anonymous content nodes are in their own binding-level scopes. binding scopes are determined by the bound element that contains the binding responsible for the generation of the anonymous nodes. ...
...nts can also have bindings attached that generate their own anonymous content, this scoping can be taken to an arbitrary level of nesting. explicit content is said to be at the document-level scope. anonymous content nodes are in their own binding-level scopes. binding scopes are determined by the bound element that contains the binding responsible for the generation of the anonymous nodes. the scope of an element can be determined using the getbindingparent method on the documentxbl interface. see section 3 for more information. this method returns the bound element in the enclosing scope that is responsible for the anonymous node. if invoked on an element at the document-level scope, it returns null. dom methods that can be invoked on elements (e.g., getelementsbytagname) will only see nod...
...And 14 more matches
Functions - JavaScript
s are one of the fundamental building blocks in javascript. a function in javascript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. to use a function, you must define it somewhere in the scope from which you wish to call it. see also the exhaustive reference chapter about javascript functions to get to know the details. defining functions function declarations a function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: the name of the function. a list of parameters to the function, enclosed in parentheses and ...
... function and specifies what to do when the function is called. calling the function actually performs the specified actions with the indicated parameters. for example, if you define the function square, you could call it as follows: square(5); the preceding statement calls the function with an argument of 5. the function executes its statements and returns the value 25. functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code), as in this example: console.log(square(5)); /* ... */ function square(n) { return n * n } the scope of a function is the function in which it is declared (or the entire program, if it is declared at the top level). note: this works only when defining the function using the above syntax (i.e...
...here a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. it turns out that functions are themselves objects—and in turn, these objects have methods. (see the function object.) one of these, the apply() method, can be used to achieve this goal. function scope 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. 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. a function defined ins...
...And 12 more matches
How to embed the JavaScript engine
jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event loop js::rootedobject global(cx, js_newglobalobject(cx, &global_class, nullptr)); if (!global) return 1; ...
... js_enumeratestub, js_resolvestub, js_convertstub, }; int main(int argc, const char *argv[]) { jsruntime *rt = js_newruntime(8l * 1024 * 1024, js_use_helper_threads); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
...quest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
...And 11 more matches
Components.utils.exportFunction
this function provides a safe way to expose a function from a privileged scope to a less-privileged scope. in this way privileged code, such as an extension, can share code with less-privileged code like a normal web page script. a function exported from privileged to less-privileged code can be called from the less privileged code's context. the function has access to its surrounding closure just as if it were being called in the privileged context. the exported function does not have to be added to the less privileged code's global window object: it can be exported to any object in the target scope. exportfunction() is made available as a global in sandboxes which have the wantexporthelpers option set in the sandbox() constructor. this includes add-on sdk content scripts. to ...
...this does not have to be the global window object: it could be any other object in the target window, or an object created by the caller. options : object optional parameter that supplies additional options. ...
...s a global in sandboxes which have the wantexporthelpers option set in the sandbox() constructor. this includes add-on sdk content scripts. to understand what happens if the functions you export accept arguments, see exporting functions that take arguments below. syntax components.utils.exportfunction(func, targetscope[, options]); parameters func : function the function to export. targetscope : object the object to attach the function to. this does not have to be the global window object: it could be any other object in the target window, or an object created by the caller. options : object optional parameter that supplies additional options. the following options are currently defined: defineas: determines the name of the function in targetscope. if this is omitted, you need t...
...And 11 more matches
Functions — reusable blocks of code - Learn web development
another essential concept in coding is functions, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. in this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. objective: to understand the fundamental concepts behind javascript functions. where do i find functions? in javascript, you'll find functions everywhere. in fact, we've been using functions all the way through the course so far; we've just not b...
...me kind of default behavior. as an example, the array join() function's parameter is optional: let myarray = ['i', 'love', 'chocolate', 'frogs']; let madeastring = myarray.join(' '); // returns 'i love chocolate frogs' let madeastring = myarray.join(); // returns 'i,love,chocolate,frogs' if no parameter is included to specify a joining/delimiting character, a comma is used by default. function scope and conflicts let's talk a bit about scope — a very important concept when dealing with functions. when you create a function, the variables and other things defined inside the function are inside their own separate scope, meaning that they are locked away in their own separate compartments, unreachable from code outside the functions. the top level outside all your functions is called the gl...
... javascript is set up like this for various reasons — but mainly because of security and organization. ...
...And 10 more matches
let - JavaScript
the let statement declares a block-scoped local variable, optionally initializing it to a value. 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 let var1 [= value1] [, var2 [= value2]] [, ..., varn [= valuen]; parameters var1, var2, …, varn the names of the variable or variables to declare. each must be a legal javascript identifier. value1, value2, …, valuen optional for each variable declared, you may optionally specify its initial value to any legal javascript expression. ...
..., var2 [= value2]] [, ..., varn [= valuen]; parameters var1, var2, …, varn the names of the variable or variables to declare. each must be a legal javascript identifier. value1, value2, …, valuen optional for each variable declared, you may optionally specify its initial value to any legal javascript expression. description let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. the other difference between var and let is that the latter is initialized to a value only when a parser evaluates it (see below). just like const the let does not create properties of the window object when declared globa...
..., or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. the other difference between var and let is that the latter is initialized to a value only when a parser evaluates it (see below). just like const the let does not create properties of the window object when declared globally (in the top-most scope). an explanation of why the name "let" was chosen can be found here. examples scoping rules variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks. ...
...And 10 more matches
Index
référence(2), spidermonkey js::callargs is helper class encapsulating access to the callee, this value, arguments, and argument count for a function call. 30 js::clonefunctionobject jsapi reference, reference, référence(2), spidermonkey js::clonefunctionobject creates a new function object from funobj. the new object has the same code and argument list as funobj. if scopechain is supplied, it uses scopechain as its enclosing scope. if scopechain is omitted, it creates a new function object in cx's global. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. 31 js::compile jsapi reference, reference, référence(2), spidermonkey js::compile compiles a script, srcbuf, c...
...reference, reference, référence(2), spidermonkey js::createerror 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 the current scope chain. 38 js::deflatestringtoutf8buffer jsapi reference, refere, spidermonkey js::deflatestringtoutf8buffer encodes src as utf8. the caller must either ensure dst has enough space to encode the entire string, or pass the length of the buffer as dstlenp. in which case, the function will encode characters from the string until the buffer is exhausted. does not write the null te...
...ting-point quiet not-a-number (nan). 40 js::doublevalue jsapi reference, reference, référence(2), spidermonkey js::doublevalue converts a c floating-point number of type double to js::value, the type of javascript values. 41 js::evaluate jsapi reference, reference, référence(2), spidermonkey js::evaluate compiles and executes a script in the specified scope, obj or scopechain. 42 js::falsevalue jsapi reference, reference, référence(2), spidermonkey js::falsevalue creates a js::value that represents the javascript value false. 43 js::float32value jsapi reference, reference, référence(2), spidermonkey js::float32value converts a c floating-point number of type float to js::value, the type of javascript val...
...And 9 more matches
nsIPushService
ervice supports the push api implementation in firefox, and can be used directly from privileged code to create system subscriptions. implemented by @mozilla.org/push/service;1 as a service: const pushservice = components.classes["@mozilla.org/push/service;1"] .getservice(components.interfaces.nsipushservice); method overview void subscribe(in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback); void getsubscription(in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback); void unsubscribe(in domstring scope, in nsiprincipal principal, in nsiunsubscriberesultcallback callback); methods subscribe() creates a push subscription. void subscribe( in domstring scop...
... principal the nsiprincipal to associate with the subscription. privileged code should pass the system principal. callback the callback to call when the nsipushsubscription is created. ...
... principal the nsiprincipal to associate with the subscription. privileged code should pass the system principal. ...
...And 9 more matches
HTML table advanced features and accessibility - Learn web development
dentify all headers and use them to make programmatic associations between those headers and the cells they relate to. the combination of column and row headers will identify and interpret the data in each cell so that screenreader users can interpret the table similarly to how a sighted user does. we already covered headers in our previous article — see adding headers with <th> elements. ...
... associations between those headers and the cells they relate to. the combination of column and row headers will identify and interpret the data in each cell so that screenreader users can interpret the table similarly to how a sighted user does. we already covered headers in our previous article — see adding headers with <th> elements. ...
...ibute a new topic for this article is the scope attribute, which can be added to the <th> element to tell screenreaders exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example? ...
...And 8 more matches
Property cache
ngth; name; setprop, bindname, and setname; callprop and callname; and {inc,dec}name and name{inc,dec}. elem opcodes do not use it. nor do {inc,dec}prop or prop{inc,dec}. nor do operations such as add that only need to look up a property (.tostring) in unusual cases. throughout this article, phrases such as "own property" should be taken to refer to the low-level representation of properties in scopes and shape chains. in the case of shared permanent properties, this differs from the notion of "own property" seen by scripts via object.prototype.hasownproperty. shape native objects have a shape, a 24-bit unsigned integer such that: basic layout guarantee — if at time t0 the object x has shape s and at time t1 the object y has shape s, and no shape-regenerating gc occurred, then y at ...
...lve hooks or non-native lookup ops, and at t1 the object x has shape s, the object x' has shape s', and no shape-regenerating gc occurred, then at t1 the lookup for x.p still finds the same property on x'. ...
...e-regenerating gc occurred, then at t1 the lookup for x.p still finds the same property on x'. ...
...And 8 more matches
Index
Mozilla › Tech › XPCOM › Index
ace is defined at js/xpconnect/idl/xpccomponents.idl. 31 components.utils.sandbox needsmarkupwork, reference, référence(2), xpcom:language bindings, xpconnect components.utils.sandbox is used to create a sandbox object for use with evalinsandbox(). 32 components.utils.cloneinto this function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope. it returns a reference to the clone: 33 components.utils.createobjectin add-ons, developing mozilla, extensions, javascript, reference, référence(2), xpcom:language bindings, xpconnect components.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment. 34 ...
...t's guaranteed to behave predictably. this is useful for privileged code, such as add-on code, to access variables and apis defined in web content. 36 components.utils.exportfunction api, add-ons, components, extensions, language bindings, method, mozilla, non-standard, reference, webextensions, xpcom this function provides a safe way to expose a function from a privileged scope to a less-privileged scope. 37 components.utils.forcegc needscontent, xpcom, xpcom:language bindings, xpconnect components.utils.forcegc lets scripts force a garbage collection cycle. the mozilla javascript engine will perform garbage collection automatically when the javascript heap grows beyond a certain size. this mechanism doesn't account for any native (c++) xpcom object...
...bindings, xpconnect this method was introduced in firefox 3 and is used for obtaining a weak reference for an object. to obtain the object reference, you have to call get() on the resulting object. 40 components.utils.import needscontent, xpcom:language bindings, xpconnect components.utils.import was introduced in firefox 3 and is used for sharing code between different scopes easily. for example, you can import xpcomutils.jsm to avoid copy/pasting long xpcom component registration boilerplate in your component files. 41 components.utils.importglobalproperties imports various objects into a system scope. 42 components.utils.isxraywrapper when privileged javascript in gecko accesses objects belonging to less-privileged code (...
...And 8 more matches
nsIMsgSearchCustomTerm
* attributes in searchattribentrytable in nsmsgsearchterm.cpp * are not allowed. */ readonly attribute acstring id; name /// name to display in term list. this should be localized. ...
...attribentrytable in nsmsgsearchterm.cpp * are not allowed. */ readonly attribute acstring id; name /// name to display in term list. this should be localized. ...
...n nsmsgsearchterm.cpp * are not allowed. */ readonly attribute acstring id; name /// name to display in term list. this should be localized. ...
...And 8 more matches
ServiceWorkerContainer.register() - Web APIs
the register() method of the serviceworkercontainer interface creates or updates a serviceworkerregistration for the given scripturl. if successful, a service worker registration ties the provided script url to a scope, which is subsequently used for navigation matching. you can call this method unconditionally from the controlled page. i.e., you don't need to first check whether there's an active registration. 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. syntax serviceworkercontainer.register(scripturl, options) .then(function(serviceworkerregistration) { ... }); parameters scripturl the url of the servi...
...a scope that is narrower than the default. syntax serviceworkercontainer.register(scripturl, options) .then(function(serviceworkerregistration) { ... }); parameters scripturl the url of the service worker script. the registered service worker file needs to have a valid javascript mime type. options optional an object containing registration options. currently available options are: scope: a usvstring representing a url that defines a service worker's registration scope; that is, what range of urls a service worker can control. this is usually a relative url. it is relative to the base url of the application. by default, the scope value for a service worker registration is set to the directory where the service worker script is located. see the examples section for more informatio...
...the service worker code in this case, if included in example.com/index.html, will control example.com/index.html, as well as pages underneath it, like example.com/product/description.html. ...
...And 8 more matches
Functions and classes available to Web Workers - Web APIs
in addition to the standard javascript set of functions (such as string, array, object, json, etc), there are a variety of functions available from the dom to workers. this article provides a list of those. workers run in another global context, dedicatedworkerglobalscope, different from the current window. by default, methods and properties of window are not available to them, but dedicatedworkerglobalscope, like window, implements windowtimers and windowbase64. ...
...nt window. by default, methods and properties of window are not available to them, but dedicatedworkerglobalscope, like window, implements windowtimers and windowbase64. ...
...s and properties of window are not available to them, but dedicatedworkerglobalscope, like window, implements windowtimers and windowbase64. ...
...And 8 more matches
itemtype - HTML: Hypertext Markup Language
google and other major search engines support the schema.org vocabulary for structured data. this vocabulary defines a standard set of type names and property names. for example, musicevent indicates a concert performance, with startdate and location properties specifying the concert's key details. ...
...d set of unique tokens which are case-sensitive, each is a valid and absolute url, and all defined to use the same vocabulary. the attribute's value must have at least one token. the item types must all be types defined in applicable specifications (such as schema.org), and must all be defined to use the same vocabulary. the itemtype attribute can only be specified on elements which have an itemscope attribute specified. the itemid attribute can only be specified on elements which have both an itemscope attribute and an itemtype attribute specified. they must only be specified on elements with an itemscope attribute, whose itemtype attribute specifies a vocabulary not supporting global identifiers for items, as defined by that vocabulary's specification. the exact meaning of a global identi...
... meaning of a global identifier is determined by the vocabulary's specification. it is left to such specifications to define whether multiple items of the same global identifier (whether on the same page or different pages) are allowed to exist, and what processing rules for that vocabulary are, with respect to handling the case of multiple items with the same id. ...
...And 8 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
ively. boolean operations such as && (logical and), || (logical or), and ! (logical not) are supported; see below. variables new variables in javascript are declared using one of three keywords: let, const, or var. let allows you to declare block-level variables. the declared variable is available from the block it is enclosed in. let a; let name = 'simon'; the following is an example of scope with a variable declared with let: // myletvariable 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; //...
...l 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 variable declared with var: // myvarvariable *is* visible out here for (var myvarvariable = 0; myvarvariable < 5; myvarvariable++) { // myvarvariable is visible to the whole function } // myvarvariable *is* visible out here if you declare a variable without assigning any value to it, its type is undefined. an important difference between javascript and other languages like java is ...
... myvarvariable *is* visible out here for (var myvarvariable = 0; myvarvariable < 5; myvarvariable++) { // myvarvariable is visible to the whole function } // myvarvariable *is* visible out here if you declare a variable without assigning any value to it, its type is undefined. an important difference between javascript and other languages like java is that in javascript, blocks do not have scope; only functions have a scope. so if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function. however, starting with ecmascript 2015, let and const declarations allow you to create block-scoped variables. operators javascript's numeric operators are +, -, *, / and % which is the remainder operator (which is t...
...And 8 more matches
Closures - JavaScript
in javascript, closures are created every time a function is created, at function creation time. ...
...hich is declared in its parent function. this is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. the word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. nested functions have access to variables declared in their outer scope. closure consider the following code example: function makefunc() { var name = 'mozilla'; function displayname() { alert(name); } return displayname; } var myfunc = makefunc(); myfunc(); running this code has exactly the same effect as the previous example of the init() function above. what's different (and interesting) is that the displayname() inner function is returned from t...
...ou might expect that the name variable would no longer be accessible. however, because the code still works as expected, this is obviously not the case in javascript. the reason is that functions in javascript form closures. a closure is the combination of a function and the lexical environment within which that function was declared. this environment consists of any local variables that were in-scope at the time the closure was created. in this case, myfunc is a reference to the instance of the function displayname created when makefunc is run. the instance of displayname maintains a reference to its lexical environment, within which the variable name exists. for this reason, when myfunc is invoked, the variable name remains available for use, and "mozilla" is passed to alert. here's a sligh...
...And 8 more matches
Using JavaScript code modules
javascript code modules are a concept introduced in gecko 1.9 and can be used for sharing code between different privileged scopes. modules can also be used to create global javascript singletons that previously required using javascript xpcom objects. a javascript code module is simply some javascript code located in a registered location. the module is loaded into a specific javascript scope, such as xul script or javascript xpcom script, using components.utils.import() or components.utils["import"](). creating a javascript code module a very simple javascript module looks like this: var exported_symbols = ["foo", "bar"]; function foo() { return "foo"; } var bar = { name : "bar", size : 3 }; var dummy = "dummy"; notice that the module uses normal javascript to create functions,...
..."]; function foo() { return "foo"; } var bar = { name : "bar", size : 3 }; var dummy = "dummy"; notice that the module uses normal javascript to create functions, objects, constants, and any other javascript type. the module also defines a special array named exported_symbols. any javascript item named in exported_symbols will be exported from the module and injected into the importing scope. for example: components.utils.import("resource://app/my_module.jsm"); alert(foo()); // displays "foo" alert(bar.size + 3); // displays "6" alert(dummy); // displays "dummy is not defined" because 'dummy' was not exported from the module note: when you're testing changes to a code module, be sure to change the application's build id (e.g., the version) before your next test r...
... sharing objects using code modules an extremely important behavior of components.utils.import() is that modules are cached when loaded and subsequent imports do not reload a new version of the module, but instead use the previously cached version. this means that a given module will be shared when imported multiple times. ...
...And 7 more matches
Components.utils.import
components.utils.import was introduced in firefox 3 and is used for sharing code between different scopes easily. for example, you can import xpcomutils.jsm to avoid copy/pasting long xpcom component registration boilerplate 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...
...o 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 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 properti...
...esource://gre/modules/xpcomutils.jsm", this); difference from mozijssubscriptloader the differences from mozijssubscriptloader: the behavior when importing/loading the same code from different locations: the subscript loader evaluates the specified code each time it is invoked, with the caller's global object. components.utils.import evaluates the code of each module only once, in its own scope. ...
...And 7 more matches
Service Worker API - Web APIs
r urls accessed by the user inside the whole origin, or inside a subset specified by you. download, install and activate at this point, your service worker will observe the following lifecycle: download install activate the service worker is immediately downloaded when a user first accesses a service worker–controlled site/page. after that, it is updated when: a navigation to an in-scope page occurs. an event is fired on the service worker and it hasn't been downloaded in the last 24 hours. installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site. if this is the first time a service worker has been made available, installation is att...
..., the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. it is only activated when there are no longer any pages loaded that are still using the old service worker. as soon as there are no more pages to be loaded, the new service worker activates (becoming the active worker). activation can happen sooner using serviceworkerglobalscope.skipwaiting() and existing pages can be claimed by the active worker using clients.claim(). you can listen for the installevent; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage api, and placing assets inside it that you'll want for running your app offline. there is also an activate event. the point where ...
...ise is successfully resolved. for a complete tutorial to show how to build up your first basic example, read using service workers. other use case ideas service workers are also intended to be used for such things as: background data synchronization. responding to resource requests from other origins. receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data. client-side compiling and dependency management of coffeescript, less, cjs/amd modules, etc. for development purposes. hooks for background services. custom templating based on certain url patterns. performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures i...
...And 7 more matches
HTTP Cache
mandatory argument to *storage methods of nsicachestorageservice. //github.com/realityripple/uxp/blob/master/netwerk/base/public/nsiloadcontextinfo.idl it is a helper interface wrapping following four arguments into a single one: private-browsing boolean flag anonymous load boolean flag app id number (0 for no ...
...ed with in any way different nsiloadcontextinfo arguments are strictly and completely distinct and cache entries in them do not overlap even when having the same uris. nsicachestorage //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicachestorage.idl obtained from call to one of the *storage methods on nsicachestorageservice. represents a distinct storage area (or scope) to put and get cache entries mapped by urls into and from it. similarity with the old cache: this interface may be with some limitations considered as a mirror to nsicachesession, but less generic and not inclining to abuse. unimplemented or underimplemented functionality: asyncevictstorage (bug 977766), asyncvisitstorage (bug 916052) nsicacheentryopencallback //gi...
...ending openers, if any, are now given this new entry to examine and read as an existing entry. adding a new storage should there be a need to add a new distinct storage for which the current scoping model would not be sufficient - use one of the two following ways: [preffered] add a new <your>storage method on nsicachestorageservice and if needed give it any arguments to specify the storage scope even more. implementation only should need to enhance the context key generation and parsing code and enhance current - or create new when needed - nsicachestorage implementations to carry any additional information down to the cache service. [not preferred] add a new argument to nsiloadcontextinfo; be careful here, since some arguments on the context may not be known during the load time, what...
...And 6 more matches
Tutorial: Embedding Rhino
rn x+1} f(7)" 8 note that you'll have to have both the rhino classes and the runscript example class file in the classpath. let's step through the body of main one line at time. entering a context the code context cx = context.enter(); creates and enters a context. a context stores information about the execution environment of a script. initializing standard objects the code scriptable scope = cx.initstandardobjects(); initializes the standard objects (object, function, etc.) this must be done before scripts can be executed. the null parameter tells initstandardobjects to create and return a scope object that we use in later calls. collecting the arguments this code is standard java and not specific to rhino. it just collects all the arguments and concatenates them together. str...
.... the null parameter tells initstandardobjects to create and return a scope object that we use in later calls. collecting the arguments 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...
...ssion: js> obj = { run: function() { print("hi"); } } [object object] js> obj.run() hi js> r = new java.lang.runnable(obj); [object object] js> t = new java.lang.thread(r) thread[thread-0,5,main] js> t.start() hi adding java objects the next example is runscript2. this is the same as runscript, but with the addition of two extra lines of code: object wrappedout = context.javatojs(system.out, scope); scriptableobject.putproperty(scope, "out", wrappedout); these lines add a global variable out that is a javascript reflection of the system.out variable: $ java runscript2 "out.println(42)" 42.0 undefined using javascript objects from java after evaluating a script it's possible to query the scope for variables and functions, extracting values and calling javascript functions. this is ill...
...And 6 more matches
HTMLTableCellElement - Web APIs
eaders read only is a domsettabletokenlist describing a list of id of <th> elements that represents headers associated with the cell. it reflects the headers attribute. htmltablecellelement.rowspan an unsigned long integer indicating the number of rows this cell must span; this lets a cell occupy space across multiple rows of the table. it reflects the rowspan attribute. ...
...etokenlist describing a list of id of <th> elements that represents headers associated with the cell. it reflects the headers attribute. htmltablecellelement.rowspan an unsigned long integer indicating the number of rows this cell must span; this lets a cell occupy space across multiple rows of the table. it reflects the rowspan attribute. htmltablecellelement.scope a domstring indicating the scope of a <th> cell. ...
...nts headers associated with the cell. it reflects the headers attribute. htmltablecellelement.rowspan an unsigned long integer indicating the number of rows this cell must span; this lets a cell occupy space across multiple rows of the table. it reflects the rowspan attribute. htmltablecellelement.scope a domstring indicating the scope of a <th> cell. ...
...And 6 more matches
Window - Web APIs
Web › API › Window
limageelement. option used for creating an htmloptionelement. staticrange read only returns a staticrange() constructor which creates a staticrange object. worker used for creating a web worker. xmlserializer converts a dom tree into xml or html source. properties this interface inherits properties from the eventtarget interface and implements properties from the windoworworkerglobalscope and windoweventhandlers mixins. note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below. window.closed read only this property indicates whether the current window is closed or not. window.console read only returns a reference to the console object which provides access to the browser's debugging console. w...
...perty is read only. window.visualviewport read only returns a visualviewport object which represents the visual viewport for a given window. window.window read only returns a reference to the current window. window[0], window[1], etc. returns a reference to the window object in the frames. see window.frames for more details. properties implemented from elsewhere windoworworkerglobalscope.caches read only returns the cachestorage object associated with the current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object. windoworworker...
...s read only returns the cachestorage object associated with the current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously 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.) deprecated properties window.content and window._content read only returns a reference to the content e...
...And 6 more matches
<table>: The Table element - HTML: Hypertext Markup Language
Web › HTML › Element › table
ecide if they need to read the rest of the table content or skip over it. this helps people navigating with the aid of assistive technology such as a screen reader, people experiencing low vision conditions, and people with cognitive concerns. mdn adding a caption to your table with <caption> caption & summary • tables • w3c wai web accessibility tutorials scoping rows and columns the scope attribute on header elements is redundant in simple contexts, because scope is inferred. however, some assistive technologies may fail to draw correct inferences, so specifying header scope may improve user experiences. in complex tables, scope can be specified so as to provide necessary information about the cells related to a header. example <table> <caption>color names and values</caption>...
...is redundant in simple contexts, because scope is inferred. however, some assistive technologies may fail to draw correct inferences, so specifying header scope may improve user experiences. in complex tables, scope can be specified so as to provide necessary information about the cells related to a header. ...
... because scope is inferred. however, some assistive technologies may fail to draw correct inferences, so specifying header scope may improve user experiences. in complex tables, scope can be specified so as to provide necessary information about the cells related to a header. ...
...And 6 more matches
Interacting with page scripts - Archive of obsolete content
ract directly with content scripts or access objects they create. for the sake of security, stability, and simplicity, this is usually what you want. you don't want arbitrary web pages to be able to access objects in content scripts, and you don't want objects created by content scripts to clash with objects created by page scripts. but sometimes, you will want to share objects between the two scopes. this guide describes: how to share objects between content scripts and page scripts how to send messages between content scripts and page scripts sharing objects with page scripts there are two possible cases here: a content script might want to access an object defined by a page script a content script might want to expose an object to a page script access objects defined by page ...
...ent-script-var"); button.addeventlistener("click", function() { // access object defined by content script console.log(window.contentscriptobject.greeting); // "hello from add-on" }, false); after firefox 30, you can still do this for primitive values, but can no longer do it for objects. instead, you need to use the global cloneinto() function to clone the object into the page script's scope. cloneinto() creates a structured clone of the object in the target context, and returns a reference to the clone. you can then assign that to a property of the target window, and the page script can access it. here's an example. the "main.js" opens the local file "page.html" and attaches a content script to it: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.
...rk" fails, and the following message is logged: permission denied to access property 'greeting' expose functions to page scripts the structured clone algorithm is a bit more powerful than simple json serialization, but not much: in particular, functions aren't cloned. this means that you can't expose a function to a page script using cloneinto(), and if you clone an object into the page script scope, its methods will not be available to the page script. to expose a function defined in a content script to a page script so the page script can call it, use exportfunction(). here's an example. the "main.js" opens the local file "page.html" and attaches a content script to it: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.open({ url: self.data.url("page.h...
...And 5 more matches
Appendix D: Loading Scripts - Archive of obsolete content
h means they don't necessarily need to read as source and compiled with each restart. flexibility: script tags provide a means to specify the character set and javascript version of the scripts to be loaded, which many other methods do not. debuggable: development tools support debugging javascript loaded by script tags disadvantages scoping: scripts loaded via script tags share the global scope with all other scripts loaded into the same window. these tags provide no means to load scripts into a private or otherwise specific scope. speed: even if these scripts are loaded from a cache, only read and compile time are reduced. the scripts still need to execute all of their initialization code and allocate and initialize all of their data structures each time the script is loaded. loading...
...aluated was extracted. this information is invaluable for debugging, and the flexibility with which it can be specified makes this method useful for extracting javascript from a number of file formats other than raw javascript scripts. additionally, as sandbox objects can be created with an arbitrary prototype object, the evaluated code can be given access to the global properties of any existing scope. security: sandbox objects are initialized with a security principal object, or otherwise a window or url from which to derive one. this means that evalinsandbox can be used to execute code with a specified privilege level rather than full chrome privileges. beyond this, the scope of the sandbox can be augmented or rarified to add or remove privileges as necessary. under ordinary circumstances, ...
...nize regexp objects from foreign compartments: bug 633830 debugging: support for sandbox evaluation in development tools is uneven. chromebug supports firebug based sandboxes. examples the following code will execute a simple script in a sandbox with the privilege level of the current content page. the globals of the current content window will be available in the scripts global scope. in stack traces, the script will appear to have been loaded from the file "zz-9://plural/zed/alpha", line 42. // use the current content window as the execution context. // to make properties defined by scripts executing on the page // available to your sandbox script, use content.wrappedjsobject // instead. let context = content; // create the sandbox let sandbox = components.utils.sandbox(co...
...And 5 more matches
Handling common JavaScript problems - Learn web development
oncentrate on the cross-browser issues. if you are not already familiar with the basics of troubleshooting javascript, you should study that article before moving on. there are a number of common javascript problems that you will want to be mindful of, such as: basic syntax and logic problems (again, check out troubleshooting javascript). making sure variables, etc. ...
...ing javascript, you should study that article before moving on. there are a number of common javascript problems that you will want to be mindful of, such as: basic syntax and logic problems (again, check out troubleshooting javascript). making sure variables, etc. are defined in the correct scope, and you are not running into conflicts between items declared in different places (see function scope and conflicts). ...
.... there are a number of common javascript problems that you will want to be mindful of, such as: basic syntax and logic problems (again, check out troubleshooting javascript). making sure variables, etc. are defined in the correct scope, and you are not running into conflicts between items declared in different places (see function scope and conflicts). confusion about this, in terms of what scope it applies to, and therefore if its value is what you intended. you can read what is "this"? for a light introduction; you should also study examples like this one, which shows a typical pattern of saving a this scope to a separate variable, then using that variable in nested functions so you can be sure you are applying functionality to the correct this scope. incorrectly using functions inside...
...And 5 more matches
Mork
Mozilla › Tech › Mork
so the zany mork version 1.4 format has become the only official mork format. after that, the lexical structure of mork is somewhat simple. the file is a collection of top-level structures, of which there exists four: dictionaries, tables, rows, and groups (changesets). dictionaries, tables, and rows all have corresponding metastructures. meta-dictionaries are in practice only used to change the scope of alias definitions (the '(a=c)' that you can see in files). meta-tables are used to establish some facts about the table as well as the default row scope. meta-rows do not appear to be used at all, although the parser seems to consider setting the charset, row scope, and atom scope. some notes on further terminology: when referring to cells or aliases, the first component is the key and the s...
...there are two types of meta-rows, those of rows and those of tables. however, since the meta-row of a row never appears to be used, i will generally use 'meta-row' to refer to the meta-row of a table, unless otherwise qualified. dictionaries a dictionary establishes a series of aliases. ...
... right of the colon. there are two types of meta-rows, those of rows and those of tables. however, since the meta-row of a row never appears to be used, i will generally use 'meta-row' to refer to the meta-row of a table, unless otherwise qualified. dictionaries a dictionary establishes a series of aliases. if inside the meta-dictionary, the only cell we care about is if the key is 'a' (for atom scope). this value is used to establish which dictionary the aliases are added to. most files will have just two dictionaries: the column scope dictionary ('c') and the value scope dictionary ('v', the default). the keys are hexadecimal numbers starting at 0x80, because the values less than 0x80 are theoretically their representative ascii values. tables a table is set of rows, potentially with a meta-...
...And 5 more matches
ARIA: grid role - Accessibility
a widget that contains one or more rows of cells. the position of each cell is significant and can be focused using keyboard input. ...
...while it does not imply a...
...r" aria-label="monday">m</th> <th role="columnheader" aria-label="tuesday">t</th> <th role="columnheader" aria-label="wednesday">w</th> <th role="columnheader" aria-label="thursday">t</th> <th role="columnheader" aria-label="friday">f</th> <th role="columnheader" aria-label="saturday">s</th> </tr> </thead> <tbody role="rowgroup"> <tr role="row"> <th scope="row" role="rowheader">week 35</th> <td>26</td> <td>27</td> <td>28</td> <td>29</td> <td>30</td> <td>31</td> <td role="gridcell" tabindex="-1">1</td> </tr> <tr role="row"> <th scope="row" role="rowheader">week 36</th> <td role="gridcell" tabindex="-1"> 2 </td> <td role="gridcell" tabindex="-1"> 3 </t...
...And 5 more matches
Functions - JavaScript
on expression is similar to and has the same syntax as a function declaration (see function expression for details). a function expression may be a part of a larger expression. one can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code. function [name]([param[, param[, ... param]]]) { statements } name the function name. can be omitted, in which case the function becomes known as an anonymous function. param the name of an argument to be passed to the function. statements the statements comprising the body of the function. here is an example of an a...
... 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 is declared. as the 4th example shows, the function name can be different from the variable the function is assigned to. they have no relation to each other. a function declaration also creates a variable with the same name as the function name. thus, unlike those defined by function expressions, functions defined by function declar...
...n which the function is declared. as the 4th example shows, the function name can be different from the variable the function is assigned to. they have no relation to each other. a function declaration also creates a variable with the same name as the function name. thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in: a function defined by 'new function' 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 f...
...And 5 more matches
var - JavaScript
the var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value. 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 var varname1 [= value1] [, varname2 [= value2] ... [, varnamen [= valuen]]]; varnamen variable name. it can be any legal identifier. valuen optional initial value of the variable. it can be any legal expression. default value is undefined. description var declarations, wherever they occur, are processed before any code is executed. this is called hoisting, and is discussed further below. ...
...ame1 [= value1] [, varname2 [= value2] ... [, varnamen [= valuen]]]; varnamen variable name. it can be any legal identifier. valuen optional initial value of the variable. it can be any legal expression. default value is undefined. description var declarations, wherever they 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. duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed. 'use stri...
..., for variables declared outside any function, global. duplicate variable declarations using 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); // referenceerror 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 referenceerror) console.log('still going...'); // st...
...And 5 more matches
loader/sandbox - Archive of obsolete content
the argument may be: a url string, in which case the sandbox will get the same privileges as a script loaded from that url a dom window object, to inherit privileges from the window being passed. omitted or null: then the sandbox will have chrome privileges giving it access to all the xpcom components. ...
... window object, to inherit privileges from the window being passed. omitted or null: then the sandbox will have chrome privileges giving it access to all the xpcom components. optionally the sandbox function can be passed a second argument (see sandbox documentation on mdn for details). ...
...ileges from the window being passed. omitted or null: then the sandbox will have chrome privileges giving it access to all the xpcom components. optionally the sandbox function can be passed a second argument (see sandbox documentation on mdn for details). ...
...And 4 more matches
Invariants
properties are native. there may be other reasons that cover more cases, but nobody can remember one.) all jsobjects and heap-allocated jsstrings must be 8-byte-aligned. (the jsval encoding depends on this.) the jsstackframe::down chain never forms a cycle. (it's a stack. but note that a stack frame is not necessarily newer than the next stack frame down, thanks to generators!) an object's scope chain (found by chasing jsobject::fslots[jsslot_parent]) never forms a cycle. (we can probably loop forever if that happens. js_setparent can violate this, if the application is really that dumb, but generally every object is newer than its __parent__.) the tracejit must not trace into a function whose scope chain ends in a different global object. (if it is a script function, global names acc...
...(a cycle would be very silly and could cause infloops. ...
...(a cycle would be very silly and could cause infloops. ...
...And 4 more matches
SpiderMonkey 1.8.5
the configuration options to enable nspr (e.g. --with-system-nspr). garbage collection spidermonkey 1.8.5 introduces a conservative stack-scanning garbage collector. unlike the exact garbage collector, the new garbage collector will scan the c stack and registers in your embedding, looking for bits that it can treat as potential gc roots. the approach eliminates the need for the js_enterlocalrootscope api, and in many cases 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 s...
...executeregexp js_executeregexpnostatics js_executescriptversion js_forget_string_flatness js_fileescapedstring js_finishjsonparse (removed in future releases, replaced with js_parsejson) js_flatstringequalsascii js_flattenstring js_flushcaches js_freezeobject js_getcompartmentprivate js_getemptystring js_getflatstringchars js_getgcparameter js_getgcparameterforthread js_getglobalforscopechain js_getinternedstringchars js_getinternedstringcharsandlength js_getownpropertydescriptor js_getpropertyattrsgetterandsetterbyid js_getpropertybyid js_getpropertybyiddefault js_getpropertydefault js_getpropertydescriptorbyid js_getruntimesecuritycallbacks js_getsecuritycallbacks js_getstringcharsandlength js_getstringcharsz js_getstringcharszandlength js_getstringencodinglength ...
...helpers while jsapi remains a c api, the engine is now implemented in c++. some c++ helpers have been introduced into the api, to help embedders writing c++ projects. please note that spidermonkey reserves the js:: namespace for itself. ...
...And 4 more matches
Split object
. the script in a might have opened tb by calling window.open, which returns a direct reference to tb's window. more indirectly, suppose there's a javascript function defined in page b that refers to global variables in page b. if page a gets a reference to that function, then by calling it, it is indirectly accessing tab tb's window. the function object carries a reference to the window, via the scope chain. to further complicate matters, a and b are in the same security domain, so security checks between them automatically succeed. this makes the problem resistant to a wrapper-based approach.) older versions of firefox accomplished this by blowing away all window properties every time a user navigated to another page, then reusing the window. each page, even on back, had to load from scratc...
...ed this by blowing away all window properties every time a user navigated to another page, then reusing the window. each page, even on back, had to load from scratch. this was slow. circa firefox 1.5, the decision was made to cache layout information and javascript state across navigation. a new approach for window was needed. security privileges are granted to js code on the basis of the scope chain of the executing code. spidermonkey walks up the scope chain to the nearest object that has jsprincipals attached. the end of the scope chain is the global object for the script. but what jsprincipals should be attached to a window object? the principals of the page the window is currently displaying? but then the page that called window.open could use a with statement to inject that window...
...this security feature is not peculiar to split objects. ...
...And 4 more matches
Components.utils
itors! please keep this list in sync with the components object page methods method description cloneinto() create a structured clone of an object in a different javascript context. createarrayin() 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() ...
...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. ...
...insandbox() 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 to be called in the less-privileged scope. ...
...And 4 more matches
Language bindings
ype 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. ...
...f 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 defined at js/xpconnect/idl/xpccomponents.idl.components.utils.cloneintothis function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope. ...
...useful xpconnect features. its interface is defined at js/xpconnect/idl/xpccomponents.idl.components.utils.cloneintothis function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope. it returns a reference to the clone:components.utils.createobjectincomponents.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment.components.utils.evalinsandboxthe evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.components.utils.evalinwindowthis function enables code running in a more-privileged javascript context to evaluate a string in a less-privileged javascript context. the re...
...And 4 more matches
XPIDL Syntax
Mozilla › Tech › XPIDL › Syntax
ike the c preprocessor, when a file is included multiple times, it acts as if the subsequent includes did not happen; this prevents the need for include guards. xpidl syntax (abnf) the root production here is idl_file. ...
...essor, when a file is included multiple times, it acts as if the subsequent includes did not happen; this prevents the need for include guards. xpidl syntax (abnf) the root production here is idl_file. ...
... literal = octal_literal / decimal_literal / hex_literal / floating_literal literal /= string_literal / char_literal literal /= "true" / "false" ; in regex: /"[^"\n]*["\n]/. yes, newline terminates. string_literal = 1*(%x22 ...
...And 4 more matches
Microdata - HTML: Hypertext Markup Language
. microdata is an attempt to provide a simpler way of annotating html elements with machine-readable tags than the similar approaches of using rdfa and classic microformats. at a high level, microdata consists of a group of name-value pairs. the groups are called items, and each name-value pair is a property. items and properties are represented by regular elements. to create an item, the itemscope attribute is used. to add a property to an item, the itemprop attribute is used on one of the item's descendants. vocabularies google and other major search engines support the schema.org vocabulary for structured data. this vocabulary defines a standard set of type names and property names, for example, schema.org music event indicates a concert performance, with startdate and location prope...
...ation of information in russian-language web-pages became considerably more successful. global attributes itemid – the unique, global identifier of an item. itemprop – used to add properties to an item. every html element may have an itemprop attribute specified, where an itemprop consists of a name and value pair. itemref – properties that are not descendants of an element with the itemscope attribute can be associated with the item using an itemref. itemref provides a list of element ids (not itemids) with additional properties elsewhere in the document. itemscope – itemscope (usually) works along with itemtype to specify that the html contained in a block is about a particular item. itemscope creates the item and defines the scope of the itemtype associated with it. itemtype is ...
...cify that the html contained in a block is about a particular item. itemscope creates the item and defines the scope of the itemtype associated with it. itemtype is a valid url of a vocabulary (such as schema.org) that describes the item and its properties context. itemtype – specifies the url of the vocabulary that will be used to define itemprop's (item properties) in the data structure. itemscope is used to set the scope of where in the data structure the vocabulary set by itemtype will be active. ...
...And 4 more matches
Modules - Archive of obsolete content
avascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. we will show how to do each of these things using the built-in components object provided by xulrunner application such as firefox and thunderbird. to improve encapsulation, each module should be defined in the scope of its own global object. this is made possible by the use of sandboxes. each sandbox lives in its own compartment. a compartment is a separate memory space. each compartment has a set of privileges that determines what scripts running in that compartment can and cannot do. we will show how sandboxes and compartments can be used to improve security in our module system. the module system used by...
...pt project reaches a certain size, it becomes necessary to split it up into multiple files. unfortunately, javascript does not provide any means to load scripts from other locations: we have to rely on the host application to provide us with this functionality. applications such as firefox and thunderbird are based on xulrunner. xulrunner adds a built-in object, known as components, to the global scope. this object forms the central access point for all functionality provided by the host application. a complete explanation of how to use components is out of scope for this document. however, the following example shows how it can be used to load scripts from other locations: const { classes: cc interfaces: ci } = components; var instance = cc["@mozilla.org/moz/jssubscript-loader;1"]; v...
...this document. however, the following example shows how it can be used to load scripts from other locations: const { classes: cc interfaces: ci } = components; var instance = cc["@mozilla.org/moz/jssubscript-loader;1"]; var loader = instance.getservice(ci.mozijssubscriptloader); function loadscript(url) { loader.loadsubscript(url); } when a script is loaded, it is evaluated in the scope of the global object of the script that loaded it. any property defined on the global object will be accessible from both scripts: // index.js: loadscript("www.foo.com/a.js"); foo; // => 3 // a.js: foo = 3; exporting names the script loader we obtained from the components object allows us load scripts from other locations, but its api is rather limited. for instance, it does not know how to h...
...And 3 more matches
Styling Vue components with CSS - Learn web development
need a terminal with node + npm installed. objective: to learn about styling vue components. styling vue components with css before we move on to add more advanced features to our app, we should add some basic css to make it look better. vue has three common approaches to styling apps: external css files. global styles in single file components (.vue files). component-scoped styles in single file components. to help familiarize you with each one, we'll use a combination of all three to give our app a nicer look and feel. styling with external css files you can include external css files and apply them globally to your app. let's look at how this is done. to start with, create a file called reset.css in the src/assets directory. files in this folder get processe...
...="off" v-model.lazy.trim="label" class="input__lg" /> <button type="submit" class="btn btn__primary btn__lg"> add </button> </form> </template> let's also add the stack-large class to the <ul> tag in our app.vue file. this will help improve the spacing of our to-do items a bit. ...
...ul aria-labelledby="list-summary" class="stack-large"> adding scoped styles the last component we want to style is our todoitem component. to keep the style definitions close to the component we can add a <style> element inside it. however, if these styles alter things outside of this component, it could be challenging to track down the styles responsible, and fix the problem. this is where the scoped attribute can be useful — this attaches a unique html data attribute selector to all of your styles, preventing them from colliding globally. ...
...And 3 more matches
Rhino serialization
lization apis two new classes, scriptableoutputstream and scriptableinputstream, were introduced to handle serialization of rhino classes. these classes extend objectoutputstream and objectinputstream respectively. ...
...no classes. these classes extend objectoutputstream and objectinputstream respectively. writing an object to a file can be done in a few lines of java code: fileoutputstream fos = new fileoutputstream(filename); scriptableoutputstream out = new scriptableoutputstream(fos, scope); out.writeobject(obj); out.close(); here filename is the file to write to, obj is the object or function to write, and scope is the top-level scope containing obj. reading the serialized object back into memory is similarly simple: fileinputstream fis = new fileinputstream(filename); objectinputstream in = new scriptableinputstream(fis, scope); object deserialized = in.readobject(); in.close(); again, we need the scope to create our serialization stream class. so why do we need these specialized stream classes instead...
...zes objects. how rhino serialization works by default, java serialization of an object also serializes objects that are referred to by that object. upon deserialization the initial object and the objects it refers to are all created and the references between the objects are resolved. however, for javascript this creates a problem. ...
...And 3 more matches
Using IndexedDB - Web APIs
ust call idbversionchangerequest.setversion to establish the versionchange transaction.) to read the records of an existing object store, the transaction can either be in readonly or readwrite mode. to make changes to an existing object store, the transaction must be in readwrite mode. you open such transactions with idbdatabase.transaction. the method accepts two parameters: the storenames (the scope, defined as an array of object stores that you want to access) and the mode (readonly or readwrite) for the transaction. the method returns a transaction object containing the idbindex.objectstore method, which you can use to access your object store. by default, where no mode is specified, transactions open in readonly mode. note: as of firefox 40, indexeddb transactions have relaxed durabilit...
...not need to concern themselves further. if you must ensure durability for some 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. ...
...on (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. you can speed up data access by using the right scope and mode in the transaction. here are a couple of tips: when defining the scope, specify only the object stores you need. this way, you can run multiple transactions with non-overlapping scopes concurrently. only specify a readwrite transaction mode when necessary. you can concurrently run multiple readonly transactions with overlapping scopes, but you can have only one readwrite transaction for an object store. to learn more, see the definition for transactions in the basi...
...And 3 more matches
Sensor APIs - Web APIs
ic sensor api specification defines a sensor interface, as a web developer you will never use it. instead you'll use one of its subclasses to retrieve specific kinds of sensor data. for example, the accelerometer interface returns the acceleration of the device along all three axes at the time it is read. sensors may or may not correspond exactly to a physical device sensor. for example, the gyroscope interface corresponds exactly to a physical device interface. alternatively, the absoluteorientationsensor interface provides information that is algorithmically agregated from two or more device sensors. these sensor types are referred to as low-level and high-level respectively. the latter type of sensor is also called a fusion sensor (alternatively, virtual or synthetic sensors). feature dete...
...life. therefore, feature detection for sensor apis must include both detection of the apis themselves and defensive programming strategies (see below). the examples below show three methods for detecting sensor apis. additionally you can put object instantiation inside a try...catch block. notice that detection through the navigator interface is not one of the available options. if (typeof gyroscope === "function") { // run in circles... } if ("proximitysensor" 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. defe...
...me === 'securityerror') console.log("no permissions to use absoluteorientationsensor."); }; the following table describes for each sensor type, the name required for the permissions api, the <iframe> element's allow attribute and the feature-policy directive. ...
...And 3 more matches
Using Service Workers - Web APIs
riments, as it supports https. in order to facilitate local development, localhost is considered a secure origin by browsers as well. basic architecture with service workers, the following steps are generally observed for basic set up: the service worker url is fetched and registered via serviceworkercontainer.register(). if successful, the service worker is executed in a serviceworkerglobalscope; this is basically a special kind of worker context, running off the main script execution thread, with no dom access. the service worker is now ready to process events. installation of the worker is attempted when service worker-controlled pages are accessed subsequently. an install event is always the first one sent to a service worker (this can be used to start the process of populating an i...
... service workers note : we're using the es6 arrow functions syntax in the service worker implementation now let’s get on to service workers! registering your worker the first block of code in our app’s javascript file — app.js — is as follows. this is our entry point into using service workers. if ('serviceworker' in navigator) { navigator.serviceworker.register('./sw-test/sw.js', {scope: './sw-test/'}) .then((reg) => { // registration worked console.log('registration succeeded. scope is ' + reg.scope); }).catch((error) => { // registration failed console.log('registration failed with ' + error); }); } the outer block performs a feature detection test to make sure service workers are supported before trying to register one. next, we use the serviceworker...
...rror); }); } the outer block performs a feature detection test to make sure service workers are supported before trying to register one. next, we use the serviceworkercontainer.register() function to register the service worker for this site, which is just a javascript file residing inside our app (note this is the file's url relative to the origin, not the js file that references it.) the scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. in this case, we have specified '/sw-test/', which means all content under the app's origin. if you leave it out, it will default to this value anyway, but we specified it here for illustration purposes. the .then() promise function is used to chain a success case onto our pr...
...And 3 more matches
<tr>: The Table Row element - HTML: Hypertext Markup Language
Web › HTML › Element › tr
n groups to help make our css easier. html the html is where the action is here, and the action is pretty simple. ...
...rowspan="2">id</th> <th colspan="2">membership dates</th> <th rowspan="2">balance</th> </tr> <tr> <th>joined</th> <th>canceled</th> </tr> </thead> <tbody> <tr> <th scope="row">margaret nguyen</td> <td>427311</td> <td><time datetime="2010-06-03">june 3, 2010</time></td> <td>n/a</td> <td>0.00</td> </tr> <tr> <th scope="row">edvard galinski</td> <td>533175</td> <td><time datetime="2011-01013">january 13, 2011</time></td> <td><time datetime="2017-04008">april 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th scope="row">hoshi nakamura</td> <td>601942</td> <td><time datetime="2012-07-23">july 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> ...
...being used, and add a background color to the header row. result again, let's take a look at the result first. ...
...And 3 more matches
Default parameters - JavaScript
this means that functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to...
... 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 referenceerror. it also means that variables declared inside the...
...thdefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":p", {value:"=^_^="}, arguments, "=^_^="] withoutdefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":p", {value:"=^_^="}, arguments, "=^_^="] scope effects if default parameters are 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 referenceerror. 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 duplica...
...And 3 more matches
eval() - JavaScript
+ 2')); // returns a string object containing "2 + 2" eval('2 + 2'); // returns 4 you can work around this limitation in a generic fashion by using tostring(). ...
... object containing "2 + 2" eval('2 + 2'); // returns 4 you can work around this limitation in a generic fashion by using tostring(). var expression = new string('2 + 2'); eval(expression.tostring()); // returns 4 if you use the eval function indirectly, by invoking it via a reference other than eval, as of ecmascript 5 it works in the global scope rather than the local scope. ...
...string('2 + 2'); eval(expression.tostring()); // returns 4 if you use the eval function indirectly, by invoking it via a reference other than eval, as of ecmascript 5 it works in the global scope rather than the local scope. this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called. ...
...And 3 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
specific instances of the object are drawn. 79 client hints client hints, glossary, performance, reference, web performance client hints are a set of http request header fields for proactive content negotiation allowing clients to indicate a list of device and agent specific preferences. 80 closure codingscripting, glossary the binding which defines the scope of execution. in javascript, functions create a closure context. 81 code splitting glossary, reference, web performance, code splitting, latency code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel. 82 codec glossary, webmechanics a codec (a blend word derived from "coder-decoder") is...
...tributed development teams. what sets it apart from previous scm systems is the ability to do common operations (branching, committing, etc.) on your local development machine, without having to change the master repository or even having write access to it. 172 global object codingscripting, glossary, needscontent a global object is an object that always exists in the global scope. 173 global scope codingscripting, glossary, needscontent in a programming environment, the global scope is the scope that contains, and is visible in, all other scopes. 174 global variable codingscripting, glossary a global variable is a variable that is declared in the global scope in other words, a variable that is visible from all other scopes. ...
...at delays the loading of some assets (e.g., images) until they are needed by the user based on the user's activity and navigation pattern; typically, these assets are only loaded when they are scrolled into view. 250 ligature css, design, glossary a ligature is a joining of two characters into one shape. for example, in french "œ" is a ligature of "oe". 251 local scope codingscripting, glossary, needscontent local scope is a characteristic of variables that makes them local (i.e., the variable name is only bound to its value within a scope which is not the global scope). 252 local variable codingscripting, glossary, needscontent a variable whose name is bound to its value only within a local scope. 253 locale compos...
...And 2 more matches
How to build custom form controls - Learn web development
xample: rebuilding the <select> element. we will also discuss how, when, and whether building your own control makes sense, and what to consider when building a control is a requirement. note: we'll focus on building the control, not on how to make the code generic and reusable; that would involve some non-trival javascript code and dom manipulation in an unknown context, and that is out of the scope of this article. design, structure, and semantics before building a custom control, you should start by figuring out exactly what you want. this will save you some precious time. in particular, it's important to clearly define all the states of your control. to do this, it's good to start with an existing control whose states and behavior are well known, so that you can simply mimic those as m...
... // we toggle the visibility of the list of options toggleoptlist(select); ...
...r', function () { // note: the `select` and `option` variable are closures // available in the scope of our function call. highlightoption(select, option); }); }); // each times the user clicks on or taps a custom select element select.addeventlistener('click', function (event) { // note: the `select` variable is a closure // available in the scope of our function call. // we toggle the visibility of the list of options toggleoptlist(select); }); // in case the control gains focus // the control gains the focus each time the user clicks on it or each time // they use the tabulation key to access the control select.addeventlistener('focus', function (event) { // note: the `select` and `selectlist` vari...
...And 2 more matches
Browser chrome tests
as all tests, they won't work in a build with tests disabled (--disable-tests). ...
...nt/test/ or without mach test_path=<path_to_the_tests> make -c <objdir> mochitest-browser-chrome to run tests in debugger the following should work ./mach mochitest -f browser --debugger gdb browser/base/content/test/ run ./mach help mochitest-browser for more options. writing browser chrome tests browser chrome tests are snippets of javascript code that run in the browser window's global scope. a simple test would look like this: function test() { ok(gbrowser, "gbrowser exists"); is(gbrowser.tabs.length, 1, "browser has 1 tab"); } the test() function is invoked by the test harness when the test is run. the test file can contain other functions, they will be ignored unless invoked by test(). gbrowser is set in browser.js and is a tabbrowser element (the tabbrowser with id="c...
...er has 1 tab"); } the test() function is invoked by the test harness when the test is run. the test file can contain other functions, they will be ignored unless invoked by test(). gbrowser is set in browser.js and is a tabbrowser element (the tabbrowser with id="content" in browser.xul). note: be careful when naming your functions and variables. since the test files are executed in the same scope as the browser window, conflicting variable names could cause trouble while running the tests. you should attempt to reduce the side effects of the testing code and "clean up" after yourself, to avoid influencing other tests. the comparison functions are identical to those supported by mochitests, see how the comparison functions work in the mochitest documentation for more details. the eventuti...
...And 2 more matches
AddonManager
t_none no operations will require a restart. op_needs_restart_enable enabling the add-on will require a restart. op_needs_restart_disable disabling the add-on will require a restart. op_needs_restart_uninstall uninstalling the add-on will require a restart. op_needs_restart_install installing the add-on will require a restart. ...
..._needs_restart_enable enabling the add-on will require a restart. op_needs_restart_disable disabling the add-on will require a restart. op_needs_restart_uninstall uninstalling the add-on will require a restart. op_needs_restart_install installing the add-on will require a restart. installation scopes constant value description scope_all 15 a combination of all the installation scopes. scope_application 4 this add-on is a part of the current application (installed and owned by firefox). scope_profile 1 this add-on is installed in the current profile directory. scope_system 8 this add-on is installed somewhere global to the system (installed for all users of the computer). ...
... 15 a combination of all the installation scopes. scope_application 4 this add-on is a part of the current application (installed and owned by firefox). scope_profile 1 this add-on is installed in the current profile directory. scope_system 8 this add-on is installed somewhere global to the system (installed for all users of the computer). scope_user 2 this add-on is installed somewhere specific to the current user (all profiles of the logged-in user). note: the extensions.enabledscopes preference lets you configure which of these scopes are enabled; however, you can't turn off the profile scope. ...
...And 2 more matches
JSAPI User Guide
ds certain values to remain in memory, just store the values in properties of the object. as long as the object is reachable, its properties will remain reachable. if these values must not be accessible from javascript, use reserved slots instead. or store the values in private data and implement jsclass.mark. if a function creates new objects, strings, or numbers, it can use js_enterlocalrootscope and js_leavelocalrootscope to keep those values alive for the duration of the function. to keep a value alive permanently, store it in a gc root. still, gc bugs do occur. these two functions, both available only in debug builds, are especially useful for debugging gc-related crashes: use js_setgczeal to enable extra garbage collection. gc zeal usually causes a gc-related crash to occur m...
...erties /* statically initialize a class to make "one-off" objects. */ jsclass my_class = { "myclass", /* all of these can be replaced with the corresponding js_*stub function pointers. */ my_addproperty, my_delproperty, my_getproperty, my_setproperty, my_enumerate, my_resolve, my_convert, my_finalize }; jsobject *obj; /* * define an object named in the global scope that can be enumerated by * for/in loops. the parent object is passed as the second argument, as * with all other api calls that take an object/name pair. the prototype * passed in is null, so the default object prototype will be used. */ obj = js_defineobject(cx, globalobj, "myobject", &my_class, nullptr, jsprop_enumerate); /* * define a bunch of properties with a j...
...lasses this pulls together the above api elements by defining a constructor function, a prototype object, and properties of the prototype and of the constructor, all with one api call. initialize a class by defining its constructor function, prototype, and per-instance and per-class properties. the latter are called "static" below by analogy to java. they are defined in the constructor object's scope, so that myclass.mystaticprop works along with new myclass(). js_initclass takes a lot of arguments, but you can pass nullptr for any of the last four if there are no such properties or methods. note that you do not need to call js_initclass to make a new instance of that class—otherwise there would be a chicken-and-egg problem making the global object—but you should call js_initclass if yo...
...And 2 more matches
JS_ExecuteScript
execute a compiled script. ...
... js::mutablehandlevalue rval); // added in spidermonkey 45 bool js_executescript(jscontext *cx, js::handlescript script); // added in spidermonkey 45 bool js_executescript(jscontext *cx, js::autoobjectvector &scopechain, js::handlescript script, js::mutablehandlevalue rval); // added in spidermonkey 36 bool js_executescript(jscontext *cx, js::autoobjectvector &scopechain, js::handlescript script); // added in spidermonkey 36 bool js_executescript(jscontext *cx, js::handleobject obj, js::handlescript script, js::mutablehandlevalue rval); // obsolete since jsapi 39 bool js_executescript(jscontext *cx, js::handleobject obj, js::handlescript script); // obsolete since jsapi 39 bool js::cloneandexecutescript(jscontext *cx, js:...
...ext *cx, js::handle<jsobject*> obj, js::handle<jsscript*> script); // added in spidermonkey 31, obsoleted since jsapi 39 name type description cx jscontext * the context in which to execute the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the scope in which to execute the script. in the simplest cases, this should just be the embedding's global object. obsolete since jsapi 39 obj must not be an array, an e4x xml object, a with object, or a proxy. in ecmascript terms, the script is executed in a new execution context, but that context is not initialized quite as described in any of the three cases in ecma 262-3 §10.2. instead: ...
...And 2 more matches
JSAPI reference
on_ecma_3 jsversion_1_6 jsversion_1_7 jsversion_1_8 jsversion_ecma_5 jsversion_default jsversion_unknown jsversion_latest js_getimplementationversion js_getversion js_setversionforcompartment added in spidermonkey 31 js_stringtoversion js_versiontostring js_setversion obsolete since jsapi 25 js::currentglobalornull added in spidermonkey 31 js_getglobalforscopechain obsolete since jsapi 25 js_getglobalobject obsolete since jsapi 24 js_setglobalobject obsolete since jsapi 25 js_initclass js_initstandardclasses js_resolvestandardclass js_enumeratestandardclasses js_enumerateresolvedstandardclasses obsolete since jsapi 24 js_isrunning js_saveframechain js_restoreframechain js_isassigning obsolete since javascript 1.8.5 js_isconstruc...
...jsapi 25 js_initclass js_initstandardclasses js_resolvestandardclass js_enumeratestandardclasses js_enumerateresolvedstandardclasses obsolete since jsapi 24 js_isrunning js_saveframechain js_restoreframechain js_isassigning obsolete since javascript 1.8.5 js_isconstructing obsolete since jsapi 26 js_isconstructing_possiblywithgiventhisobject obsolete since jsapi 17 js_getscopechain obsolete since javascript 1.8.7 compartments: class jsautocompartment added in spidermonkey 24 js_newglobalobject added in spidermonkey 17 js_entercompartment added in spidermonkey 24 js_leavecompartment added in spidermonkey 24 js_getcompartmentprivate added in spidermonkey 1.8.5 js_setcompartmentprivate added in spidermonkey 1.8.5 js_getglobalforcompartmentornull added in spider...
...lete since jsapi 31 js_addroot obsolete since javascript 1.8.5 js_addnamedroot obsolete since javascript 1.8.5 js_addnamedrootrt obsolete since javascript 1.8.5 js_removeroot obsolete since javascript 1.8.5 js_removerootrt obsolete since javascript 1.8.5 js_mapgcroots obsolete since jsapi 19 jsgcmaprootfun obsolete since jsapi 19 js_dumpnamedroots obsolete since jsapi 19 local root scopes were another way of protecting objects from the garbage collector. they have been removed in js 1.8.5, though js_enterlocalrootscope obsolete since javascript 1.8.5 js_leavelocalrootscope obsolete since javascript 1.8.5 js_leavelocalrootscopewithresult obsolete since javascript 1.8.5 js_forgetlocalroot obsolete since javascript 1.8.5 added in spidermonkey 1.8 if an object contains refere...
...And 2 more matches
Components.utils.createObjectIn
this function is made available as a global in sandboxes which have the wantexporthelpers option set in the sandbox() constructor. note that this function is now mostly obsolete when you are using sandbox, because you can create an object in a different compartment using new. for example, to create a new object in the compartment identified by contentwindow: var newobject = new contentwindow.object(); but it is really needeed from firefox 30 onwards when trying to manipulate the dom window. see details in https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/. ...
... is really needeed from firefox 30 onwards when trying to manipulate the dom window. see details in https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/. ...
...bject = components.utils.createobjectin(obj, options); parameters obj an object indicating the compartment in which the new object should be created; the new object will be created in the scope of this object's compartment. options an object containing a single option defineas, which determines the name of the object in the target compartment. return value a new object in the specified scope. ...
...And 2 more matches
Working with windows in chrome code
ly, there's a better way. to declare a shared variable, we need to find a place that exists while the application is running and is easily accessible from the code in different chrome windows. there are actually a few such places. using javascript code modules javascript code modules is a simple method for creating shared global singleton objects that can be imported into any other javascript scope. the importing scope will have access to the objects and data in the code module. since the code module is cached, all scopes get the same instance of the code module and can share the data in the module. see components.utils.import for more information. pros: it's the "right way" very simple to make and import. no need to build an xpcom component. cons: only works in f...
... you can't use the window object, its members, like alert and open, and many other objects available from inside a window. ...
... you can't use the window object, its members, like alert and open, and many other objects available from inside a window. the functionality isn't lost, however -- you just have to use the xpcom components directly instead of using convenient shortcuts. ...
...And 2 more matches
Debugger.Object - Firefox Developer Tools
e otherwise. name the name of the referent, if it is a named function. if the referent is an anonymous function, or not a function at all, this is undefined. this accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function’s body). displayname the referent’s display name, if the referent is a function with a display name. if the referent is not a function, or if it has no display name, this is undefined. if a function has a given name, its display name is the same as its given name. in this case, the disp...
... created. if the referent is not a promise, throw a typeerror exception. promisetimetoresolution if the referent is a promise, this is the number of milliseconds elapsed between when the promise was created and when it was resolved. if the referent hasn’t been resolved or is not a promise, throw a typeerror exception. global a debugger.object instance referring to the global object in whose scope the referent was allocated. this does not unwrap cross-compartment wrappers: if the referent is a wrapper, the result refers to the wrapper’s global, not the wrapped object’s global. the result refers to the global directly, not via a wrapper. allocationsite if object allocation site tracking was enabled when this debugger.object’s referent was allocated, return the javascript execution s...
...aulting to the debugger.object if omitted. getownpropertydescriptor(name) return a property descriptor for the property namedname of the referent. if the referent has no such property, return undefined. (this function behaves like the standard object.getownpropertydescriptor function, except that the object being inspected is implicit; the property descriptor returned is allocated as if by code scoped to the debugger’s global object (and is thus in the debugger’s compartment); and its value, get, and set properties, if present, are debuggee values.) getownpropertynames() return an array of strings naming all the referent’s own properties, as if object.getownpropertynames(referent) had been called in the debuggee, and the result copied in the scope of the debugger’s global object. g...
...And 2 more matches
Debugger - Firefox Developer Tools
ally undefined. any value assigned to a debugging handler must be either a function or undefined; otherwise a typeerror is thrown. handler functions run in the same thread in which the event occurred. they run in the compartment to which they belong, not in a debuggee compartment. onnewscript(script,global) new code, represented by the debugger.script instancescript, has been loaded in the scope of the debuggees. this method’s return value is ignored. onnewpromise(promise) a new promise object, referenced by the debugger.object instance promise, has been allocated in the scope of the debuggees. the promise’s allocation stack can be obtained using the promiseallocationstack accessor property of the debugger.object instance promise. this handler method should return a resumpt...
...bject instance promise. this handler method should return a resumption value specifying how the debuggee’s execution should proceed. however, note that a { return:value } resumption value is treated like undefined (“continue normally”);value is ignored. onpromisesettled(promise) a promise object, referenced by the debugger.object instance promise that was allocated within a debuggee scope, has settled (either fulfilled or rejected). the promise’s state, fulfillment or rejection value, and the allocation and resolution stacks can be obtained using the promise-related accessor properties of the debugger.object instance promise. this handler method should return a resumption value specifying how the debuggee’s execution should proceed. however, note that a { return:value } resu...
...ppears only once in the array.query is an object whose properties restrict which sources are returned; a source must meet all the criteria given byquery to be returned. ifquery is omitted, we return all sources of all debuggee scripts. querymay have the following properties: url the source’s url property must be equal to this value. global the source must have been evaluated in the scope of the given global object. if this property’s value is a debugger.object instance belonging to this debugger instance, then its referent is used. if the object is not a global object, then the global in whose scope it was allocated is used. note that the result may include sources that can no longer ever be used by the debuggee: say, eval code that has finished running, or source for unrea...
...And 2 more matches
EventTarget.addEventListener() - Web APIs
a' }.bind(somestring)); this method is suitable when you don't need to know which html element the event listener fired on programmatically from within the event listener. the primary benefit to doing this is that the event listener receives the data in much the same way that it would if you were to actually pass it through its argument list. ...
... method is suitable when you don't need to know which html element the event listener fired on programmatically from within the event listener. the primary benefit to doing this is that the event listener receives the data in much the same way that it would if you were to actually pass it through its argument list. getting data into an event listener using the outer scope property when an outer scope contains a variable declaration (with const, let), all the inner functions declared in that scope have access to that variable (look here for information on outer/inner functions, and here for information on variable scope). therefore, one of the simplest ways to access data from outside of an event listener is to make it accessible to the scope in which the event listener is declared. const myb...
...t accessible to the scope in which the event listener is declared. const mybutton = document.getelementbyid('my-button-id'); const somestring = 'data'; mybutton.addeventlistener('click', function() { console.log(somestring); // expected value: 'data' somestring = 'data again'; }); console.log(somestring); // expected value: 'data' (will never output 'data again') note: although inner scopes have access to const, let variables from outer scopes, you cannot expect any changes to these variables to be accessible after the event listener definition, within the same outer scope. why? simply because by the time the event listener would execute, the scope in which it was defined would have already finished executing. getting data into and out of an event listener using objects unlike m...
...And 2 more matches
Basic concepts - Web APIs
time. transaction an atomic set of data-access and data-modification operations on a particular database. it is how you interact with the data in a database. in fact, any reading or changing of data in the database must happen in a transaction. ...
...action an atomic set of data-access and data-modification operations on a particular database. it is how you interact with the data in a database. in fact, any reading or changing of data in the database must happen in a transaction. a database connection can have several active transactions associated with it at a time, so long as the writing transactions do not have overlapping scopes. ...
...as for reading transactions, you can have several of them — even overlapping ones. ...
...And 2 more matches
Web APIs
Web › API
nt animationplaybackevent animationtimeline arraybufferview attr audiobuffer audiobuffersourcenode audioconfiguration audiocontext audiocontextlatencycategory audiocontextoptions audiodestinationnode audiolistener audionode audionodeoptions audioparam audioparamdescriptor audioparammap audioprocessingevent audioscheduledsourcenode audiotrack audiotracklist audioworklet audioworkletglobalscope audioworkletnode audioworkletnodeoptions audioworkletprocessor authenticatorassertionresponse authenticatorattestationresponse authenticatorresponse b baseaudiocontext basiccardrequest basiccardresponse batterymanager beforeinstallpromptevent beforeunloadevent biquadfilternode blob blobbuilder blobevent bluetooth bluetoothadvertisingdata bluetoothcharacteristicproperties blueto...
...vent d domconfiguration domerror 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 deprecationreportbody devicelightevent devicemotionevent devicemotioneventacceleration devicemotioneventrotationrate deviceorientationevent deviceproximityevent directoryentrysync directoryreadersync displaymediastreamconstraints document documentfragment documentorshadowroot documenttimeline documenttouch documenttype doublerange dragevent dynamicscompressornode e ext_bl...
...lesystementrysync filesystemfileentry filesystemflags filesystemsync focusevent fontface fontfaceset fontfacesetloadevent formdata formdataentryvalue formdataevent fullscreenoptions g gainnode gamepad gamepadbutton gamepadevent gamepadhapticactuator geolocation geolocationcoordinates geolocationposition geolocationpositionerror geometryutils gestureevent globaleventhandlers gyroscope h htmlanchorelement htmlareaelement htmlaudioelement htmlbrelement htmlbaseelement htmlbasefontelement htmlbodyelement htmlbuttonelement htmlcanvaselement htmlcollection htmlcontentelement htmldlistelement htmldataelement htmldatalistelement htmldetailselement htmldialogelement htmldivelement htmldocument htmlelement htmlembedelement htmlfieldsetelement htmlfontelement htmlformcontrolsco...
...And 2 more matches
Grammar and types - JavaScript
...
...tifiers. some examples of legal names are number_hits, temp99, $credit, and _name. declaring variables you can declare a variable in two ways: with the keyword var. for example, var x = 42. this syntax can be used to declare both local and global variables, depending on the execution context. with the keyword const or let. for example, let y = 13. this syntax can be used to declare a block-scope local variable. (see variable scope below.) you can also simply assign a value to a variable for example, x = 42. this form creates an undeclared 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 ...
...ause the myarray element is undefined: var myarray = []; if (!myarray[0]) myfunction(); the undefined value converts to nan when used in numeric context. var a; a + 2; // evaluates to nan when you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. for example: var n = null; console.log(n * 32); // will log 0 to the console variable scope when you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. when you declare a variable within a function, it is called a local variable, because it is available only within that function. javascript before ecmascript 2015 does not have block statement scope. rather, a variable declared within a block is...
...And 2 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
either receive a use permit from the copyright holder, or must be assigned partial rights by the author. this use permit for a copyrighted work is called a license. when we talk about a driver’s license, we mean a permit to drive a car. when we talk about a license to kill, we mean james bond. a license on a copyrighted work is a use permit that says “it’s ok to use this work within this scope, as long as you follow these conditions.” those conditions could be something like “if you pay me money” or “you can print up to 10,000 copies.” software licenses software is subject to copyright law. in order to use it (in the authorial sense), you need permission from the copyright holder. how software licenses work in order to duplicate, distribute, or modify software, you need a...
...ll it on their computers, they cannot modify it. and essential freedoms, such as reverse-engineering, are also restricted. this use permit is displayed when you install the software. when the user clicks “i agree,” the installation process finishes. software range of uses restricted to author unrestricted software license >> usable within permitted scope restricted use within permitted scope fixme: wow, the table is weird! so what’s an oss license? so now you’re wondering, what conditions does an oss license place on software? this can be briefly answered by the open source definition, which was determined by the open source initiative (osi). this covers three rights and six conditions. what is im...
... away there’s nothing in an oss license that prevents you from charging money for software. one of the advantages of oss is that it emphasizes that software can be distributed for free, but it can also be distributed for money. of course, customers who buys the software can then redistribute it themselves, so unless you provide some added value, you’ll have a hard time building a business. scope of modifications in the open-source world, “copyleft” is when you require that any modifications to your source code must also be released under the same terms. the following tasks can be considered modifications revision: rewriting the source code; addition: adding new code, or adding parts of it to other code; linkage: creating static or dynamic links. depending on what kind of modifi...
... mpl will give the text of the license at the top; if it’s gpl or lgpl, there will be a license declaration. the full text of the license should also appear packaged in the same archive as the source code. if you’ve modified existing source code if you are modifying existing source code, you need to judge whether or not to publish your revised version at all. see the previously mentioned “scope of modification.” using the same license as the existing work is a straightforward option. if you are not going to be distributing the modified software at all, and will only be using it within your own organization, you need not release it. for example, if you are using an modified version of linux as the operating system for a web server, it’s fine if you don’t release it. picking a lic...
Index - Archive of obsolete content
eads in a folder, and some meta information about the folder. 553 metro browser chrome tests automated testing, developing mozilla, metro browser the metro browser chrome test suite is an automated testing framework designed to allow testing of the immersive version of firefox for windows 8 and above using javascript. it currently allows you to run javascript code in the same scope as the immersive browser and report results using the same functions as the mochitest test framework. 554 microsummary topics microsummaries to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsim...
... debug, javascript, method, reference, msupdateasynccallbackrelation the debug.msupdateasynccallbackrelation function updates the relationship status between a synchronous work item and the associated asynchronous operation. 2029 debug.setnonusercodeexceptions debug, example, javascript, property, setnonusercodeexceptions if this property is set to true within a given scope, the debugger can then choose whether to take some specified action on exceptions thrown inside that scope: for instance, if the developer wishes to break on user-unhandled exceptions. setting this property to false is the same as never having set the property. 2030 debug.write debug, example, javascript, method, write the debug.write function sends strings to the script debu...
... makefile - .mk files no summary! 3415 misc top level these pages were moved from the top level of mdn in a spate of furious reorganization. 3416 bypassing security restrictions and signing code security, web development early versions of firefox allowed web sites to segregate principals using signed scripts, and request extra permissions for scopes within signed scripts using a function called enableprivelege. these privilege manager feature was not used much (aside from abuse), and its complexity made performance improvements difficult. signed script segregation was removed in bug 726125, the enableprivilege prompt was removed in bug 750859, and enableprivilege itself was nerfed in bug 757046. 3417 creating a web based tone gen...
...n_getvalue. 3632 npn_createobject npapi, plugins allocates a new npobject. 3633 npn_destroystream api, gecko, npapi, plugins, reference closes and deletes a stream. 3634 npn_enumerate gets the names of the properties and methods of the specified npobject. 3635 npn_evaluate npapi, plugins evaluates a script in the scope of the specified npobject. 3636 npn_forceredraw npapi, plugins asks the plugin host to immediately (synchronously) repaint invalid areas. 3637 npn_getauthenticationinfo the function is called by plugins to get http authentication information from the browser. 3638 npn_getintidentifier npapi, plugins returns an opaque identifier for t...
Gecko FAQ - Gecko Redirect 1
project working to support, and to what extent does it support them? ...
...rking to support, and to what extent does it support them? ...
...pport, and to what extent does it support them? ...
...at extent does it support them? ...
Styling tables - Learn web development
es. a typical html table let's start by looking at a typical html table. well, i say typical — most html table examples are about shoes, or the weather, or employees; we decided to make things more interesting by making it about famous punk bands from the uk. ...
... let's start by looking at a typical html table. well, i say typical — most html table examples are about shoes, or the weather, or employees; we decided to make things more interesting by making it about famous punk bands from the uk. ...
...ml table. well, i say typical — most html table examples are about shoes, or the weather, or employees; we decided to make things more interesting by making it about famous punk bands from the uk. the markup looks like so: <table> <caption>a summary of the uk's most famous punk bands</caption> <thead> <tr> <th scope="col">band</th> <th scope="col">year formed</th> <th scope="col">no. of albums</th> <th scope="col">most famous song</th> </tr> </thead> <tbody> <tr> <th scope="row">buzzcocks</th> <td>1976</td> <td>9</td> <td>ever fallen in love (with someone you shouldn't've)</td> </tr> <tr> <th scope="row">the clash</th> <td>1976</td> <td>6</td> <td>london calling</td> </tr> ... some ...
...l">most famous song</th> </tr> </thead> <tbody> <tr> <th scope="row">buzzcocks</th> <td>1976</td> <td>9</td> <td>ever fallen in love (with someone you shouldn't've)</td> </tr> <tr> <th scope="row">the clash</th> <td>1976</td> <td>6</td> <td>london calling</td> </tr> ... some rows removed for brevity <tr> <th scope="row">the stranglers</th> <td>1974</td> <td>17</td> <td>no more heroes</td> </tr> </tbody> <tfoot> <tr> <th scope="row" colspan="2">total albums</th> <td colspan="2">77</td> </tr> </tfoot> </table> the table is nicely marked up, easily styleable, and accessible, thanks to features such as scope, <caption>, <thead>, <tbody>, etc. unfortunately, it d...
Choosing the right approach - Learn web development
ng internetsettimeoutchrome full support 30edge full support 12firefox full support 1 full support 1 full support 52notes notes setinterval now defined on windoworworkerglobalscope mixin.ie full support 4opera full support 4safari full support 1webview android full support 4.4chrome android full support 30firefox android full support ...
... android full support 4.4chrome android full support 30firefox android full support 4 full support 4 full support 52notes notes setinterval now defined on windoworworkerglobalscope mixin.opera android full support 10.1safari ios full support 1samsung internet android full support 3.0supports parameters for callbackchrome full support yesedge full support ...
...g internetsetintervalchrome full support 30edge full support 12firefox full support 1 full support 1 full support 52notes notes setinterval now defined on windoworworkerglobalscope mixin.ie full support 4opera full support 4safari full support 1webview android full support 4.4chrome android full support 30firefox android full support ...
... android full support 4.4chrome android full support 30firefox android full support 4 full support 4 full support 52notes notes setinterval now defined on windoworworkerglobalscope mixin.opera android full support 10.1safari ios full support 1samsung internet android full support 3.0supports parameters for callbackchrome full support yesedge full support ...
Command line crash course - Learn web development
more complex example let’s go through something a bit more complicated. we will first try to fetch the contents of mdn's "fetch" page using the curl command (which can be used to request content from urls), from /docs/web/api/fetch. however, this url is the old location of the page. if you enter it in a new browser tab, you’ll (eventually) get redirected to /docs/web/api/windoworworkerglobalscope/fetch. therefore, if you use curl to request /docs/web/api/fetch, you won’t get an output. try it now: curl /docs/web/api/fetch we need to explicitly tell curl to follow redirects using the -l flag. let's also look at the headers that developer.mozilla.org returns using curl's -i flag, and print all the location redirects it sends to the terminal, by piping the output of curl into grep (we ...
...for that, we'll add awk to the mix (which is a programming language akin to javascript or ruby or python, just a lot older!). try running this: curl /docs/web/api/fetch -l -i | grep location | a...
...mix (which is a programming language akin to javascript or ruby or python, just a lot older!). try running this: curl /docs/web/api/fetch -l -i | grep location | awk '{ print "https://developer.mozilla.org" $2 }' your final output should look something like this: /docs/web/api/fetch /docs/web/api/globalfetch/globalfetch.fetch() /docs/web/api/globalfetch/fetch /docs/web/api/windoworworkerglobalscope/fetch by combining these commands we've customised the output to show the full urls that the mozilla server is redirecting through when we request the /docs/web/api/fetch url. getting to know your system will prove useful in years to come — learn how these single serving tools work and how they can become part of your arsenal to solve niche problems. adding powerups now we’ve had a look a...
... console.log(obj.b.c); } printme(myobj); depending on your workflow (or the workflow that you pick) you can make this an automated part of your process. automation is really where tools excel; our personal preference is the kind of automation that "just happens" without having to configure anything. with prettier there's a number of ways automation can be achieved and though they're beyond the scope of this article, there's some excellent resources online to help (some of which have been linked to). you can invoke prettier: before you commit your code into a git repository using husky. whenever you hit "save" in your code editor, be it vs code, atom, or sublime text. as part of continuous integration checks using tools like github actions. our personal preference is the second one —...
Storage access policy: Block cookies from trackers
ly restrict third-party storage access for resources that are not classified as tracking resources. we may choose to apply additional restrictions to third-party storage access in the future. the restrictions applied by the policy will not prevent third-party scripts classified as tracking resources from accessing storage in the main context of the page. these scripts can continue to use storage scoped to the top-level origin. origins classified as trackers will have access to their own storage when they are loaded in a first-party context. cross-origin resources loaded from the same etld+1 as the top-level context will still have access to their storage. origins normally classified as trackers will not be blocked if the top-level page origin is determined to be from the same organization a...
...aded from the same etld+1 as the top-level context will still have access to their storage. origins normally classified as trackers will not be blocked if the top-level page origin is determined to be from the same organization as them. storage access grants in order to improve web compatibility and permit third-party integrations that require storage access, firefox will grant storage access scoped to the first party for a particular third-party origin as described in this section. currently, firefox includes some web compatibility heuristics that grant storage access to third-party resources classified as trackers when a user interacts with those third parties. we do this when we expect that not granting access would cause the web page to break. we also support an initial implementation o...
...g origin to a non-tracking origin, the tracking origin receives short-lived storage access on the non-tracking origin and any other non-tracking origins that appear further down the redirect chain (i.e., if the load continues to redirect). the tracking origin must have received user interaction as a first party within the past 30 days, and the storage access permission expires after 15 minutes. scope of storage access when storage access is granted, it is scoped to the origin of the opener document or subdomains of that origin. access that is granted on the subdomain of an origin does not extend to the top-level origin. as an example, if a resource from tracker.example is granted storage access on foo.example.com, then tracker.example will be able to access its cookies on bar.foo.example.com...
...ing identifiers does not prevent the display of advertisements. i use a third-party analytics service that is classified as a tracker. will i still receive analytics data? this depends on how the third-party analytics service is implemented. third-party analytics providers will no longer be able to user their third-party storage to collect data. this means that providers using cookies which are scoped to their third-party domain, or local storage and other site data stored under their origin, will no longer have access to those identifiers across other websites. if these services are embedded into the main context of the page, they can continue to use first-party cookies and site storage to track users across page visits on that specific first-party domain. i use third-party services for so...
Script security
erved from https://example.org/ can access each other, and they can also access objects served from https://example.org/foo. objects that are cross-origin get highly restricted access to each other, according to the same-origin policy. for example, code served from https://example.org/ trying to access objects from https://somewhere-else.org/ will have restricted access. ...
...n also access objects served from https://example.org/foo. objects that are cross-origin get highly restricted access to each other, according to the same-origin policy. for example, code served from https://example.org/ trying to access objects from https://somewhere-else.org/ will have restricted access. ...
...ame-origin policy. for example, code served from https://example.org/ trying to access objects from https://somewhere-else.org/ will have restricted access. objects in a privileged scope are allowed complete access to objects in a less privileged scope, but by default they see a restricted view of such objects, designed to prevent them from being tricked by the untrusted code. an example of this scope is chrome-privileged javascript accessing web content. objects in a less privileged scope don't get any access to objects in a more privileged scope, unless the more privileged scope explicitly clones those objects. an example of this scope is web content accessing objects in a chrome-privileged scope. compartments compartments are the foundation for gecko's script security architecture. a c...
...ys if it wants unfiltered access to the untrusted object. see xray vision for much more information on xrays. unprivileged to privileged code if the caller has lower privileges than the target object, then the caller gets an opaque wrapper. an opaque wrapper denies all access to the target object. however, the privileged target is able to copy objects and functions into the less privileged scope using the exportfunction() and cloneinto() functions, and the less privileged scope is then able to use them. security checks to determine the security relation between two compartments, gecko uses two concepts: security principals and the act of subsuming. to establish the security relationship between two compartments a and b, gecko asks: does the security principal for compartment a subsume...
Threads
minated and has finished with both the resources to which the thread has access and the resources of the thread itself. for an overview of the nspr threading model and sample code that illustrates its use, see introduction to nspr. for api reference information related to thread synchronization, see locks and condition variables. threading types and constants prthread prthreadtype prthreadscope prthreadstate prthreadpriority prthreadprivatedtor threading functions most of the functions described here accept a pointer to the thread as an argument. nspr does not check for the validity of the thread. it is the caller's responsibility to ensure that the thread is valid. the effects of these functions on invalid threads are undefined. creating, joining, and identifying threads cont...
...d here accept a pointer to the thread as an argument. nspr does not check for the validity of the thread. it is the caller's responsibility to ensure that the thread is valid. the effects of these functions on invalid threads are undefined. creating, joining, and identifying threads controlling thread priorities interrupting and yielding setting global thread concurrency getting a thread's scope creating, joining, and identifying threads pr_createthread creates a new thread. pr_jointhread blocks the calling thread until a specified thread terminates. pr_getcurrentthread returns the current thread object for the currently running code. pr_attachthread associates a prthread object with an existing native thread. pr_detachthread disassociates a prthread object from a native thr...
... ...
...the thread until the notification either has been delivered exactly once or is cleared. pr_clearinterrupt clears a previous interrupt request. pr_sleep causes a thread to yield to other threads for a specified number of ticks. setting global thread concurrency pr_setconcurrency sets the number of global threads used by nspr to create local threads. getting a thread's scope pr_getthreadscope gets the scoping of the current thread. ...
Functions
in javascript and compiled to bytecode. there are four variations that affect how nameexpressions are evaluated. (nameexpressions are basic expressions like string and x that would eat up a huge amount of run time if the engine weren't smart enough to avoid symbol table lookups.) general closures are the base case. when the function object is created, its parent is set to the first object on the scope chain. when a name is evaluated that doesn't refer to a local variable, the interpreter consults the scope chain to find the variable. when with or eval are used, we have to do this for correctness. this is slow, not only because walking the scope chain is a drag, but also because we'd rather avoid actually creating the scope chain at all, if possible. general closures force the interpreter to ve...
...name is evaluated that doesn't refer to a local variable, the interpreter consults the scope chain to find the variable. when with or eval are used, we have to do this for correctness. this is slow, not only because walking the scope chain is a drag, but also because we'd rather avoid actually creating the scope chain at all, if possible. general closures force the interpreter to verify the whole scope chain. so we optimize this when we can. these optimizations depend on being sure that we will never have to walk the scope chain, so with and eval inhibit them all. null closures. if we can prove at compile time that a function does not refer to any locals or arguments of enclosing functions, it is a null closure. since it will never need to walk the scope chain, its parent is the global object. ...
... if the function does not assign to any closed-on vars/args, and it only reads closed-on local variables and arguments that never change value after the function is created, then the function can be implemented as a flat closure. when a flat closure is created, all the closed-on values are copied from the stack into reserved slots of the function object. to evaluate a name, instead of walking the scope chain, we just take the value from the reserved slot. the function object's parent is the global object. flat closures and null closures have been removed: https://bugzilla.mozilla.org/show_bug.cgi?id=730497 https://bugzilla.mozilla.org/show_bug.cgi?id=739808 name lookups in order of speed, fastest to slowest. arg and local instructions. if a name definitely refers to an argument or local va...
...it's a non-configurable data property (which amounts to the same thing). otherwise the gvar instructions are as slow as name instructions. there are also combo instructions jsop_{inc,dec}gvar and jsop_gvar{inc,dec}. name instructions. in the worst case we emit jsop_{,set,call}name. these are totally general. they can still be optimized via the property cache; in the worst case we walk the scope chain. in some cases, the jit can optimize a jsop_name instruction that refers to a variable in an enclosing scope to pull the value directly out of the call object's dslots. for the expression delete name we always emit jsop_delname. it's not worth optimizing. ...
JS::CompileFunction
this article covers features introduced in spidermonkey 17 create a javascript function from a text string. ...
...m a text string. ...
...requires request. in a js_threadsafe build, th...
...s &options, const char *name, unsigned nargs, const char *const *argnames, const char *bytes, size_t length, js::mutablehandlefunction fun); name type description cx jscontext * the context in which to compile the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. scopechain js::autoobjectvector &amp; the scope in which to compile the function. options js::readonlycompileoptions &amp; compile options. name const char * name to assign the newly compiled function. nargs unsigned number of arguments to pass to the function. argnames const char *const * names to assign to the arguments passed to the f...
JS_ForgetLocalRoot
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. remove a value from the innermost current local root scope. syntax void js_forgetlocalroot(jscontext *cx, void *thing); name type description cx jscontext * pointer to the context in which the caller is running. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...escription cx jscontext * pointer to the context in which the caller is running. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. thing void * pointer to the value to be unrooted. this must point to a jsobject, jsstring, jsfunction, or jsdouble. it must not be null. description this function is used to interact with scoped local root management. see js_enterlocalrootscope for more on this topic. in case a native hook allocates many objects or other gc-things, but the native protects some of those gc-things by storing them as property values in an object that is itself protected, the hook can call js_forgetlocalroot to free the local root automatically pushed for the now-protected gc-thing. (here the term gc-thing ...
...ings by storing them as property values in an object that is itself protected, the hook can call js_forgetlocalroot to free the local root automatically pushed for the now-protected gc-thing. (here the term gc-thing refers to any value that is subject to garbage collection: a jsobject, jsstring, jsfunction, or jsdouble.) js_forgetlocalroot works on any gc-thing allocated in the current local root scope, but it's more time-efficient when called on references to more recently created gc-things. calling it successively on other than the most recently allocated gc-thing will tend to average the time inefficiency, and may risk o(n2) growth rate, but in any event, you shouldn't allocate too many local roots if you can root as you go (build a tree of objects from the top down, forgetting each latest-a...
...see also bug 519949 bug 803907 ...
SpiderMonkey 1.8.7
nspr (e.g. --with-system-nspr). xxx all sections below need updating garbage collection spidermonkey 1.8.5 introduces a conservative stack-scanning garbage collector. unlike the exact garbage collector, the new garbage collector will scan the c stack and registers in your embedding, looking for bits that it can treat as potential gc roots. the approach eliminates the need for the js_enterlocalrootscope api, and in many cases 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 s...
...executeregexp js_executeregexpnostatics js_executescriptversion js_forget_string_flatness js_fileescapedstring js_finishjsonparse (removed in future releases, replaced with js_parsejson) js_flatstringequalsascii js_flattenstring js_flushcaches js_freezeobject js_getcompartmentprivate js_getemptystring js_getflatstringchars js_getgcparameter js_getgcparameterforthread js_getglobalforscopechain js_getinternedstringchars js_getinternedstringcharsandlength js_getownpropertydescriptor js_getpropertyattrsgetterandsetterbyid js_getpropertybyid js_getpropertybyiddefault js_getpropertydefault js_getpropertydescriptorbyid js_getruntimesecuritycallbacks js_getsecuritycallbacks js_getstringcharsandlength js_getstringcharsz js_getstringcharszandlength js_getstringencodinglength ...
...helpers while jsapi remains a c api, the engine is now implemented in c++. some c++ helpers have been introduced into the api, to help embedders writing c++ projects. please note that spidermonkey reserves the js:: namespace for itself. jsautorequest jsautosuspendrequest jsautocheckrequest jsautoentercompartment js::anchor<> js::call obsolete apis js_clearnewbornroots js_enterlocalrootscope js_leavelocalrootscope js_leavelocalrootscopewithresult js_forgetlocalroot js_newgrowablestring deleted apis js_getscopechain use js_getglobalforscopechain api changes operation callback js_setoperationcallback was introduced in js 1.8.0, replacing the branch callback, in anticipation of the addition of the tracing jit (tracemonkey). the interface was finalized only after js 1.8.0 shipped...
...ls to passing jsid as part of bug 549143. this bug introduced "fat" (64-bit) unboxed valued into the engine. garbage collection js_markgcthing was changed in bug 549143 to mark jsvals rather than void pointers (gc root addresses), improving the typed rooting api which was introduced in bug 565157. a conservative stack-scanning collector was also added for spidermonkey 1.8.5, making the *localrootscope apis obsolete; they are now nops. bug 614138 introduces a c++ js::anchor<> template class to help tie lexical scope to the conservative gc for cases where the compiler might optimize away important stack/register roots (such as when we access the jschars in a jsstring). a c analogue, js_anchorptr, was introduced with bug 630209. bug 630209 also removed the need for js_newscriptobject, by modify...
SpiderMonkey 45
ates to its language features, yo. new c++ apis jsapi is a c++ exclusive api. please note that spidermonkey reserves the js:: namespace for itself for public exports and the js:: namespace for internal use. ...
...apis jsapi is a c++ exclusive api. please note that spidermonkey reserves the js:: namespace for itself for public exports and the js:: namespace for internal use. ...
...e note that spidermonkey reserves the js:: namespace for itself for public exports and the js:: namespace for internal use. ...
...(bug 987514) js::toprimitive (bug 1206168) js::getfirstargumentastypehint (bug 1054756) js::objecttocompletepropertydescriptor (bug 1144366) js_setimmutableprototype (bug 1211607) js_getownucpropertydescriptor (bug 1211607) js_hasownpropertybyid (bug 1211607) js_hasownproperty (bug 1211607) js_deleteucproperty (bug 1211607) js::newfunctionfromspec (bug 1054756) js::compilefornonsyntacticscope (bug 1165486) js_checkforinterrupt (bug 1058695) js::mapdelete (bug 1159469) js::mapforeach (bug 1159469) js::newsetobject (bug 1159469) js::setsize (bug 1159469) js::sethas (bug 1159469) js::setdelete (bug 1159469) js::setadd (bug 1159469) js::setclear (bug 1159469) js::setkeys (bug 1159469) js::setvalues (bug 1159469) js::setentries (bug 1159469) js::setforeach (bug 1159469) js::e...
Shell global objects
efined addintlextras(obj) adds various not-yet-standardized intl functions as properties on the provided object (this should generally be intl itself). the added functions and their behavior are experimental: don't depend upon them unless you're willing to update your code if these experimental apis change underneath you. functions available if --fuzzing-safe is not specified clone(fun[, scope]) clone function object. getselfhostedvalue() get a self-hosted value by its name. note that these values don't get cached, so repeatedly getting the same value creates multiple distinct clones. line2pc([fun,] line) map line number to pc. pc2line(fun[, pc]) map pc to line number. nestedshell(shellargs...) execute the given code in a new js shell process, passing this nested shell the arg...
...ind. wrapwithproto(obj) wrap an object into a noop wrapper with prototype semantics. note: this is not fuzzing safe because it can be used to construct deeply nested wrapper chains that cannot exist in the wild. trackedopts(fun) returns an object describing the tracked optimizations of fun, if any. if fun is not a scripted function or has not been compiled by ion, null is returned. dumpscopechain(obj) prints the scope chain of an interpreted function or a module. crash([message]) crashes the process with a moz_crash. setarmhwcapflags("flag1,flag2 flag3") on non-arm, no-op. on arm, set the hardware capabilities. the list of flags is available by calling this function with help as the flag's name wasmloop(filename, imports) performs an afl-style persistent loop reading data from...
...rget, or undefined if target is unreachable from start. each element of the array is either of the form: { node: {object or string}, edge: {string describing edge from node} } , if the node is a javascript object or value; or of the form: { type: {string describing node}, edge: {string describing edge} } , if the node is some internal thing that is not a proper javascript value (like a shape or a scope chain element). the destination of the i'th array element's edge is the node of the i+1'th array element; the destination of the last array element is implicitly target. shortestpaths(start, targets, maxnumpaths) return an array of arrays of shortest retaining paths. there is an array of shortest retaining paths for each object in targets. the maximum number of paths in each of those arrays is ...
...paths(start, targets, maxnumpaths) return an array of arrays of shortest retaining paths. there is an array of shortest retaining paths for each object in targets. the maximum number of paths in each of those arrays is bounded by maxnumpaths. each element in a path is of the form { predecessor, edge }. sharedmemoryenabled() return true if sharedarraybuffer and atomics are enabled evalreturningscope(scriptstr, [global]) evaluate the script in a new scope and return the scope. if global is present, clone the script to global before executing. cloneandexecutescript(source, global) compile source in the current compartment, clone it into global's compartment, and run it there. backtrace() dump out a brief backtrace. getbacktrace([options]) return the current stack as a string. takes an o...
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
se in a class: class nodecontainer { public: void addnode(nsinode* node); private: nscomarray<nsinode> mnodes; }; // typesafety of mnodes ensures that we only append an nsinode* void nodecontainer::addnode(nsinode* node) { mnodes.appendobject(node); } nscomarray<t> can also be declared on the stack to collect a temporary list of objects and manipulate them. when the object goes out of scope, all its members are released. void processvisibleitems() { // temporary stack-based nscomarray nscomarray<nsifoo> fooitems; getcompletelist(fooitems); // now filter out non visible objects // doing this backwards pruint32 i = fooitems.count(); while (i > 0) { --i; prbool isvisible; fooitems[i]->getisvisible(&isvisible); if (!isvisible) { fooitems.removeobjec...
...when using the [] operator, the reference count is unchanged. this allows direct processing of array elements without worrying about calling release(). for example, this code calls the same method on each member: void notifyobservers(const nscomarray<nsimyobserver>& observers) { ...
... medialist { public: void addmedium(const nsstring& amedium); private: nstarray<nsstring> mmedia; }; // typesafety of mmedia ensures that we only append an nsstring void nodecontainer::addmedium(const nsstring& amedium) { mmedia.appendelement(amedium); } nstarray<t> can also be declared on the stack to collect a temporary list of objects and manipulate them. when the object goes out of scope, all its members have their destructors called. note that if the nstarray<t> holds pointers to objects, the objects will not be deleted (and hence not have their destructors called). you can work around this by using nstarray<uniqueptr<t>> instead. void processvisibleitems() { // temporary stack-based nstarray nstarray<foostruct> fooitems; getcompletelist(fooitems); // now filter out no...
... for example, this code calls the same method on each member: void notifyobservers(const nstarray<observerclass*>& observers) { for (pruint32 i = observers.length(); i > 0 ; ) { --i; observers[i]->observe(); } } bounds-safe access to elements you can also access eleme...
nsIMsgFolder
d notifyunicharpropertychanged(in nsiatom property, in astring oldvalue, in astring newvalue); void notifyitemadded(in nsisupports item); void notifyitemremoved(in nsisupports item); void notifyfolderevent(in nsiatom event); void listdescendents(in nsisupportsarray descendents); void shutdown(in boolean shutdownchildren); void setinvfeditsearchscope(in boolean asearchthisfolder, in boolean asetonsubfolders); void copydatatooutputstreamforappend(in nsiinputstream aistream, in long alength, in nsioutputstream outputstream); void copydatadone(); void setjunkscoreformessages(in nsisupportsarray amessages, in acstring ajunkscore); void applyretentionsettings(); boolean fetchmsgpreviewtext([array, size_...
...gfolder items that are subfolders of the instance this is called on. hassubfolders boolean readonly: returns true if this folder has sub folders. messages nsisimpleenumerator readonly: returns a list of components.interfaces.nsimsgdbhdr. numsubfolders unsigned long readonly: returns the number of sub folders that this folder has. invfeditsearchscope boolean readonly customidentity nsimsgidentity readonly: this allows a folder to have a special identity. e.g., you might want to associate an identity with a particular newsgroup, or for imap shared folders in the other users namespace, you might want to create a delegated identity. gettingnewmessages boolean are we running a url as a result of the user click...
...added() void notifyitemadded(in nsisupports item); notifyitemremoved() void notifyitemremoved(in nsisupports item); notifyfolderevent() void notifyfolderevent(in nsiatom event); listdescendents() ists all descendents, not just first level children. ...
...n nsisupports item); notifyitemremoved() void notifyitemremoved(in nsisupports item); notifyfolderevent() void notifyfolderevent(in nsiatom event); listdescendents() ists all descendents, not just first level children. ...
nsIMsgSearchTerm
coreorigin /* * test search term match for junkscoreorigin * @param ajunkscoreorigin who set junk score? possible values: * plugin filter imapflag user whitelist * @return true if matches */ boolean matchjunkscoreorigin(in string ajunkscoreorigin); matchbody /** * test if the body of the passed in message matches "this" search term. ...
... /* * test search term match for junkscoreorigin * @param ajunkscoreorigin who set junk score? possible values: * plugin filter imapflag user whitelist * @return true if matches */ boolean matchjunkscoreorigin(in string ajunkscoreorigin); matchbody /** * test if the body of the passed in message matches "this" search term. ...
...g ajunkscoreorigin); matchbody /** * test if the body of the passed in message matches "this" search term. * @param ascopeterm scope of search * @param aoffset offset of message in message store. * @param alength length of message. * @param acharset folder charset. * @param amsg db msg hdr of message to match. * @param adb db containing msg header. ...
...eorigin); matchbody /** * test if the body of the passed in message matches "this" search term. * @param ascopeterm scope of search * @param aoffset offset of message in message store. * @param alength length of message. * @param acharset folder charset. * @param amsg db msg hdr of message to match. * @param adb db containing msg header. ...
UI Tour - Firefox Developer Tools
this article is a quick tour of the main sections of the javascript debugger's user interface. the ui is split vertically into three panels source list pane source pane the contents of the third pane depend on the current state of the debugger and may include the following sections: toolbar watch expressions breakpoints call stack scopes xhr breakpoints event listener breakpoints dom mutation breakpoints source list pane the source list pane lists all the javascript source files loaded into the page, and enables you to select one to debug. at the top level sources are organized by origin, and under that they're organized by the directory structure from which they are served. you can search for a file using ctrl + p (cmd + p on a mac). web extension...
...lipboard. ignore source causes the debugger to skip the file when "stepping into" functions. any stack frames from the ignored source file are hidden in the call stack pane. (to remove this restriction, choose unignore source in the context menu of the sources list or the source pane.) copy stack trace copies all items in the call stack (including their uris and line number) to the clipboard. ...
...p the file when "stepping into" functions. any stack frames from the ignored source file are hidden in the call stack pane. (to remove this restriction, choose unignore source in the context menu of the sources list or the source pane.) copy stack trace copies all items in the call stack (including their uris and line number) to the clipboard. scopes in the right-hand pane you'll see a label "scopes" with a disclosure arrow next to it. ...
...estriction, choose unignore source in the context menu of the sources list or the source pane.) copy stack trace copies all items in the call stack (including their uris and line number) to the clipboard. scopes in the right-hand pane you'll see a label "scopes" with a disclosure arrow next to it. when the debugger's paused, you'll be able to expand this section to see all objects that are in scope at this point in the program: objects are organized by scope: the most local appears first, and the global scope (window, in the case of page scripts) appears last. within the scopes pane, you can create watchpoints that pause the debugger when a value is read or assigned. ...
Debugger.Environment - Firefox Developer Tools
a debugger.environment instance represents a lexical environment, associating names with variables. each debugger.frame instance representing a debuggee frame has an associated environment object describing the variables in scope in that frame; and each debugger.object instance representing a debuggee function has an environment object representing the environment the function has closed over. ecmascript environments form a tree, in which each local environment is parented by its enclosing environment (in ecmascript terms, its ‘outer’ environment). ...
...representing the environment the function has closed over. ecmascript environments form a tree, in which each local environment is parented by its enclosing environment (in ecmascript terms, its ‘outer’ environment). we say an environmentbinds an identifier if that environment itself associates the identifier with a variable, independently of its outer environments. we say an identifier isin scope in an environment if the identifier is bound in that environment or any enclosing environment. spidermonkey creates debugger.environment instances as needed as the debugger inspects stack frames and function objects; calling debugger.environment as a function or constructor raises a typeerror exception. spidermonkey creates exactly one debugger.environment instance for each environment it prese...
... enclosing environments. getvariable(name) return the value of the variable bound toname in this environment, or undefined if this environment does not bindname.name must be a string that is a valid ecmascript identifier name. the result is a debuggee value. javascript engines often omit variables from environments, to save space and reduce execution time. if the given variable should be in scope, but getvariable is unable to produce its value, it returns an ordinary javascript object (not a debugger.object instance) whose optimizedout property is true. this is not an invocation function; if this call would cause debuggee code to run (say, because the environment is a "with" environment, andname refers to an accessor property of the with statement’s operand), this call throws a debugg...
...script identifier name;value must be a debuggee value. if this environment binds no variable namedname, throw a referenceerror. this is not an invocation function; if this call would cause debuggee code to run, this call throws a debugger.debuggeewouldrun exception. find(name) return a reference to the innermost environment, starting with this environment, that bindsname. ifname is not in scope in this environment, return null.name must be a string whose value is a valid ecmascript identifier name. source metadata generated from file: js/src/doc/debugger/debugger.environment.md watermark: sha256:3d6f67939e351803d5d7fe201ed38c4aaf766caf032f255e168df1f1c6fe73cb changeset: 7ae377917236 ...
Debugger.Object - Firefox Developer Tools
otherwise. name the name of the referent, if it is a named function. if the referent is an anonymous function, or not a function at all, this is undefined. this accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function's body). displayname the referent's display name, if the referent is a function with a display name. if the referent is not a function, or if it has no display name, this is undefined. if a function has a given name, its display name is the same as its given name. in this case, the displayn...
...nstructtrap if the referent is a function proxy whose handler object was allocated by debuggee code, its construction trap function—the function called when the function proxy is called via a new expression. if the referent is not a function proxy whose handler object was allocated by debuggee code, this is null. global a debugger.object instance referring to the global object in whose scope the referent was allocated. this does not unwrap cross-compartment wrappers: if the referent is a wrapper, the result refers to the wrapper's global, not the wrapped object's global. the result refers to the global directly, not via a wrapper. hostannotations a javascript object providing further metadata about the referent, or null if none is available. the metadata object is in the same c...
...application-specific functionality to scripts. the hostannotations accessor consults the embedding for additional information about the referent that might be of interest to the debugger. the returned object's properties' meanings are up to the embedding. for example, a web browser might provide host annotations for global objects to distinguish top-level windows, iframes, and internal javascript scopes. by convention, host annotation objects have a string-valued "type" property that, taken together with the object's class, indicate what sort of thing the referent is. the host annotation object's other properties provide further details, as appropriate for the type. for example, in firefox, a metadata object for a javascript module's global object might look like this: { "type":"jsm", "uri"...
...string;value must be a debuggee value. getownpropertydescriptor(name) return a property descriptor for the property namedname of the referent. if the referent has no such property, return undefined. (this function behaves like the standard object.getownpropertydescriptor function, except that the object being inspected is implicit; the property descriptor returned is allocated as if by code scoped to the debugger's global object (and is thus in the debugger's compartment); and its value, get, and set properties, if present, are debuggee values.) getownpropertynames() return an array of strings naming all the referent's own properties, as if object.getownpropertynames(referent) had been called in the debuggee, and the result copied in the scope of the debugger's global object. def...
AnalyserNode - Web APIs
or time-domain, data into a uint8array (unsigned byte array) passed into it. examples note: see the guide visualizations with web audio api for more information on creating audio visualizations. basic usage 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 audioctx = new(window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); // ... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8...
...voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new(window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); // ... ...
...5 for relevant code). var audioctx = new(window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); // ... ...
...ow.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); // ... ...
ExtendableEvent - Web APIs
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 invalidstateerror; note also that multiple calls will stack up, and the resulting promises will be added to the list of extend lifetime promises. ...
... constructor extendableevent() creates a new extendableevent object. properties doesn't implement any specific properties, but inherits properties from its parent, event. methods inherits methods from its parent, event. extendableevent.waituntil() extends the lifetime of...
..."50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="191" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">extendableevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} note: this interface is only available when the global scope is a serviceworkerglobalscope. it is not available when it is a window, or the scope of another kind of worker. constructor extendableevent() creates a new extendableevent object. properties doesn't implement any specific properties, but inherits properties from its parent, event. methods inherits methods from its parent, event. extendableevent.waituntil() extends the lifetime of the event. it is intended to...
...rom its parent, event. extendableevent.waituntil() extends the lifetime of the event. it is intended to be called in the install eventhandler for the installing worker and on the activate eventhandler for the active worker. examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall, delaying treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully. the promise resolves when all resources have been fetched and cached, or else when any exception occurs. the code snippet also shows a best practice for versioning caches used by the service worker. though there's only one cache in this example, the same appro...
ServiceWorkerContainer.getRegistration() - Web APIs
this is usually a relative url. return value a promise that resolves to a serviceworkerregistration object or undefined. ...
...this is usually a relative url. return value a promise that resolves to a serviceworkerregistration object or undefined. ...
...this is usually a relative url. return value a promise that resolves to a serviceworkerregistration object or undefined. ...
...this is usually a relative url. return value a promise that resolves to a serviceworkerregistration object or undefined. ...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
, it's useful to think about the kinds of situation that call for the use of a camera. gaming-related situations are listed separately since they are often a special case specific to gaming, but any of these perspectives might apply to any 3d graphics scene. generalized cameras in general, virtual cameras may or may not be incorporated into physical objects within the scene. indeed, outside the scope of 3d gaming, the odds are far more likely that the camera will not correspond with an object that appears in the scene at all. some examples of ways 3d cameras are used: when rendering animation—whether for filmmaking or for use within the context of a presentation or game—the virtual camera is used just like a real-world film camera. as much as possible, standard cinematographic techniqu...
...lso includes games where the camera is placed just over the player's shoulder. some 3d games offer the ability to change your point of view, such as to look out the various windows of an aircraft in a flight simulator, or to see the views from all the security cameras within the game level (a common feature of spy and stealth-based games). this ability is also used by games offering weapons with scopes, where the view isn't quite based off the head's position in the same way anymore. 3d games might also provide the ability for non-players to observe the action, either by positioning an invisible avatar of sorts or by choosing a fixed virtual camera to watch from. in advanced 3d games, a camera or camera-like object could be used to determine what a non-player character can see, relying on th...
...createscalingmatrix(2.0)); panning (yawing left or right) panning or yaw is the rotation of the camera left to right or right to left, with its base otherwise fixed in place. the position of the camera in space does not change, only the direction in which it's looking. and that direction does not change other than horizontally. panning is great for establishing a setting or providing a sense of scope in a vast space or on a vast object. or just for looking left and right, like simulating the player turning their head in an immersive or vr scenario. to do this, then, we need to rotate around the y axis, to simulate the left and right rotation of the camera. using the glmatrix library we've used previously, this can be performed using the rotatey() method on the mat4 class, which represents ...
...to the right; a negative value for panangle will pan to the left. tilting (pitching up or down) when you tilt or pitch the camera, you keep it fixed in space at the same coordinates while changing the direction in which it's facing vertically without altering the horizontal portion of its facing at all. it simply adjusts the direction it's pointing up and down. tilting is good for capturing the scope of a tall object or scene, such as a forest or a mountain, but is also a popular way to introduce a character or locale of importance or which inspires awe. it's also of course useful for implementing support for a player looking up and down. thus, tilting the camera can be achieved by rotating the camera around the x axis, so that it pivots to look up and down. this can be done using the appr...
Web Workers API - Web APIs
the ui) thread to run without being blocked/slowed down. web workers concepts and usage 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. this context is represented by either a dedicatedworkerglobalscope object (in the case of dedicated workers - workers that are utilized by a single script), or a sharedworkerglobalscope (in the case of shared workers - workers that are shared between multiple scripts). you can run whatever code you like inside the worker thread, with some exceptions. for example, you can't directly manipulate the dom from inside a worker, or use some default methods and propert...
...ind 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 the worker. sharedworker represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers. ...
... 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 the worker. sharedworker represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers. ...
...r code. workerlocation defines the absolute location of the script executed by the worker. sharedworker represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers. workerglobalscope represents the generic scope of any worker (doing the same job as window does for normal web content). different types of worker have scope objects that inherit from this interface and add more specific features. dedicatedworkerglobalscope represents the scope of a dedicated worker, inheriting from workerglobalscope and adding some dedicated features. sharedworkerglobalscope represents the scope of a shared worker, inheriting from workerglobalscope and adding some dedicated features. workernavigator represents the identity and ...
itemid - HTML: Hypertext Markup Language
the exact meaning of an itemtype's global identifier is provided by the definition of that identifier within the specified vocabulary. ...
... the exact meaning of an itemtype's global identifier is provided by the definition of that identifier within the specified vocabulary. ...
...ulary defines whether several items with the same global identifier can coexist and, if so, how items with the same identifier are handled. note: the whatwg definition specifies that an itemid must be a url. however, the following example correctly illustrates that a urn may also be used. this inconsistency may reflect the incomplete nature of the microdata specification. ...
...incomplete nature of the microdata specification. example html <dl itemscope itemtype="http://vocab.example.net/book" itemid="urn:isbn:0-330-34032-8"> <dt>title <dd itemprop="title">the reality dysfunction <dt>author <dd itemprop="author">peter f. hamilton <dt>publication date <dd><time itemprop="pubdate" datetime="1996-01-26">26 january 1996</time> </dl> structured data itemscope itemtype: itemid http://vocab.example.net/book: urn:isbn:0-330-34032-8 itemprop title the reality dysfunction itemprop author peter f. hamilton itemprop pubdate 1996-01-26 result specifications specification status comment html living standardthe definition of 'itemid' in that specification...
Global attributes - HTML: Hypertext Markup Language
custom elements for more details). note: the item* attributes are part of the whatwg html microdata feature. itemid the unique, global identifier of an item. itemprop used to add properties to an item. every html element may have an itemprop attribute specified, where an itemprop consists of a name and value pair. itemref properties that are not descendants of an element with the itemscope attribute can be associated with the item using an itemref. it provides a list of element ids (not itemids) with additional properties elsewhere in the document. itemscope itemscope (usually) works along with itemtype to specify that the html contained in a block is about a particular item. itemscope creates the item and defines the scope of the itemtype associated with it. itemtype is a valid ...
... lang helps define the language of an element: the language that non-editable elements are in, or the language that editable elements should be written in by the user. ...
... lang helps define the language of an element: the language that non-editable elements are in, or the language that editable elements should be written in by the user. ...
... comment html living standardthe definition of 'global attributes' in that specification. living standard shadow parts working draft added the part and exportparts global attributes. html 5.2the definition of 'global attributes' in that specification. recommendation snapshot of html living standard. from html 5.1, itemid, itemprop, itemref, itemscope, and itemtype have been added. html 5.1the definition of 'global attributes' in that specification. recommendation snapshot of html living standard. from html5, contextmenu, draggable, dropzone, and spellcheck have been added. html5the definition of 'global attributes' in that specification. recommendation snapshot of html living standard. from html 4.01 specificatio...
Function - JavaScript
is can be seen with the code (function(){}).constructor === function, which returns true. constructor function() creates a new function object. calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval. however, unlike eval, the function constructor creates functions that execute in the global scope only. instance properties function.arguments an array corresponding to the arguments passed to a function. this is deprecated as a property of function. use the arguments object (available within the function) instead. function.caller specifies the function that invoked the currently executing function. this property is deprecated, and is only functional for some non-strict functions. ...
...ue. arguments can be passed as they are. function.prototype.tostring() returns a string representing the source code of the function. overrides the object.prototype.tostring method. examples difference between function constructor and function declaration functions created with the function constructor do not create closures to their creation contexts; they always are created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the function constructor was created. this is different from using eval with code for a function expression. var x = 10; function createfunction1() { var x = 20; return new function('return x;'); // this |x| refers global |x| } function createfunction2() ...
... specifications specification ecmascript (ecma-262)the definition of 'function' in that specification. ...
... specifications specification ecmascript (ecma-262)the definition of 'function' in that specification. ...
undefined - JavaScript
e no configurable no 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 undefined description undefined is a property of the global object. that is, it is a variable in global scope. the initial value of undefined is the primitive value undefined. in modern browsers (javascript 1.8.5 / firefox 4+), undefined is a non-configurable, non-writable property, per the ecmascript 5 specification. (even when this is not the case, avoid overriding it.) a variable that has not been assigned a value is of type undefined. a method or statement also returns undefined if the variable tha...
...specification. (even when this is not the case, avoid overriding it.) a variable that has not been assigned a value is of type undefined. a method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. a function returns undefined if a value was not returned. be careful. while it is possible to use it as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug. // don't do this // logs "foo string" (function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })(); // logs "foo string" (function(undefined) { console.log(undefined, typeof undefined); })('foo'); exampl...
...) { // 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 referenceerror } however, there is another alternative. ...
.... // x has not been declared before if (typeof x === 'undefined') { // evaluates to true without errors // these statements execute } if (x === undefined) { // throws a referenceerror } 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 in an enclosing context. the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object, using the in operator, for instance: if ('x' in window) { // these statements execute only if x is defined globally } void operator and undefined the void operator is a third alternative. var x; if (x === void 0) { // thes...
const - JavaScript
constants are block-scoped, much like variables defined using the let keyword. the value of a constant can't be changed through reassignment, and it can't be redeclared. 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 name1 = value1 [, name2 = value2 [, ... [, namen = valuen]]]; namen the constant's name, which can be any legal identifier. valuen the constant's value. this can be any legal expression, including a function expression. description this declaration creates a constant whose scope can be either global or local to the block in which it is declared. global constants do not become prop...
...e. it does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. for instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered. all the 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. // define my_fav as a constant and give it the value 7 const my_fav = 7; // this will throw an error - uncaught typeerror: assignment to constant variable. my_fav = 20; // my_fav is 7 console.log('my favorite number is: ' + my_fav); // trying to redecl...
...ing to redeclare a constant throws an error // uncaught syntaxerror: 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. ...
...ier '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. ...
with - JavaScript
use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues. see the "ambiguity contra" paragraph in the "description" section below for details. the with statement extends the scope chain for a statement. syntax with (expression) statement expression adds the given expression to the scope chain used when evaluating the statement. the parentheses around the expression are required. statement any statement. to execute multiple statements, use a block statement ({ ... }) to group those statements. description javascript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. the 'with' statement adds the given object to the...
...es around the expression are required. statement any statement. to execute multiple statements, use a block statement ({ ... }) to group those statements. description javascript looks up an unqualified name by searching a scope chain 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 referenceerror 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 w...
...y. otherwise a referenceerror 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 by 'with' is not computationally expensive. use of 'with' will relieve the interpreter of parsing repeated object references. note, however, that in many cases this benefit can be achieved by using a temporary variable to store a reference to the desired object. contra: the with statement forces the specified object to be searched first for all name lookups. therefore all i...
...e all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object. ambiguity contra contra: the with statement makes it hard for a human reader or javascript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which 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 c...
/loader - Archive of obsolete content
le`. 'toolkit/loader': loadermodule } }); use this feature with a great care though. while reuse may sound like a compelling idea it comes with the side effect of shared state, which can cause problems. for example, unload of a loader won't trigger unload hooks on pseudo-modules. globals each module loaded via the loader instance is secured in own js sandbox. these modules don't share scope and get their own set of built-ins (object, array, string ...). but sometimes it's convenient to define a set 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: d...
...ribed above. other utilities the loader module exposes several other utility functions that are used internally and can also be handy while bootstrapping the loader itself. they are low level helpers and should be used only during loader bootstrap. module() the module() function takes a module id and uri and creates a module instance object that is exposed as the module variable in the module scope. let module = module('foo/bar', 'resource:///modules/foo/bar.js'); note that this won't actually load any module code, it just creates a placeholder for it. the section below describes how to load the module. load() the load() function takes loader and loads the given module into it: let loader = loader(options); let module = module('foo/bar', 'resource:///modules/foo/bar.js'); load(loader...
... creates a placeholder for it. the section below describes how to load the module. load() the load() function takes loader and loads the given module into it: let loader = loader(options); let module = module('foo/bar', 'resource:///modules/foo/bar.js'); load(loader, module); sandbox() the sandbox() function is a utility function for creating js sandboxes. it is used by the loader to create scopes into which modules are loaded. it takes the following set of configuration options: name: a string value which identifies the sandbox in about:memory. will throw exception if omitted. principal: string uri or nsiprincipal for the sandbox. if omitted defaults to system principal. prototype: object that the returned sandbox will inherit from. defaults to {}. wantxrays: a boolean value indica...
Venkman Introduction - Archive of obsolete content
n lines. both the line and length column are blank for file names. if a function has a breakpoint in it, a small red dot will show up in the function icon, as well as the parent's file icon. the local variables view the local variables view is on the left portion of the window, at the bottom. when the debugger is stopped, the local variables view displays values for the current function. ...
...figure 9 shows which icons represent which data types. properties which are of the type object are displayed with the name of their constructor function in curly braces as their value. you can locate the source code of the constructor by selecting "find constructor" from the property's context menu. ...
...either case, a red breakpoint icon appears in the source code view. type /break in the debugger. if you don't provide arguments to the /break command, all breakpoints are listed in the interactive session view. on the fishcam page, press the "pause" link. you should hit the breakpoint you just set in step 3. in the interactive session, context becomes animator-0.03.js and the scope is the pause function. there will also be "stopped for breakpoint" in red in the interactive session, along with the file name, line number, and snippet source code from where it stopped. figure 13. (from step 5) stopped at a breakpoint. in the interactive session's input field, enter this.fpaused venkman evaluates the expression, giving you [boolean] false back. press step ...
Introduction to XUL - Archive of obsolete content
s of at least some xul documents. "xptoolkit" is rather synonymous with xpfe. though the former term seems more concrete than the other, and therefore is not an exact replacement, no one is completely certain why we have both. "xul" already introduced, is an application of xml used to describe the layout of most windows in the mozilla browser, including and especially the main, browser window. scope this paper makes no attempt to explain requirements. we don't have a current "requirements" document. xptoolkit architecture is a better place to gain an understanding of such things. this paper contains a short introduction to mozilla front-end architecture, concentrating on the task of building uis. it is, as always, incomplete. mozilla applications will be built of "small" components like di...
...ation. scripting a xul interface is only a collection of disconnected widgets until it has been programmed. "programming" can be as simple as some javascript to tie the widgets together and perhaps to give them extra functionality, or as complex as application (c++) code which is free to do ... anything. this paper will concentrate on javascript, deeming application programming to be beyond its scope. javascript xul can contain html content, including javascript. javascript functions may be added in a fashion similar to html. there is no <head> section of a xul file, so script is just mixed in with the other content, delimited by a script element in the html namespace. <html:script type="application/javascript"> // dialog initialization code function initwindow() { var checkbox = d...
..., where localization can be performed by altering only a subset of the ui description devoted expressly to localization issues. that is, a separate file of localized strings. internationalization is discussed more completely in the xul coding style guidelines document. in brief, mozilla has settled on xml entities as the mechanism. entities are a feature of the language and therefore outside the scope of this paper. a xul file can be made localizeable very easily by substituting entities for any content which may change as the locale changes. the localized text must be defined in a separate dtd or dtd fragment. the whole system is then configured with different locale-specific dtds, and the correct dtd will be chosen for a given xml file at runtime, depending on the current locale settings. mo...
Debug.setNonUserCodeExceptions - Archive of obsolete content
setting this property to false is the same as never having set the property. for more information on debugging, see the active script debugging overview. ...
...setting this property to false is the same as never having set the property. for more information on debugging, see the active script debugging overview. ...
...setting this property to false is the same as never having set the property. for more information on debugging, see the active script debugging overview. example the following code shows how to set this property. ...
Using the DOM File API in chrome code - Extensions
can create file objects specifying the path of the file on the user's computer. this only works from privileged code, so web content can't do it. this protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. if you pass a path to the file constructor from unprivileged code (such as web content), an exception will be thrown. ...
...ying the path of the file on the user's computer. this only works from privileged code, so web content can't do it. this protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. if you pass a path to the file constructor from unprivileged code (such as web content), an exception will be thrown. ...
...ged code, so web content can't do it. this protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. if you pass a path to the file constructor from unprivileged code (such as web content), an exception will be thrown. scope availability in the jsm scope file is available without needing to do anything special. in bootstrap scope, this must be imported in like so: cu.importglobalproperties( [ "file" ] ) accessing a file by hard-coded pathname to reference a file by its path, you can simply use a string literal: var file = file.createfromfilename("path/to/some/file"); cross platform note: however using hard-coded paths raises cross platform issues since it uses a platform-dependent path separator (here "/"). in the x...
MDN Web Docs Glossary: Definitions of Web-related terms
item flexbox forbidden header name forbidden response header name fork fragmentainer frame rate (fps) ftp ftu function fuzz testing g gaia garbage collection gecko general header gif gij git global object global scope global variable glyph gonk google chrome gpl gpu graceful degradation grid grid areas grid axis grid cell grid column grid container grid lines grid row grid tracks guard gutters gzip compression h hash ...
... intrinsic size ip address ipv4 ipv6 irc iso isp itu j jank java javascript jpeg jquery json k key keyword l latency layout viewport lazy load lgpl ligature local scope local variable locale localization long task loop lossless compression lossy compression ltr (left to right) m main axis main thread markup mathml media media (audio-visual presentation) media (css) metadata method micros...
... rest rgb ril robots.txt round trip time (rtt) routers rss rtcp (rtp control protocol) rtf rtl (right to left) rtp (real-time transport protocol) and srtp (secure rtp) rtsp: real-time streaming protocol ruby s safe same-origin policy scm scope screen reader script-supporting element scroll container scrollport sctp sdp search engine second-level domain secure sockets layer (ssl) selector (css) self-executing anonymous function semantics seo serialization server server timing session hi...
Your first form - Learn web development
you to define the right set of data you want to ask your user to enter. from a user experience (ux) point of view, it's important to remember that the bigger your form, the more you risk frustrating people and losing users. keep it simple and stay focused: ask only for the data you absolutely need. designing forms is an important step when you are building a site or application. it's beyond the scope of this article to cover the user experience of forms, but if you want to dig into that topic you should read the following articles: smashing magazine has some good articles about forms ux, including an older but still relevant extensive guide to web form usability article. uxmatters is also a very thoughtful resource with good advice from basic best practices to complex concerns such as mul...
... content. basic form styling now that you have finished writing your form's html code, try saving it and looking at it in a browser. at the moment, you'll see that it looks rather ugly. note: if you don't think you've got the html code right, try comparing it with our finished example — see first-form.html (also see it live). forms are notoriously tricky to style nicely. it is beyond the scope of this article to teach you form styling in detail, so for the moment we will just get you to add some css to make it look ok. first of all, add a <style> element to your page, inside your html head. it should look like so: <style> </style> inside the style tags, add the following css: form { /* center the form on the page */ margin: 0 auto; width: 400px; /* form outline */ paddin...
...sent to the url "/my-handling-form-page" using the http post method. on the server side, the script at the url "/my-handling-form-page" will receive the data as a list of 3 key/value items contained in the http request. the way this script will handle that data is up to you. each server-side language (php, python, ruby, java, c#, etc.) has its own mechanism of handling form data. it's beyond the scope of this guide to go deeply into that subject, but if you want to know more, we have provided some examples in our sending form data article later on. summary congratulations, you've built your first web form. it looks like this live: that's only the beginning, however — now it's time to take a deeper look. forms have way more power than what we saw here and the other articles in this modul...
Client-side storage - Learn web development
we then use the body.blob() method to extract each response's body as a blob, giving us an object representation of the videos that can be stored and displayed later on. we have a problem here though — these two requests are both asynchronous, but we only want to try to display or store the video when both promises have fulfilled. fortunately there is a built-in method that...
... that page, meaning that it will start controlling it. when this occurs, an install event is fired against the service worker; you can write code inside the service worker itself that will respond to the installation. let's look at an example, in the sw.js file (the service worker). you'll see that the install listener is registered against self. this self keyword is a way to refer to the global scope of the service worker from inside the service worker file. inside the install handler we use the extendableevent.waituntil() method, available on the event object, to signal that the browser shouldn't complete installation of the service worker until after the promise inside it has fulfilled successfully. here is where we see the cache api in action. we use the cachestorage.open() method to ope...
...ow, installation done. responding to further requests with the service worker registered and installed against our html page, and the relevant assets all added to our cache, we are nearly ready to go. there is only one more thing to do, write some code to respond to further network requests. this is what the second bit of code in sw.js does. we add another listener to the service worker global scope, which runs the handler function when the fetch event is raised. this happens whenever the browser makes a request for an asset in the directory the service worker is registered against. inside the handler we first log the url of the requested asset. we then provide a custom response to the request, using the fetchevent.respondwith() method. inside this block we use cachestorage.match() to chec...
Getting started with Svelte - Learn web development
nds it to the body of our html page. public: this directory contains all the files that will be published in production. favicon.png: this is the favicon for your app. currently, it's the svelte logo. index.html: this is the main page of your app. initially it's just an empty html5 page that loads the css files and js bundles generated by svelte. global.css: this file contains unscoped styles. it's a regular css file that will be applied to the whole application. build: this folder contains the generated css and javascript source code. bundle.css: the css file that svelte generated from the styles defined for each component. bundle.js: the javascript file compiled from all your javascript source code. having a look at our first svelte componen...
... max-width: 240px; margin: 0 auto; } h1 { color: #ff3e00; text-transform: uppercase; font-size: 4em; font-weight: 100; } @media (min-width: 640px) { main { max-width: none; } } </style> we are applying a style to our <h1> element. what will happen other components with <h1> elements in them? in svelte, css inside a component's <style> block will be scoped only to that component. this works by adding a class to selected elements, which is based on a hash of the component styles. you can see this in action by opening localhost:5000 in a new browser tab, right/ctrl-clicking on the hello world! label, and choosing inspect: when compiling the app, svelte changes our h1 styles definition to h1.svelte-1tky8bj, and then modifies every <h1> element in...
...we'll start building our first proper application — a todo list. before we do that, however, let's recap some of the things we’ve learned. in svelte: we define the script, style and markup of each component in a single .svelte file. component props are declared with the export keyword. svelte components can be used just by importing the corresponding .svelte file. components styles are scoped, keeping them from clashing with each other. in the markup section you can include any javascript expression by putting it between curly braces. the top-level variables of a component constitute its state. reactivity is fired just by assigning a new value to a top level variable. previous overview: client-side javascript frameworks next in this module introduction to client-side...
HTML parser threading
esents a small operation, such as element creation or appending a node into another, that can later be performed on the main thread. note that mtokenizermutex is being held by the parser thread for the entire time that the tokenizer runs. parseavailabledata() checks for parser termination or interruption from time to time. the termination and interruption indicators are guarded by a more narrowly scoped mterminatedmutex, so parseavailabledata() has the opportunity to receive an order to terminate or interrupt even while the parser thread is holding mterminatedmutex. the tree op queue is flushed to the main thread from time to time. there's a timer that calls timerflush() (which takes mtokenizermutex). tree ops from the queue in the tree builder are moved to a tree op stage (nshtml5treeopstage).
...hout having heap-allocated nsstrings involved.) element names, attribute names and the doctype name are represented as nsiatoms. pre-interned attribute and element names hold atoms that are actually app-wide nsstaticatoms. since nsstaticatoms are valid app-wide, these atoms work right app-wide on the main thread. for other atoms, the parser uses nshtml5atom objects that are atomic only within the scope of an nshtml5atomtable. there is one nshtml5atomtable per each nshtml5parser and one per each nshtml5streamparser. thus, each tokenizer/tree builder pair sees atoms that are atomic (pointer-comparable) within the tokenizer/tree builder pair. however, when tree ops are executed, every atom has to be tested for being a static atom (using isstaticatom()). if the atom isn't static, a corresponding no...
... if there is data in document.write() input after a an external script (or any data at all if a previous document.write() call has contained an external script and blocked the parser), the data is left in a linked list of nshtml5owningutf16buffer objects. (how exactly data is inserted into the buffer list depends on parser keys when document.write() is invoked re-entrantly, but that's outside the scope of this document, since this document is about parser threading.) whenever the argument of document.write() isn't tokenized to completion synchronously, the part left unprocessed by the main document.write() tokenizer/tree builder is processed by the third tokenizer/tree builder pair. the tree ops from that processing are ignored and only speculative loads are used. (speculative loads are discuss...
PromiseWorker.jsm
like chromeworker objects, promiseworker is mostly used for js-ctypes but it is not limited to that. there is no xpcom access, similar to chromeworker. this answers the question "when should i use a promiseworker?", and the answer is, whenever you would normally use a chromeworker, but want postmessage to return promises. ...
...ll known with workers, there is a minimum of two files required. the worker file, and the main thread file. the following sections tell you which content to use in your worker and main thread files, in order to use promiseworker objects. worker file there is some standard templating that must be dropped into the worker file by the developer. the require.js file must be imported with workerglobalscope/importscripts(). next, the promiseworker.js file should be brought in with the require() method. finally, the template code should be added in. the code below is what should be copied and pasted: importscripts('resource://gre/modules/workers/require.js'); let promiseworker = require('resource://gre/modules/workers/promiseworker.js'); // instantiate abstractworker (see below). let worker = new p...
...or reject the promise. in summary, from a worker file, data can only be sent back as a response to a request from the main thread, it is not possible for a worker to send data to the main thread otherwise, this is a key difference between promiseworker worker file and all other types of workers. resolving the promise to resolve the promise from the worker, simply return anything from the worker scope, and the main thread promise will be resolved with the returned value. function func(buffer) { // do something with buffer... return 1; // 1 is sent back to main thread, as a resolved promise. } transferring special data from worker to main thread just as it was possible to transfer special data from main thread to worker, it is possible to transfer data from the worker to the main threa...
XPCOMUtils.jsm
declare the class (or multiple classes) implementing the component(s). create an array of component constructors. ...
... methods definelazygetter() getter functions in javascript give you a way to define a property of an object, but not c...
...sistreamlistener, components.interfaces.nsistreamconverter, ]), // ...methods... } importrelative() imports a javascript code module given the calling javascript code module's global object (you should specify this) and a path relative to that module. this lets modules bundled in a package load one another without having to hard-code full paths. void importrelative( that, path, scope ); parameters that the javascript object of the calling javascript code module's global scope. you should simply pass this. path the relative path of the javascript code module to import. scope an optional object to import into; if omitted, the object passed in for the that parameter is used. remarks this lets an extension bundle its own javascript code modules within itself and have...
Rhino Debugger
elf a java program which you may run as java org.mozilla.javascript.tools.debugger.main [options] [filename.js] [script-arguments] where the options are the same as the shell. the rhino javascript debugger can debug scripts running in multiple threads and provides facilities to set and clear breakpoints, control execution, view variables, and evaluate arbitrary javascript code in the current scope of an executing script. console window the debugger redirects the system.out, system.in, and system.err streams to an internal javascript console window which provides an editable command line for you to enter javascript code and view system output. the console window maintains a history of the commands you have entered. you may move backward and forward through the history list by pressing t...
...oving up and down the stack the lower-left (dockable) pane in the debugger main window contains a combo-box labeled "context:" which displays the current stack of the executing script. you may move up and down the stack by selecting an entry in the combo-box. when you select a stack frame the variables and watch windows are updated to reflect the names and values of the variables visible at that scope. setting and clearing breakpoints the main desktop of the debugger contains file windows which display the contents of each script you are debugging. you may set a breakpoint in a script by doing one of the following: place the cursor on the line at which you want to set a breakpoint and right-click with the mouse. this action will display a pop-up menu. select the set breakpoint menu item...
... variable may be expanded to show its sub-properties. the locals table is updated each time control returns to the debugger or when you change the stack location in the context: window watch window you may enter arbitrary javascript expressions in the watch: table located in the lower-right (dockable) pane in the debugger main window. the expressions you enter are re-evaluated in the current scope and their current values displayed each time control returns to the debugger or when you change the stack location in the context: window. evaluation window the evaluate pane located in the lower-right (dockable) pane in the debugger main window contains an editable command line where you may enter arbitrary javascript code. the code is evaluated in the context of the current stack frame. the...
JS::Evaluate
blehandlevalue rval); bool js::evaluate(jscontext *cx, const js::readonlycompileoptions &options, const char *bytes, size_t length, js::mutablehandlevalue rval); bool js::evaluate(jscontext *cx, const js::readonlycompileoptions &options, const char *filename, js::mutablehandlevalue rval); bool js::evaluate(jscontext *cx, js::autoobjectvector &scopechain, const readonlycompileoptions &options, const char16_t *chars, size_t length, js::mutablehandlevalue rval); // added in spidermonkey 17 bool js::evaluate(jscontext *cx, js::autoobjectvector &scopechain, const js::readonlycompileoptions &options, js::sourcebufferholder &srcbuf, js::mutablehandlevalue rval); // obsolete since jsapi 39 boo...
...context *cx, js::handleobject obj, const js::readonlycompileoptions &options, const char *filename, js::mutablehandlevalue rval); name type description cx jscontext * the context in which to run the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the scope in which to execute the script. this parameter is documented in detail at js_executescript. obsolete since jsapi 39 scopechain js::autoobjectvector &amp; the scope in which to execute the script. this parameter is documented in detail at js_executescript. options js::readonlycompileoptions &amp; compile options. srcbuf js::sourcebufferholder &amp; sour...
...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. 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 valu...
JS_ExecuteScriptVersion
with specified version. syntax jsbool js_executescriptversion(jscontext *cx, jsobject *obj, jsobject *scriptobj, jsval *rval, jsversion version); name type description cx jscontext * the context in which to execute the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...otherwise obj is used. the this value is obj. ...
...otherwise obj is used. the this value is obj. script jsobject * the compiled script to execute. rval jsval * out parameter. ...
JS_GetGlobalObject
d using it. retrieves a context's global object. (in javascript, global variables are stored as properties of the global object.) syntax jsobject * js_getglobalobject(jscontext *cx); name type description cx jscontext * the context from which to retrieve the global object. description this function is obsolete: use js_getglobalforobject or js_getglobalforscopechain instead. the concept of a global object belonging to a context will likely be phased out in future versions of spidermonkey. js_getglobalobject retrieves the global object for a specified jscontext *, cx. this returns null if cx has no global object. spidermonkey supports applications that have multiple global objects, such as the various window objects in a web browser. the object returned ...
...ntext's global object field serves two purposes. first, it is a convenient place for the application to stash the global object, where it is automatically protected from garbage collection and the application can easily access it. ...
...value of last resort by functions that need a default parent object (see js_setparent for details) and by js_getscopechain. use js_setglobalobject to replace the global object. ...
Parser API
tatement"; object: expression; body: statement; } a with statement. interface switchstatement <: statement { type: "switchstatement"; discriminant: expression; cases: [ switchcase ]; lexical: boolean; } a switch statement. the lexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope). interface returnstatement <: statement { type: "returnstatement"; argument: expression | null; } a return statement. interface throwstatement <: statement { type: "throwstatement"; argument: expression; } a throw statement. interface trystatement <: statement { type: "trystatement"; block: blockstatement; handler: catchclause | null; guardedhandlers: [ cat...
...ote: the debugger statement is new in ecmascript 5th edition, although spidermonkey has supported it for years. declarations interface declaration <: statement { } any declaration node. note that declarations are considered statements; this is because declarations can appear in any statement context in the language recognized by the spidermonkey parser. note: declarations in arbitrary nested scopes are spidermonkey-specific. interface functiondeclaration <: function, declaration { type: "functiondeclaration"; id: identifier; params: [ pattern ]; defaults: [ expression ]; rest: identifier | null; body: blockstatement | expression; generator: boolean; expression: boolean; } a function declaration. note: the id field cannot be null. interface variabledecla...
...ce a custom if statement node. switchstatement(disc, cases, islexical[, loc]) disc: customexpression cases: [ customswitchcase ] islexical: boolean loc: sourcelocation returns: customstatement callback to produce a custom switch statement node. the islexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope). whilestatement(test, body[, loc]) test: customexpression body: customstatement loc: sourcelocation returns: customstatement callback to produce a custom while statement node. dowhilestatement(body, test[, loc]) body: customstatement test: customexpression loc: sourcelocation returns: customstatement callback to produce a custom do-while statement node. forstatement(init, test, update...
Using XPCOM Utilities to Make Things Easier
es]: nsastring and nsacstring. the former handles double byte characters, and the latter tends to be used in more general circumstances, but both of these classes define the functionality of a string. you can see these classes being passed as arguments in many of the xpcom interfaces we'll look at in the following chapters. using strings explaining how all the string classes work is outside the scope of this book, but we can show you how to use strings in the weblock component. the first thing to note is that the string classes themselves are not frozen, which means that you should not link against them when you can avoid it. linking the full string library (.lib or .a) into a component may raise its footprint by more than 100k (on windows), which in many cases is an unacceptable gain (see t...
...efore 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, but in real code, this can easily happen in goto constructs, or in deep nesting with early returns. having more than one interface pointer that needs to be released when a block goes out 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)) ...
...e: nsisupports-warning note that ns_decl_isupports doesn't obey the general rule in which every interface has a declaration macro of the form ns_decl_interfacename, where interfacename is the name of the interface being compiled. note: nulls-in-strings the string classes may also support embedded nulls. note: other-string-classes there are other abstract string classes, but they are outside the scope of this book. « previousnext » copyright (c) 2003 by doug turner and ian oeschger. this material may be distributed only subject to the terms and conditions set forth in the open publication license, v1.02 or later. distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. distribution of the work or derivat...
Components.utils.cloneInto
this function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope. it returns a reference to the clone: var clonedobject = cloneinto(myobject, targetwindow); you can then assign the clone to an object in the target scope as an expando property, and scripts running in that scope can access it: targetwindow.foo = clonedobject; in this way privileged code, such as an add-on, can share an object with less-privileged code like a normal web page script. syntax components.utils.cloneinto(obj, targetscope[, options]); parameters obj : object the object to clone. targetscope : object the object to attach the object to. options : object this optional parameter is an object with the following op...
...suppose the page script defines a function like this: // page script function foo(greeting) { console.log("they said: " + greeting.message); } the add-on script can define an object, clone it, and pass it into this function: // add-on script var...
... ...
jsdIStackFrame
private data for this object is an nsisupports object. attempting to alter this bit will result in an ns_error_illegal_value. opt_* values above, or'd together. ...
...lue. 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. unique tag among all valid jsdicontext objects, useful as a hash key. 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 ha...
...dcontext jsdcontext internal use only. read only. native code only! jsdstackframeinfo jsdstackframeinfo internal use only. read only. native code only! jsdthreadstate jsdthreadstate internal use only. read only. native code only! line unsigned long current line number (using the script's pc to line map.) read only. pc unsigned long current program counter in this stack frame. read only. scope jsdivalue top object in the scope chain. read only. script jsdiscript script running in this stack frame, null for native 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 ); param...
mozIJSSubScriptLoader
context, "utf-8" /* the script's encoding */); parameters url the url pointing to the script to load. it must be a local chrome:, resource: or file: url (see bug 307686 and bug 418356). note: in versions of gecko prior to gecko 1.9, you could use data: urls as well, but this introduced security concerns, and is no longer permitted. targetobj the object to use as the scope object for the script being executed. this is where var declarations in the script will be placed. it defaults to the global object of the caller. note that let and const declarations in the script will be placed on a syntactic scope that is not an object at all, and will not be available to the caller of loadsubscript. note: undeclared variables in the loaded script will be created as global ...
... charset an optional string to specify the character encoding of the file. if absent, the file is interpreted as ascii. loadsubscriptwithoptions() same as loadsubscript(), except that parameters after url are expressed as an object, and a new ignorecache option is available. ...
...method must only be called from javascript! jsval loadsubscriptwithoptions( in string url, in object options ); parameters url the url pointing to the script to load. it must be a local chrome:, resource: or file: url. options an object that may include any of these parameters: property type description target object the object to use as the scope object for the script being executed. it defaults to the global object of the caller. note: undeclared variables in the loaded script will be created as global variables in the caller (ie.: in the caller's global object). this object will be searched for variables that cannot be resolved in the subscript scope. charset string an optional string to specify the character encodin...
nsIFrameScriptLoader
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisupports this interface is used to load frame scripts. methods void loadframescript(in astring aurl, in boolean aallowdelayedload, [optional] in boolean aruninglobalscope) void removedelayedframescript(in astring aurl); jsval getdelayedframescripts(); loadframescript() load a script in the remote frame. frame scripts are loaded as soon as loadframescript() is called. if this function is called on a chromemessagebroadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame...
... aurl string url for the script to load. aurl must be the absolute url. data: urls are also supported. for example data:,dump("foo\n"); aallowdelayedload boolean if true, this flag means that the frame script will be loaded into any new frames opened after the loadframescript() call, until removedelayedframescript() is called for that script. aruninglobalscope boolean optional, defaults to false. by default, frame scripts each have their own scope, so they can declare global variables without causing conflicts with any other frame scripts. if present and set to true, this flag switches off that behavior, meaning that the script's scope is shared with any other frame scripts in the same frame that have also set the flag. remov...
...ad, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled). parameters name type description aurl string url for the script to remove. getdelayedframescripts() returns all delayed scripts that will be loaded once a (remote) frame becomes available. the return value is a list of pairs [<url>, <wasloadedinglobalscope>]. returns list of the delayed scripts. each script is returned as a pair: [<url>, <wasloadedinglobalscope>]. ...
XPCOM Interface Reference
converternsimimeheadersnsimodulensimsgaccountnsimsgaccountmanagerextensionnsimsgcompfieldsnsimsgcustomcolumnhandlernsimsgdbhdrnsimsgdbviewnsimsgdbviewcommandupdaternsimsgdatabasensimsgfilternsimsgfiltercustomactionnsimsgfilterlistnsimsgfoldernsimsgheaderparsernsimsgidentitynsimsgincomingservernsimsgmessageservicensimsgprotocolinfonsimsgruleactionnsimsgsearchcustomtermnsimsgsearchnotifynsimsgsearchscopetermnsimsgsearchsessionnsimsgsearchtermnsimsgsearchvaluensimsgsendlaternsimsgthreadnsimsgwindownsimsgwindowcommandsnsimutablearraynsinavbookmarkobservernsinavbookmarksservicensinavhistorybatchcallbacknsinavhistorycontainerresultnodensinavhistoryfullvisitresultnodensinavhistoryobservernsinavhistoryquerynsinavhistoryqueryoptionsnsinavhistoryqueryresultnodensinavhistoryresultnsinavhistoryresultnodens...
...erregistrarnsiwebnavigationnsiwebnavigationinfonsiwebpagedescriptornsiwebprogressnsiwebprogresslistenernsiwebprogresslistener2nsiwebsocketchannelnsiwebsocketlistenernsiwebappssupportnsiwifiaccesspointnsiwifilistenernsiwifimonitornsiwinaccessnodensiwinapphelpernsiwintaskbarnsiwindowcreatornsiwindowmediatornsiwindowwatchernsiwindowsregkeynsiwindowsshellservicensiworkernsiworkerfactorynsiworkerglobalscopensiworkermessageeventnsiworkermessageportnsiworkerscopensiwritablepropertybagnsiwritablepropertybag2nsixformsmodelelementnsixformsnsinstanceelementnsixformsnsmodelelementnsixmlhttprequestnsixmlhttprequesteventtargetnsixmlhttprequestuploadnsixpcexceptionnsixpcscriptablensixpconnectnsixsltexceptionnsixsltprocessornsixsltprocessorobsoletensixulappinfonsixulbrowserwindownsixulbuilderlistenernsixulrunt...
...appinfonsixulbrowserwindownsixulbuilderlistenernsixulruntimensixulsortservicensixultemplatebuildernsixultemplatequeryprocessornsixultemplateresultnsixulwindownsixmlrpcclientnsixmlrpcfaultnsizipentrynsizipreadernsizipreadercachensizipwriternsmsgfilterfileattribvaluensmsgfolderflagtypensmsgjunkstatusnsmsgkeynsmsglabelvaluensmsgpriorityvaluensmsgruleactiontypensmsgsearchattribnsmsgsearchopnsmsgsearchscopensmsgsearchtermnsmsgsearchtypevaluensmsgsearchvaluensmsgsearchwidgetvaluenspipromptservice see also interfaces grouped by function ...
Storage
t a statement. be aware that you should always reset even if an exception is thrown, so your code should look something like this: var statement = dbconn.createstatement("select * from table_name"); try { while (statement.step()) { // use the results... ...
...o your code should look something like this: var statement = dbconn.createstatement("select * from table_name"); try { while (statement.step()) { // use the results... } } finally { statement.reset(); } in c++, storage provides a helper object in storage/public/mozstoragehelper.h, mozstoragestatementscoper, which ensures that the statement object is reset when the object falls out of scope. of course, if your statement is local only to the function, you do not have to worry about calling reset since the object will be destroyed. nsresult myclass::myfunction() { // mspecialstatement is a member variable of the class that contains a statement. mozstoragestatementscoper scoper(mspecialstatement); // you can use mspecialstatement without concern now. nscomptr<mozistoragestate...
...ce you start a transaction, you can either commit the changes by calling mozistorageconnection.committransaction(), or rollback the changes by calling mozistorageconnection.rollbacktransaction(). in c++ code, there is a helper class defined in storage/public/mozstoragehelper.h, mozstoragetransaction, that will attempt to get a transaction for you, and handle it appropriately 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...
Frequently Asked Questions
n "you can't dereference a null nscomptr with operator*()" other issues printf("%x\n", mynscomptr); can cause the program to crash on sigill (illegal instruction), and not on the line with the printf, which can make it tricky to figure out. for debugging purposes you can write printf("%x\n", mynscomptr.get()); how do i... initialize an nscomptr? release an nscomptr before it goes out of scope? assign 0 into it. whenever an nscomptr takes on a new value, it always releases its old value, if any. assigning in the value 0 is just like assigning in a raw pointer that happens to be null. the old referent will be released. [see initialization and assignment for more details] you should note, though, that there is a small performance penalty for this. the nscomptr will still exercize logic...
...ould note, though, that there is a small performance penalty for this. the nscomptr will still exercize logic in its destructor to attempt to release the value it has at that time. the optimal solution is to arrange the lifetime of your nscomptr to correspond to exactly how long you want to hold the reference. e.g., using blocks as in this sample // the most efficient scheme is to scope your |nscomptr| to live exactly as long // as you need to hold the reference nsresult somelongfunction( nsibar* abar ) { nsresult rv; // ... { // i only need the |nsifoo| interface for a short time // so i control its lifetime by declaring it inside // a block statement. nscomptr<nsifoo> foo( do_queryinterface(abar, &rv) ); if ( foo ) foo-...
... you need to hold the reference nsresult somelongfunction( nsibar* abar ) { nsresult rv; // ... { // i only need the |nsifoo| interface for a short time // so i control its lifetime by declaring it inside // a block statement. nscomptr<nsifoo> foo( do_queryinterface(abar, &rv) ); if ( foo ) foo->dosomefoothing(); // |foo| goes out of scope, and so |release|s its referent, here } // ...tons of stuff here, during which i don't need an |nsifoo| return rv; } editors note: move this discussion to the efficiency section, and link to it from here. make an nscomptr leak (for a debug test)? call a getter that uses a raw xpcom interface pointer as an `in/out' parameter? call a getter that fills in an nsifoo*& p...
Getting Started Guide
good starting point, but by no means complete. you use an owning reference when you created the object; you got the object from a function that might have created it, e.g., any `getter' function, such as queryinterface, or createinstance. ...
...thus providing you with an owning reference; you will hold onto the reference longer than the scope of the function in which you acquired it, e.g., you got it as a parameter, but you're hanging onto it in a member variable (see, for example, comparison 1, below). you don't need an owning reference when the object is passed in as a parameter, and you don't need to keep it any longer than the scope of this function; the object's lifetime is known to contain yours in some well defined way, e.g., in the nodes of a tree, parent nodes keep owning references to their children, children need not keep owning references to their parents. it turns out that reference counting by hand is hard for programmers to get right. it may sound simple, but in practice it's very easy to forget to release at t...
...ing in the new value. by declaring the parameter as an nscomptr&, the relationship is explicit. summary an nscomptr is an owning reference. whatever it points to has been addrefed, counting the nscomptr as one of its `owners'. an nscomptr always calls release before letting go, whether the nscomptr is letting go so that it can point to a different object, or because the nscomptr is going out of scope. any time a new value is assigned into an nscomptr, the nscomptr automatically always releases its old referent, if any, and (unless you tell it you already have) addrefs the new. you use an nscomptr exactly as you would a raw xpcom interface pointer in almost all cases. you won't have to explictly call addref or release through it, nor will the compiler allow it. the only place you can't use an...
Content Index API - Web APIs
sers to discover and view what is available, whilst giving developers the ability to add and manage this content. examples could be a news website prefetching the latest articles in the background, or a content streaming app registering downloaded content. the content index api is an extension to service workers, which allows developers to add urls and metadata of already cached pages, under the scope of the current service worker. the browser can then use these entries to display offline reading to a user. as a developer you can also display these entries within your application. indexed entries do not automatically expire. it's good practice to present an interface for clearing out entries, or periodically remove older entries. the api supports indexing urls corresponding to html docume...
...t index api defines the object used to represent the contentdelete event. service worker additions the following additions to the serviceworker have been specified in the content index api spec to provide an entry point for using content indexing. serviceworkerregistration.index read only returns a reference to the contentindex interface for indexing cached pages. serviceworkerglobalscope.oncontentdelete an event handler fired whenever a contentdelete event occurs. this happens when content is removed by the user agent. examples all the following examples assume a service worker has been registered. for more information see the service worker api. feature detection and interface access here we get a reference to the serviceworkerregistration, then check for the index proper...
...us function, that removes an item from the content index. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker. they are accessible from the workerglobalscope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); contentdelete event when an item is removed from the user agent interface, a contentdelete event is received by the service worker. self.addevent...
Microdata DOM API - Web APIs
s can use it to expose information to the user, for example offering it in a form that can be used by other applications. the document.getitems(typenames) method provides access to the top-level microdata items. it returns a nodelist containing the items with the specified types, or all types if no argument is specified. each item is represented in the dom by the element on which the relevant itemscope attribute is found. these elements have their element.itemscope idl attribute set to true. the type(s) of items can be obtained using the element.itemtype idl attribute on the element with the itemscope attribute. methods document . getitems( [ types ] ) returns a nodelist of the elements in the document that create items, that are not part of other items, and that are of the types given in th...
...bject returned by the earlier call. in other cases, a new nodelist object must be returned. properties element . itemvalue [ = value ] returns the element's value. can be set, to change the element's value. setting the value when the element has no itemprop attribute or when the element's value is an item throws an invalidaccesserror exception. element . properties if the element has an itemscope attribute, returns an htmlpropertiescollection object with all the element's properties. otherwise, an empty htmlpropertiescollection object. code example this sample shows how the getitems() method can be used to obtain a list of all the top-level microdata items of a particular type given in the document: var cats = document.getitems("http://example.com/feline"); once an element representin...
...var name = 0; name < items[item].properties.names.length; name += 1) { var propli = document.createelement('li'); propli.appendchild(document.createtextnode(items[item].properties.names[name])); inner.appendchild(propli); } itemli.appendchild(inner); outer.appendchild(itemli); } document.body.appendchild(outer); if faced with the following from an earlier example: <section itemscope itemtype="http://example.org/animals#cat"> <h1 itemprop="name http://example.com/fn">hedral</h1> <p itemprop="desc">hedral is a male american domestic shorthair, with a fluffy <span itemprop="http://example.com/color">black</span> fur with <span itemprop="http://example.com/color">white</span> paws and belly.</p> <img itemprop="img" src="hedral.jpeg" alt="" title="hedral, age 18 months"> </sectio...
Push API - Web APIs
Web › API › Push API
e service worker is active, it can subscribe to push notifications, using pushmanager.subscribe(). the resulting pushsubscription includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data. the service worker will be started as necessary to handle incoming push messages, which are delivered to the serviceworkerglobalscope.onpush event handler. this allows apps to react to push messages being received, for example, by displaying a notification (using serviceworkerregistration.shownotification().) each subscription is unique to a service worker. the endpoint for the subscription is a unique capability url: knowledge of the endpoint is all that is necessary to send a message to your application. the endpoint url th...
...t all generate a visible notification. note: chrome versions earlier than 52 require you to set up a project on google cloud messaging to send push messages, and use the associated project number and api key when sending push notifications. it also requires an app manifest, with some special parameters to use this service. interfaces pushevent represents a push action, sent to the global scope of a serviceworker. it contains information sent from an application to a pushsubscription. pushmanager provides a way to receive notifications from third-party servers, as well as request urls for push notifications. this interface has replaced the functionality offered by the obsolete pushregistrationmanager interface. pushmessagedata provides access to push data sent by a server, and inclu...
... point for using push messages. they also monitor and respond to push and subscription change events. serviceworkerregistration.pushmanager read only returns a reference to the pushmanager interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. this is the entry point into using push messaging. serviceworkerglobalscope.onpush an event handler fired whenever a push event occurs; that is, whenever a server push message is received. serviceworkerglobalscope.onpushsubscriptionchange an event handler fired whenever a pushsubscriptionchange event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.) examples mozilla'...
SharedWorker - Web APIs
note: if sharedworker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port). ...
... note: if sharedworker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port). ...
...the ports associated with that worker are accessible in the connect event's ports property — we then use messageport start() method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.addeventlistener('message', function(e) { v...
Web Authentication API - Web APIs
ace in the browser and authenticator and what the resulting data means. figure 1 - a diagram showing the sequence of actions for a web authentication registration and the essential data associated with each action. the registration steps are: application requests registration - the application makes the initial registration request. the protocol and format of this request is outside of the scope of the web authentication api. server sends challenge, user info, and relying party info - the server sends a challenge, user information, and relying party information to the javascript program. the protocol for communicating with the server is not specified and is outside of the scope of the web authentication api. typically, server communications would be rest over https (probably using xmlht...
...e (where publickeycredential.response is the authenticatorassertionresponse interface) . figure 2 - similar to figure 1, a diagram showing the sequence of actions for a web authentication and the essential data associated with each action. application requests authentication - the application makes the initial authentication request. the protocol and format of this request is outside of the scope of the web authentication api. server sends challenge - the server sends a challenge to the javascript program. the protocol for communicating with the server is not specified and is outside of the scope of the web authentication api. typically, server communications would be rest over https (probably using xmlhttprequest or fetch), but they could also be soap, rfc 2549 or nearly any other proto...
...hat was signed by the authenticator matches the challenge that was generated by the server. checking that the relying party id is the one expected for this service. a full list of the steps for validating an assertion can be found in the web authentication api specification. assuming the validation is successful, the server will note that the user is now authenticated. this is outside the scope of the web authentication api specification, but one option would be to drop a new cookie for the user session. interfaces credential provides information about an entity as a prerequisite to a trust decision. credentialscontainer exposes methods to request credentials and notify the user agent when events such as successful sign in or sign out happen. this interface is accessible from ...
Using Web Workers - Web APIs
ersa). this article provides a detailed introduction to 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 scrip...
...ge received from worker'); } here we grab the message event data and set it as the textcontent of the result paragraph, so the user can see the result of the calculation. note: notice that onmessage and postmessage() need to be hung off the worker object when used in the main script thread, but not when used in the worker. this is because, inside the worker, the worker is effectively the global scope. note: when a message is passed between the main 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(); th...
... features inside a web worker, including: navigator xmlhttprequest array, date, math, and string windowtimers.settimeout and windowtimers.setinterval the main thing you can't do in a worker is directly affect the parent page. this includes manipulating the dom and using that page's objects. you have to do it indirectly, by sending a message back to the main script via dedicatedworkerglobalscope.postmessage, then actioning the changes from there. note: for a complete list of functions available to workers, see functions and interfaces available to workers. specifications specification status comment html living standardthe definition of 'web workers' in that specification. living standard ...
Worker.onmessage - Web APIs
Web › API › Worker › onmessage
note: the message payload is available in the message event's data property. syntax myworker.onmessage = function(e) { ... ...
... for a full example, see ourbasic dedicated worker example (run dedicated worker). specifications specification status comment html living standardthe definition of 'worker.onmessage' in that specification. living standard ...
... for a full example, see ourbasic dedicated worker example (run dedicated worker). specifications specification status comment html living standardthe definition of 'worker.onmessage' in that specification. living standard ...
CSS Containment - CSS: Cascading Style Sheets
es you a nice way to explain to the browser this fact, and allow it to make performance optimizations based on that knowledge. key concepts and terminology this specification defines only one property, the contain property. the values for this property indicate the type of containment that you want to apply to that element. ...
... in addition: float layout will be performed independently. ...
... children cannot affect the size of the element itself — its size is computed as if it had no children. if you turn on contain: size you need to also specify the size of the element you have applied this to. it will end up being zero-sized in most cases, if you don't manually give it a size. style containment article { contain: style; } despite the name, style containment does not provide scoped styles such as you would get with the shadow dom. the main use case is to prevent situations where a css counter could be changed in an element, which could then affect the rest of the tree. using contain: style would ensure that the counter-increment and counter-set properties created new counters scoped to that subtree only. note: style containment is "at-risk" in the spec and may not be s...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
ha channel, to make the color less than 100% opaque. ...
...paque. ...
... white (or nearly white), black (or nearly black), and some number of shades of gray. usually, you are far better off using the smallest number of colors possible. by using color to accentuate rather than adding color to everything on the page, you keep your content easy to read and the colors you do use have far more impact. color theory resources a full review of color theory is beyond the scope of this article, but there are plenty of articles about color theory available, as well as courses you can find at nearby schools and universities. a couple of useful resources about color theory: color science (khan academy in association with pixar) an online course which introduces concepts such as what color is, how it's percieved, and how to use colors to express ideas. presented by pixa...
<th> - HTML: Hypertext Markup Language
Web › HTML › Element › th
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. content categories none. permitted content flow content, but with no header, footer, sectioning content, or heading content descendants. tag omission the start tag is mandatory. ...
...bute of the <th> elements that apply to this element. rowspan this attribute contains a non-negative integer value that indicates for how many rows the cell extends. its default value is 1; if its value is set to 0, it extends until the end of the table section (<thead>, <tbody>, <tfoot>, even if implicitly defined), that the cell belongs to. values higher than 65534 are clipped down to 65534. scope this enumerated attribute defines the cells that the header (defined in the <th>) element relates to. it may have the following values: row: the header relates to all cells of the row it belongs to. col: the header relates to all cells of the column it belongs to. rowgroup: the header belongs to a rowgroup and relates to all of its cells. these cells can be placed to the right or the lef...
... element. to achieve the same effect as the char value, give the text-align property the same value you would use for the char. unimplemented in css3. axis obsolete since html5 this attribute contains a list of space-separated strings. each string is the id of a group of cells that this header applies to. note: do not use this attribute as it is obsolete in the latest standard: use the scope attribute instead. bgcolor this attribute defines the background color of each cell in a column. it consists of a 6-digit hexadecimal code as defined in srgb and is prefixed by '#'. this attribute may be used with one of sixteen predefined color strings: black = "#000000" green = "#008000" silver = "#c0c0c0" lime = "#00ff00" ...
itemref - HTML: Hypertext Markup Language
properties that are not descendants of an element with the itemscope attribute can be associated with an item using the global attribute itemref. itemref provides a list of element ids (not itemids) elsewhere in the document, with additional properties the itemref attribute can only be specified on elements that have an itemscope attribute specified. note: the itemref attribute is not part of the microdata data model. it is merely a syntactic construct to aid authors in adding annotations to pages where the data to be annotated does not follow a convenient tree structure. for example, it allows authors to mark up data in a table so that each column defines a separate item while keeping the properties in the cells. ...
...d. note: the itemref attribute is not part of the microdata data model. it is merely a syntactic construct to aid authors in adding annotations to pages where the data to be annotated does not follow a convenient tree structure. for example, it allows authors to mark up data in a table so that each column defines a separate item while keeping the properties in the cells. ...
...ding annotations to pages where the data to be annotated does not follow a convenient tree structure. for example, it allows authors to mark up data in a table so that each column defines a separate item while keeping the properties in the cells. ...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
or more properties forms an item. property values are either a string or a url and can be associated with a very wide range of elements including <audio>, <embed>, <iframe>, <img>, <link>, <object>, <source> , <track>, and <video>. ...
... with a very wide range of elements including <audio>, <embed>, <iframe>, <img>, <link>, <object>, <source> , <track>, and <video>. 23 itemref attribute, global attribute, html, html microdata, microdata, reference properties that are not descendants of an element with the itemscope attribute can be associated with an item using the global attribute itemref. 24 itemscope attribute, global attribute, html, html microdata, microdata, reference itemscope is a boolean global attribute that defines the scope of associated metadata. specifying the itemscope attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element. 25 itemtype attribute, global attribute, html, html microdata...
..., web the html <tfoot> element defines a set of rows summarizing the columns of the table. 208 <th> element, html, html tabular data, heading cell, reference, table cell, table head, table header, table heading, table heading cell, tables, web, cell the html <th> element defines a cell as header of a group of table cells. the exact nature of this group is defined by the scope and headers attributes. 209 <thead>: the table head element element, html, html tabular data, reference, tables, web the html <thead> element defines a set of rows defining the head of the columns of the table. 210 <time> element, html, html text-level semantics, html5, html:flow content, html:palpable content, html:phrasing content, reference, web the ht...
Control flow and error handling - JavaScript
lock statement, which is used to group statements. the block is delimited by a pair of curly brackets: { statement_1; statement_2; ⋮ statement_n; } example block statements are commonly used with control flow statements (if, for, while). while (x < 10) { x++; } here, { x++; } is the block statement. important: javascript before ecmascript2015 (6th edition) does not have block scope! in older javascript, variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. in other words, block statements do not define a scope. "standalone" blocks in javascript can produce completely different results from what they would produce in c or java. for example: var x = 1; { var x = 2; } console.l...
...see the let and const reference pages for more information. ...
...see the let and const reference pages for more information. conditional statements a conditional statement is a set of commands that executes if a specified condition is true. ...
Using Promises - JavaScript
dosomething() is the same function as before. you can read more about the syntax here. promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown exceptions and programming errors. this is essential for functional composition of asynchronous operations. promise rejection events whenever a promise is rejected, one of two events is sent to the global scope (generally, this is either the window or, if being used in a web worker, it's the worker or other worker-based interface). the two events are: rejectionhandled sent when a promise is rejected, after that rejection has been handled by the executor's reject function. unhandledrejection sent when a promise is rejected but there is no rejection handler available. in both cases, the event (of ...
...oon: const wait = ms => new promise(resolve => settimeout(resolve, ms)); wait().then(() => console.log(4)); promise.resolve().then(() => console.log(2)).then(() => console.log(3)); console.log(1); // 1, 2, 3, 4 nesting simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition. see common mistakes. nesting is a control structure to limit the scope of catch statements. specifically, a nested catch only catches failures in its scope and below, not errors higher up in the chain outside the nested scope. when used correctly, this gives greater precision in error recovery: dosomethingcritical() .then(result => dosomethingoptional(result) .then(optionalresult => dosomethingextranice(optionalresult)) .catch(e => {})) // ignore if optional st...
...ence, the chain is broken, or rather, we have two independent chains racing. this means dofourththing() won't wait for dosomethingelse() or dothirdthing() to finish, and will run in parallel with them, likely unintended. separate chains also have separate error handling, leading to uncaught errors. the second mistake is to nest unnecessarily, enabling the first mistake. nesting also limits the scope of inner error handlers, which—if unintended—can lead to uncaught errors. a variant of this is the promise constructor anti-pattern, which combines nesting with redundant use of the promise constructor to wrap code that already uses promises. the third mistake is forgetting to terminate chains with catch. unterminated promise chains lead to uncaught promise rejections in most browsers. a go...
TypeError: invalid assignment to const "x" - JavaScript
) typeerror: redeclaration of const 'x' (ie) error type typeerror what went wrong? 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. in javascript, constants are declared using the const keyword. examples invalid redeclaration assigning a value to the same constant name in the same block-scope will throw. const columns = 80; // ... columns = 120; // typeerror: invalid assignment to const `columns' fixing the error there are multiple options to fix this error. check what was intended to be achieved with the constant in question. rename if you meant to declare another constant, pick another name and re-name. this constant name is already taken in this scope. const columns = 80; c...
...ple options to fix this error. check what was intended to be achieved with the constant in question. rename if you meant to declare another constant, pick another name and re-name. this constant name is already taken in this scope. const columns = 80; const wide_columns = 120; const, let or var? ...
...nstant, pick another name and re-name. this constant name is already taken in this scope. const columns = 80; const wide_columns = 120; const, let or var? do not use const if you weren't meaning to declare a constant. maybe you meant to declare a block-scoped variable with let or global variable with var. let columns = 80; // ... let columns = 120; scoping check if you are in the correct scope. should this constant appear in this scope or was it meant to appear in a function, for example? const columns = 80; function setupbigscreenenvironment() { const columns = 120; } const and immutability the const declaration creates a read-only reference to a value. it does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. for instance, in case...
ReferenceError: "x" is not defined - JavaScript
the javascript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere. message referenceerror: "x" is not defined error type referenceerror. 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); // referenceerror: 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...
... 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); // referenceerror: 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 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); // referenceerror num1 is not defined. however, a function can access al...
...rent 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); // referenceerror 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 ...
Arrow function expressions - JavaScript
owup() { // the callback refers to the `that` variable of which // the value is the expected object. that.age++; }, 1000); } alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growup() function in the example above). an arrow function does not have its own this. the this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. so while searching for this which is not present in the current scope, an arrow function ends up finding the this from its enclosing scope. thus, in the following code, the this within the function that is passed to setinterval has the same value as the this in the lexically enclosing function: function person(){ this.age = 0; ...
...nction(a) { var f = v => v + this.base; var b = { base: 2 }; return f.call(b, a); } }; console.log(adder.add(1)); // this would log 2 console.log(adder.addthrucall(1)); // this would log 2 still no binding of arguments arrow functions do not have their own arguments object. thus, in this example, arguments is simply a reference to the arguments of the enclosing scope: var arguments = [1, 2, 3]; var arr = () => arguments[0]; arr(); // 1 function foo(n) { var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n return f(); } foo(3); // 6 in most cases, using rest parameters is a good alternative to using an arguments object. function foo(n) { var f = (...args) => args[0] + n; return f(10); } foo(1); // 11 arrow func...
... using rest parameters is a good alternative to using an arguments object. function foo(n) { var f = (...args) => args[0] + n; return f(10); } foo(1); // 11 arrow functions used as methods as stated previously, arrow function expressions are best suited for non-method functions. let's see what happens when we try to use them as methods: 'use strict'; var obj = { // does not create a new scope i: 10, b: () => console.log(this.i, this), c: function() { console.log(this.i, this); } } obj.b(); // prints undefined, window {...} (or the global object) obj.c(); // prints 10, object {...} arrow functions do not have their own this. another example involving object.defineproperty(): 'use strict'; var obj = { a: 10 }; object.defineproperty(obj, 'b', { get: () => { conso...
delete operator - JavaScript
if the property which you are trying to delete does not exist, delete will not have any effect and will return true. if a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties). any property declared with var cannot be deleted from the global scope or from a function's scope. as such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression). functions which are part of an object (apart from the global scope) can be deleted with delete. any property declared with let or const cannot be deleted from the scope within which they were defined. non-configurable p...
...s one might expect after having deleted the property and then added it back. if you want to use an ordered associative array in a cross-browser environment, use a map object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc. examples // creates the property adminname on the global scope. adminname = 'xyz'; // creates the property empcount on the global scope. // since we are using var, this is marked as non-configurable. the same is true of let and const. var empcount = 43; employeedetails = { name: 'xyz', age: 5, designation: 'developer' }; // adminname is a property of the global scope. // it can be deleted since it is created without var, // and is therefore configur...
...s used. delete empcount; // returns false // delete can be used to remove properties from objects. delete employeedetails.name; // returns true // even when the property does not exist, delete returns "true". delete employeedetails.salary; // returns true // delete does not affect built-in static properties. delete math.pi; // returns false // employeedetails is a property of the global scope. // since it was defined without "var", it is marked configurable. delete employeedetails; // returns true function f() { var z = 44; // delete doesn't affect local variable names delete z; // returns false } delete and the prototype chain in the following example, we delete an own property of an object while a property with the same name is available on the prototype chain: fun...
block - JavaScript
ctice in javascript. the opposite behavior is possible using an empty statement, where you provide no statement, although one is required. blocks are commonly used in association with if...else and for statements. examples block scoping rules with var or function declaration in non-strict mode variables declared with var or created by function declarations in non-strict mode do not have block scope. variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. in other words, block statements do not introduce a scope. for example: var x = 1; { var x = 2; } console.log(x); // logs 2 this logs 2 because the var x statement within the block is in the same scope as the var x statement before the block. ...
...{ var x = 2; } console.log(x); // logs 2 this logs 2 because the var x statement within the block is in the same scope as the var x statement before the block. in non-strict code, function declarations inside blocks behave strangely. do not 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 syntaxerror... ...
...les 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 syntaxerror... note that the block-scoped const c = 2 does not throw a syntaxerror: 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-262)the definition of 'block sta...
switch - JavaScript
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': ...
...output: so what is your name? 1 output: what is your name? 2 output: your name? 3 output: name? 4 output: ? 5 output: ! block-scope variables within switch statements with ecmascript 2015 (es6) support made available in most modern browsers, there will be cases where you would want to 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 syntaxerror: identifier 'message' ha...
...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 the same variable name within the same block scope. we can easily fix this by wrapping our case clauses with brackets: const action = 'say_hello'; switch (action) { case 'say_hello': { // added brackets let message = 'hello'; console.log(message); break; } // added brackets case 'say_hi': { // added brackets let message = 'hi'; console.log(message); break; } // added brackets default: { // added brackets co...
Strict mode - JavaScript
ct. obviously, concatenation of scripts is never ideal, but if you must, consider enabling strict on a function-by-function basis. you can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. this eliminates the concatenation problem and it means that you have to explicitly export any shared variables out of the function scope. strict mode for functions likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements. function strict() { // function-level strict mode syntax 'use strict'; function nested() { return 'and so am i!'; } return "hi! i'm a strict mode function! " + nested(); } function notstrict() { return ...
... basic mapping of name to variable definition in the code impossible to perform until runtime. strict mode removes most cases where this happens, so the compiler can better optimize strict mode code. first, strict mode prohibits with. the problem with with is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at runtime: it's impossible to know which beforehand. strict mode makes with a syntax error, so there's no chance for a name in a with to refer to an unknown location at runtime: 'use strict'; var x = 17; with (obj) { // !!! syntax error // if this weren't strict mode, would this be var x, or // would it instead be obj.x? it's impossible in general // to say without running the code, so ...
..., or // would it instead be obj.x? it's impossible in general // to say without running the code, so the name can't be // optimized. x; } the simple alternative of assigning the object to a short name variable, then accessing the corresponding property on that variable, stands ready to replace with. second, eval of strict mode code does not introduce new variables into the surrounding scope. in normal code eval("var x;") introduces a variable x into the surrounding function or the global scope. this means that, in general, in a function containing a call to eval every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). in strict mode eval ...
Private Properties - Archive of obsolete content
ys. when an object is used as a key, it's converted to a string using its tostring method. to make the above code work, a unique identifier must be associated with each image and override its tostring method. the second problem is more severe: the thumbnail cache maintains a strong reference to each thumbnail object, so they will never be freed, even when their corresponding image has gone out of scope. this is a memory leak waiting to happen. the above two problems are exactly what weakmaps were designed to solve. a weakmap is very similar to an ordinary hash map, but differs from it in two crucial ways: it can use ordinary objects as keys it does not maintain a strong reference to its values to understand how weakmaps are used in practice, the following rewrites the thumbnail cache usi...
...rewrites the thumbnail cache using a weakmap: let thumbnails = new weakmap(); function getthumbnail(image) { let thumbnail = thumbnails.get(image); if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails.set(image, thumbnail); } return thumbnail; } this version suffers from none of the problems we mentioned earlier. when a thumbnail's image goes out of scope, the weakmap ensures that its entry in the thumbnail cache will eventually be garbage collected. as a final caveat: the image cache created earlier suffers from the same problem, so for the above code to work properly, the image cache must be rewritten using weakmaps too. from weakmap to namespace in the previous section, a separate weakmap was used to associate each private property with an ob...
StringView - Archive of obsolete content
presented by a collection of 1-6 uint8 elements for utf-8, 1-2 uint16 elements for utf-16, 1 uint32 element for ucs4, 1 uint8 element for ascii, or something else. byte a collection of 8 bits. null codepoint the character whose codepoint is equal to 0 ('\0'). notes when you include the script stringview.js into a page, no variables other than stringview itself will be added to the global scope. stringview is a highly extensible library, that anyone can extend by adding methods to the object stringview.prototype. for example, imagine you want to create a method similar to string.replace(), but for stringview objects. maybe you would like to solve a situation like the following: var omystringview = new stringview("hello,&nbsp;strange&nbsp;people!"); // utf-8 var omyregexp = new clik...
...ringview); // "hello, strange people!\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000" as you can see, the previous example needs you to create two new algorithms: the clikeregexp() constructor – a constructor of c-like regular expression objects – and stringview.prototype.replace() – the new method, able to act on stringview instances. well, just include stringview.js to your scope and work on them in another script: /* a constructor of c-like regular expression objects... */ function clikeregexp (sregexp, sflags) { /** * [...] * * constructor code here! **/ } /* a "replace" method for stringview... */ stringview.prototype.replace = function (oclikeregexp, swith) { /** * [...] * * method code here! **/ }; if you want to cre...
Jetpack Processes - Archive of obsolete content
rome process are the only means by which they can be endowed with any real power. note: the above statement is not currently true, as js-ctypes is now provided to jetpack processes as of bug 588563. a mechanism to optionally disable this feature has been proposed in bug 614351. privileged apis when script is evaluated in a jetpack process via a call to nsijetpack.evalscript(), the script's global scope is endowed with the following privileged apis: sendmessage(amessagename [, v1 [, v2 [, ...]]]) similar to nsijetpack.sendmessage(), this function asynchronously sends a message to the chrome process. callmessage(amessagename [, v1 [, v2 [, ...]]]) this function is like sendmessage() but sends the message synchronously. it returns an array whose elements are the return values of each receiver in ...
...n unregisters a callback previously registered with registerreceiver(). unregisterreceivers(amessagename) similar to nsijetpack.unregisterreceivers(), this function unregisters all callbacks for the given message name. createhandle() similar to nsijetpack.createhandle(), this function creates a new handle and returns it. createsandbox() this creates a new javascript sandbox and returns its global scope. this global scope does not contain privileged apis, or any non-standard javascript objects for that matter, though new globals can be endowed by simply attaching them to the global scope as properties. evalinsandbox(asandbox, ascript) evaluates the given script contents in the given sandbox's global scope. at minimum, javascript 1.8.1 is used. individual lines of the form //@line 1 "foo.js" can ...
JavaScript Object Management - Archive of obsolete content
avascript has a host of features that make it extremely flexible, but it also has some disadvantages, as it is not as strict as other languages, such as java. a clear example of this is the fact that there are no private or public keywords that allow you to protect object members. as a alternative for this, a naming standard is frequently used to distinguish private and public members. there's no scope enforcement whatsoever, but this standard give others the chance to "play nice" and don't use private members. use "_" at the beginning of private attributes and methods in js objects. for example: _stringbundle, _createusernode(). exercise here's a short exercise to test a particular aspect of the chrome. modify the hello world extension so that the message says how many times it has been...
...rting your code to seamonkey, which doesn't have those constants declared in the main window). include the cc and ci constants in all xul windows that are not overlays, all jsm files, and all xpcom components (see further ahead). do this even if you don't need them now. it's better to just make a habit out of it. this is a point that is worth highlighting: modules work outside of the window scope. unlike scripts in the chrome, modules don't have access to objects such as window, document, or other global functions, such as openuilink. these are all ui components and ui operations anyway, so they are better done in the chrome. as a general guideline, we keep all of our business logic in jsm, available through service objects, and chrome scripts are limited to handle presentation logic. ...
Setting up an extension development environment - Archive of obsolete content
however, it is usually easier to place extension files in a temporary location, which also protects source files from accidental deletion. this section explains how to create a proxy file...
... ...
Tabbed browser - Archive of obsolete content
furthermore another meaning of 'browser' in this document and in some firefox source is "the tabbrowser element" in a firefox xul window. getting access to the browser from main window code running in firefox's global chromewindow, common for extensions that overlay into browser.xul, can access the tabbrowser element using the global variable gbrowser. // gbrowser is only accessible from the scope of // the browser window (browser.xul) gbrowser.addtab(...); if gbrowser isn't defined your code is either not running in the scope of the browser window or running too early. you can access gbrowser only after the browser window is fully loaded. if you need to do something with gbrowser right after the window is opened, listen for the load event and use gbrowser in the event listener. if your...
...n selected } // during initialisation var container = gbrowser.tabcontainer; container.addeventlistener("tabselect", exampletabselected, false); // when no longer needed container.removeeventlistener("tabselect", exampletabselected, false); getting document of currently selected tab the following code allows you to retrieve the document that is in the selected tab. this code will work in the scope of the browser window (e.g. you're working from an overlay to the browser window). gbrowser.contentdocument; or content.document if you're working from a window or dialog that was opened by the browser window, you can use this code to get the document displayed in the selected tab in the browser window that opened the new window or dialog. window.opener.content.document from windows or d...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
) will show you this popup: that's a popup titled as "error", but it's just a debug tool for me as i didn't find any other way to popup information. cf. bug 206294: ------- comment #14 from daniel wang 2003-11-06 09:06 pdt [reply] ------- jehan procaccia, you need to change 5.8 to reflect what i said in comment 21. ...
...autoconfig works fine, but ldap calls are still unavailable in firefox (as it was the case in firefox 1.x, but fortunatly not the case for thunderbird !). ...
Metro browser chrome tests - Archive of obsolete content
running the metro browser chrome tests to run mochitest, first build mozilla with your changes; then run ./mach mochitest-metro this will launch metro browser chrome tests in the default immersive browser. ...
...nored unless invoked by test(). gtests make use of promises and tasks for managing execution. test comparison functions used in metro browser chrome tests are identical to those supported by mochitests, see how the comparison functions work in the mochitest documentation for more details. helper functions the eventutils helper functions are available on the eventutils object defined in the global scope. additional metro specific test helpers can be found in /browser/metro/base/tests/mochitest/head.js. you may add additional common utils and helpers to head.js. be careful about changing existing helpers as changes may impact tests in other libraries. static content for tests static content (html files, images, etc.) should be stored in sub directories to avoid polluting the main test directory. ...
Abc Assembler Tests - Archive of obsolete content
rms of the mpl, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the gpl or the lgpl. if you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the mpl, the gpl or the lgpl. ...
...ll .try { pushnull convert_o pop findproperty fail pushstring "convert_o null" pushstring "exception should have been thrown: typeerror: error #1009: cannot access a property or method of a null object reference." getlocal1 callpropvoid fail 3 jump finished_convert_o_null } .catch { getlocal0 pushscope setlocal2 // save typeerror findproperty compare_typeerror pushstring "convert_o null" // test name pushstring "typeerror: error #1009" // expected getlocal2 // actual callpropvoid compare_typeerror 3 } finished_convert_o_null: } ...
Using Breakpoints in Venkman - Archive of obsolete content
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 displays the value of the newsig...
...tory venkman article. clearing breakpoints to clear the breakpoint, click on the margin twice. the first click will clear the hard breakpoint and leave you with only a future breakpoint, which is represented by a yellow letter "f". a second click will remove the future breakpoint as well. advanced breakpoints venkman allows you to associate a breakpoint with a script that will be executed in the scope of the function when that breakpoint is hit. this advanced feature and other options you can see for the associated script are available from the future breakpoint properties dialog, which you can access by right-clicking a breakpoint and selecting properties. once you've created a script that will be executed when the associated breakpoint is hit, you can select a number of different options fr...
XBL 1.0 Reference - Archive of obsolete content
this example is targeted to demonstrate the xbl usage...
... this example is targeted to demonstrate the xbl usage rather than to be a practically useful application. for this reason it contains many comments and some blocks could ...
NPN_Evaluate - Archive of obsolete content
script the script to evaluate. result on return, contains the value returned by the script. can't be null. returns true if the script was evaluated successfully, otherwise false. ...
... script the script to evaluate. result on return, contains the value returned by the script. can't be null. returns true if the script was evaluated successfully, otherwise false. ...
Scratchpad - Archive of obsolete content
x and a short description: the "[docs]" link takes you to the mdn documentation for the symbol. executing once you've written your code, select the code you want to run. if you don't select anything, all the code in the window will be run. then choose the way you want the code to run using the buttons along the top, using the execute menu, or using the context menu. the code is executed in the scope of the currently selected tab. any variables you declare outside of a function will be added to the global object for that tab. there are four execution options available. run when you choose the run option, the selected code is executed. this is what you'd use to execute a function or other code that manipulates the content of your page without needing to see the result. inspect the inspec...
...ent. running scratchpad in the browser context you can run scratchpad in the context of the browser as a whole rather than a specific web page. this is useful if you are working on firefox itself or developing add-ons. to do this check "enable chrome and add-on debugging" in the developer tool settings. once you've done this, the environment menu has a browser option; once that's selected, your scope is the entire browser rather than just the page content, as you will see from examining some globals: window /* [object chromewindow] */ gbrowser /* [object xulelement] */ the scratchpad execution context is set to browser when a snippet file has // -sp-context: browser on the first line. keyboard shortcuts command windows macos linux open the scratchpad shift...
Common causes of memory leaks in extensions - Extensions
o window objects or dom nodes (such as window.document) for too long by storing them in a javascript module. for example: var windows = []; function injavascriptcodemodule(window) { // forgetting or failing to pop the window again windows.push(window); } both of these cases can happen if you forget 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 7258...
...ent.body.someproperty = leakref; } see also kris maglione's guide to cleaning up bootstrapped extensions. failing to clean up event listeners extensions can be disabled and removed by user actions, but it also happens when an add-on is updated. if a bootstrapped (restartless) extension fails to clean up event listeners when disabled or removed, the listeners will still reference the enclosing scope — usually the bootstrap.js sandbox — and therefore keep that scope (and its enclosing compartment) alive until the window is unloaded. if the window in question is browser.xul or some long-lived web app such as gmail, the leaked compartment might survive for quite some time. function leakref() {} function main(window) { // this is a potential leak, as the window (e.g. browser.xul) will ho...
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
scripts running under node.js have an object called global as their global object. ...
... of the global object. (in node.js this is not the case.) the global object's interface depends on the execution context in which the script is running. for example: in a web browser, any code which the script doesn't specifically start up as a background task has a window as its global object. this is the vast majority of javascript code on the web. code running in a worker has a workerglobalscope object as its global object. scripts running under node.js have an object called global as their global object. window object in the browser the window object is the global object in the browser. any global variables or functions can be accessed as properties of the window object. access global variables var foo = "foobar"; foo === window.foo; // returns: true after defining a global vari...
Global variable - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript it is a property of the global object. ...
... in javascript it is a property of the global object. ...
IIFE - MDN Web Docs Glossary: Definitions of Web-related terms
an iife (immediately invoked function expression) is a javascript function that runs as soon as it is defined. (function () { statements })(); it is a design pattern which is also known as a self-executing anonymous function and contains two major parts: the first is the anonymous function with lexical scope enclosed within the grouping operator (). this prevents accessing variables within the iife idiom as well as polluting the global scope. the second part creates the immediately invoked 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 = "barr...
... second part creates the immediately invoked 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 referenceerror: 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" ...
From object to iframe — other embedding technologies - Learn web development
0 removes the border. using this isn't really recommended any more, as the same effect can be better achieved using border: none; in your css. src this attribute, as with <video>/<img>, contains a path pointing to the url of the document to b...
...x-frame-options header. this can prevent other websites from embedding your content in their web pages (which would enable clickjacking and a host of other attacks), which is exactly what the mdn developers have done, as we saw earlier on. note: you can read frederik braun's post on the x-frame-options security header for more background information on this topic. obviously, it's rather out of scope for a full explanation in this article. the <embed> and <object> elements the <embed> and <object> elements serve a different function to <iframe> — these elements are general purpose embedding tools for embedding multiple types of external content, which include plugin technologies like java applets and flash, pdf (which can be shown in a browser with a pdf plugin), and even content like vi...
Index - Learn web development
another essential concept in coding is functions, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. in this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters. 93 image gallery assessment, beginner, codingscripting, conditionals, event handler, javascript, learn, loops, events, l10n:priority now that we've looked at the fundamental building blocks of javascript, we'll test your knowledge of loops, functions, conditionals and events by getting you to build a fairly common item you'll see on a lot of websites — a ja...
... structuring planet data assessment, beginner, codingscripting, html, learn, tables in our table assessment, we provide you with some data on the planets in our solar system, and get you to structure it into an html table. 228 html table advanced features and accessibility accessibility, advanced, article, beginner, codingscripting, html, headers, learn, caption, nesting, scope, sumary, table, tbody, tfoot, thead there are a few other things you could learn about table html, but we have really given all you need to know at this moment in time. at this point, you might want to go and learn about styling html tables — see styling tables. 229 html table basics article, beginner, codingscripting, html, learn, tables, basics, cell, col, colgroup, colsp...
Build your own function - Learn web development
function immediately — only after the button has been clicked. if you try changing the line to btn.onclick = displaymessage(); and saving and reloading, you'll see that the message box appears without the button being clicked! the parentheses in this context are sometimes called the "function invocation operator". you only use them when you want to run the function immediately in the current scope. in the same respect, the code inside the anonymous function is not run immediately, as it is inside the function scope. if you tried the last experiment, make sure to undo the last change before carrying on. improving the function with parameters as it stands, the function is still not very useful — we don't want to just show the same default message every time. let's improve our function b...
...lude some updated message text. change the following line: btn.onclick = displaymessage; to this block: btn.onclick = function() { displaymessage('woo, this is a different message!'); }; if we want to specify parameters inside parentheses for the function we are calling, then we can't call it directly — we need to put it inside an anonymous function so that it isn't in the immediate scope and therefore isn't called immediately. now it will not be called until the button is clicked. reload and try the code again and you'll see that it still works just fine, except that now you can also vary the message inside the parameter to get different messages displayed in the box! a more complex parameter on to the next parameter. this one is going to involve slightly more work — we are...
Solve common problems in your JavaScript code - Learn web development
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 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 af...
...r the members of an object nested inside an array? intermediate use cases functions how do you find functions in the browser? what is the difference between a function and a method? how do you create your own functions? how do you run (call, or invoke) a function? what is an anonymous function? how do you specify parameters (or arguments) when invoking a function? what is function scope? what are return values, and how do you use them? objects how do you create an object? what is dot notation? what is bracket notation? how do you get and set the methods and properties of an object? what is this, in the context of an object? what is object-oriented programming? what are constructors and instances, and how do you create them? what different ways are there to create ob...
Ember interactivity: Events, classes and state - Learn web development
ibute is inside double curly braces, which tells you it is part of ember's dynamic templating syntax. the first argument passed to on is the type of event to respond to (keydown), and the last argument is the event handler — the code that will run in response to the keydown event firing. as you may expect from dealing with vanilla javascript objects, the this keyword refers to the "context" or "scope" of the component. one component's this will be different from another component's this. we can define what is available inside this by generating a component class to go along with your component. this is a vanilla javascript class and has no special meaning to ember, other than extending from the component super-class. to create a header class to go with your header component, type this in to...
... access them. storing todos with a service ember has built-in application-level state management that we can use to manage the storage of our todos and allow each of our components to access data from that application-level state. ember calls these constructs services, and they live for the entire lifetime of the page (a page refresh will clear them; persisting the data for longer is beyond the scope of this tutorial). run this terminal command to generate a service for us to store our todo-list data in: ember generate service todo-data this should give you a terminal output like so: installing service create app/services/todo-data.js installing service-test create tests/unit/services/todo-data-test.js this creates a todo-data.js file inside the todomvc/app/services directory to cont...
Package management basics - Learn web development
type the following command, making sure you are inside the parcel-experiment directory: npm init you will now be asked some questions; npm will then create a default package.json file based on the answers: name: a name to identify the app. just press return to accept the default parcel-experiment. version: the starting version number for the app: again, just press return ...
...rcel. there will be more available than this, but these are popular ones: the rollup tool offers tree shaking and code splitting as it’s core features. webpack requires some configuration (though “some” might be understating the complexity of some developers’ webpack configurations). in the case of parcel (prior to parcel version 2), there's a special flag required — --experimental-scope-hoisting — which will tree shake while building. let’s stick with parcel for now, given that we’ve already got it installed. try running the following command: parcel build index.html --experimental-scope-hoisting you’ll see that this makes a huge difference: ✨ built in 7.87s. dist/my-project.86f8a5fc.js 10.34 kb 7.17...
Accessibility API cross-reference
command a supporting section of the document, designed to be complementary to the main content at a similar le...
...ed by giving each radio button the same value name attribute represents the an row in a table row n/a n/a row <tr> a structure containing one or more row elements in a tabular container. n/a n/a rowgroup n/a a table row header rowheader row_header row_header, table_row_header rowheader <th scope=row> vertical or horizontal scrollbar scrollbar scroll_bar scroll_bar scrollbar a landmark region that contains a collection of items and objects that, as a whole, combine to create a search facility. search a type of textbox intended for specifying search criteria. searchbox ...
Mozilla’s UAAG evaluation report
element (table): available through dom, can be styled using css? html: tbody element (table): available through dom, can be styled using css? html: tfoot element (table): available through dom, can be styled using css? html: colgroup element (table): available through dom, can be styled using css? html: col element (table): available through dom, can be styled using css? html: scope attribute (table): available through dom html: headers attribute (table): available through dom html: axis attribute (table): available through dom html: tabindex attribute: yes, can be used to order sequential navigation html: accesskey attribute: supported with alt-{key}, menu key conflict favor the accesskey? html: alt for img: yes html: longdesc for img: yes, available...
...ty, but not really intended for end users (tasks, tools, dom inspector) 9.10 configure important elements. (p3) ni the navigational elements aren't user configurable guideline 10. orient the user. checkpoint title status notes/plans checkpoint title status notes/plans 10.1 table orientation. (p1) ni we don't make use of scope, headers, axis, or any other table accessibility features we have nothing under properties, or anywhere else, to orient users reading a table 10.2 highlight selection and content focus. (p1) vg provides a focus outline box highlights follow graphical rendering conventions for windows does not highlight selected images we do not have the ability to show a border arou...
Message manager overview
ge manager, how to access them, and at a high level, what sorts of things you can use them for. at the top level, there are two different sorts of message managers: frame message managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) in the content process. these scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. if chrome code wants to run code in the content process so it can access web content, this is usually the sort of message manager to use. process message managers: these correspond to process boundaries, and enable code running in the parent (chrome) process to communicate with code running in the child (content) process. from firefox 38 onwards, they also enable co...
...operty of the xul <browser> element: // chrome script let browsermm = gbrowser.selectedbrowser.messagemanager; content process content frame message manager description there's a content frame message manager for every open tab. it's the content-side end of frame message manager conversations. frame scripts are loaded into the content frame message manager scope, and messages from chrome message managers end up here. the content frame message manager provides the global object for frame scripts (but note that there is trickery to ensure that top-level variables defined by frame scripts are not shared). frame scripts can use this object to send messages to the chrome process, and to receive messages from the chrome process. its most importa...
Performance
mething(message) { result = helper(content, message.data) sendasyncmessage("my-addon:response-from-child", {something: result}) } addmessagelistener("my-addon:request-from-parent", dosomething) why is this bad? because declared functions are also objects. and since frame scripts get evaluated for each tab this means new function objects get instantiated, new constants get computed, block scopes must be set up etc. while it may seem fairly innocencous in this toy example, real scripts often have a lot more functions and initialize some fairly heavyweight objects. better: addon.js as above // framescript.js components.utils.import("resource://my-addon/processmodule.jsm", {}).addframe(this) // processmodule.jsm const exported_symbols = ['addframe']; const precomputedconstants = //...
...if each framescript registers a seperate listener then the observed action will trigger the callbacks in all tabs. additionally the example above does not clean unregister itself, thus leaking objects each time a tab is closed. frame message manager message and event listeners are limited in their lifetime to that of the frame itself, this does not apply to observer regist...
ChromeWorker
tions and the behavior may change in the future. summary if you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object. it works exactly like a standard worker, except that it has access to js-ctypes via a global ctypes object available in the global scope of the worker. examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below. to use a postmessage with callback version of chromeworker that features promises, see promiseworker. addons must use absolute urls to load their workers, and those urls have to be using a chrome:// or resource:// protocol (file:// is not accepted). addons that wish...
...//my-cool-addon/worker.js'); more references: you can use chromeworker from javascript code modules. see using workers in javascript code modules for details. you can use chromeworker modules in chromeworkers. see using web workers for examples and details. see also using web workers using workers in javascript code modules worker sharedworker web workers specification workerglobalscope github :: chromeworker - a fully working demo addon using js-ctypes from a chrome worker. uses winapi example. promiseworker github :: promiseworker - shows how to uses promises as an twist on postmessage feature of chromeworker ...
JavaScript-DOM Prototypes in Mozilla
shtmlimageelement) implements and chooses to expose to xpconnect through the object's class info. one of these interfaces is nsidomhtmlimageelement, others are nsidomnshtmlimageelement (netscape extensions to the standard interface), nsidomeventtarget, nsidomeventlistener, nsidom3node, and so on. the prototype object that xpconnect creates for the classes that have class info are shared within a scope (window). because of this, the following holds true (assuming img1 and img2 are two different image objects in the same document): img1.__proto__ === img2.__proto__ if img1 would come from one document and img2 from another document, then the above would not be true. both prototypes would look identical, but they would be two different jsobject's. this sharing of prototypes lets users do cool...
...windowsh::globalresolve() will be called for every name on the parent chain). the result of this recursion is that by resolving the name htmlimageelement, we'll create the constructor htmlimageelement, htmlelement, element, and node, and the prototype properties on all those constructor will be correctly set up. this means that the next time the name of a class constructor is resolved in the same scope, say htmlanchorelement, the code will resolve the name htmlanchorelement, find the parent name, which is htmlelement, and resolve that, but since we've already resolved htmlelement as a result of resolving the name htmlimageelement earlier, the recursion will stop right there. ok, so that's how class constructor and their prototype properties are set up, what about the actual prototype chain of ...
FxAccountsOAuthClient.jsm
w successfully completes. first and only argument is an object that has "state" and "code" properties. constructor fxaccountsoauthclient() creates and returns a new fxaccountsoauthclient object. fxaccountsoauthclient fxaccountsoauthclient( object options object parameters string client_id string state string oauth_uri string content_uri [optional] string scope [optional] string action [optional] string authorizationendpoint ); parameters client_id - oauth id returned from client registration. state - oauth state value that will be returned to the client as-is upon redirection. oauth_uri - the fxa oauth api server uri, versioned. example: "https://oauth.accounts.firefox.com/v1" content_uri - the fxa content server uri. example: "https:/...
... [optional] string authorizationendpoint ); parameters client_id - oauth id returned from client registration. state - oauth state value that will be returned to the client as-is upon redirection. oauth_uri - the fxa oauth api server uri, versioned. example: "https://oauth.accounts.firefox.com/v1" content_uri - the fxa content server uri. example: "https://accounts.firefox.com" [optional] scope - a colon-separated list of scopes that the user has authorized. [optional] action - if provided, should be either "signup" or "signin". parameters set of parameters to initialize the firefox accounts oauth flow. authorizationendpoint optional optional authorization endpoint for the oauth server. default: /authorization return value a newly created fxaccountsoauthclient object...
Following the Android Toasts Tutorial from a JNI Perspective
wing java code, which invokes a toast and says "hello, firefox!". context context = getapplicationcontext(); charsequence text = "hello, firefox!"; int duration = toast.length_short; toast toast = toast.maketext(context, text, duration); toast.show(); nativewindow code as mentioned earlier, toasts are a very popular feature, so mozilla developers chose to bring it to the privileged javascript scope via the nativewindow object. the java code example above can be done with privileged javascript from firefox for android with the following code: window.nativewindow.toast.show("hello, firefox!", "short"); converting java to jni.jsm the first step is to look at the java code and see all the different types, methods, constructors, and fields that are being used. in the toast code we have the f...
...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 because the global privileged window scope of firefox for android has a variable jenv already, and we don't want to mix. declare constructors, methods, and fields now that the sig's and java environment is ready, it is now possible to declare the constructors, methods, and fields. load the class the first step is to load the class. every constructor, method, and field belongs to a class. in our case, we have a class called toast, and ...
JNI.jsm
if you would like to support versions before that, you can copy and paste the contents of the jsm file int jni stands for java native interface; this library allows calling java code running in java virtual machines (jvms), etc. the most common use for this module is in add-ons and other works on firefox for android (fennec). ...
...allows calling java code running in java virtual machines (jvms), etc. the most common use for this module is in add-ons and other works on firefox for android (fennec). with this module, all of the android sdk functions that firefox has permissions for are at your fingertips. a note about firefox for android, this jsm file is already globally imported and is available from the privileged window scope as window.jni. there also exists a jenv variable in the window scope, so if you need to run jni from the global scope, use a different variable name then jenv. jni.jsm contains all the js-ctypes needed to communicate with the jni libraries. the js-ctypes is abstracted away while all the underlying data is all ctype data. functions are declared similar to js-ctypes but in a very different syntax.
Mozilla Framework Based on Templates (MFBT)
ther split up so that its functionality is less grab-bag.) debugging assertions.h provides assertion macros in implementing runtime assertions and compile-time assertions. guardobjects.h provides macros which can be used to annotate an raii-style guard class, so that any attempt to create an unnamed temporary for it will assert. (an unnamed temporary lives for a shorter period of time than the scope where it's found, so it usually isn't what was desired.) data structures linkedlist.h implements a type-safe doubly-linked list class. most new code should use this rather than prclist. rangedptr.h implements rangedptr, a smart pointer template whose value may be manipulated only within a range specified at construction time, and which may be dereferenced only at valid locations in that range.
...gedptr.h implements rangedptr, a smart pointer template whose value may be manipulated only within a range specified at construction time, and which may be dereferenced only at valid locations in that range. this pointer is a useful way to expose access to values within an array. refptr.h implements various smart pointer templates to simplify reference counting of values of particular classes. scoped.h implements scope-based resource management, to simplify the task of cleaning up resources when leaving a scope. threadlocal.h implements thread-local storage, aka "tls", also called thread-specific storage. it should be used only for static-storage-duration variables, such as global variables or static class members. ...
MathML Torture Test
>minion</option> <option value="stixtwo">stix two</option> <option value="texgyrebonum">tex gyre bonum</option> <option value="texgyrepagella">tex gyre pagella</option> <option value="texgyreschola">tex gyre schola</option> <option value="texgyretermes">tex gyre termes</option> <option value="xits">xits</option> </select> <br/> </p> <table> <tr> <td></td> <th scope="col">as rendered by tex</th> <th scope="col">as rendered by your browser</th></tr> <tr> <td>1</td> <td><img src="https://udn.realityripple.com/samples/45/d5a0dbbca3.png" width="38" height="22" alt="texbook, 16.2-16.3" /></td> <td> <math display="block"> <mrow> <msup> <mi>x</mi> <mn>2</mn> </msup> <...
...i></msub></mrow></munder><mrow><mi>ϵ</mi><mo stretchy="false">(</mo><mi>σ</mi><mo stretchy="false">)</mo></mrow><mrow><munderover><mo>∏</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi></munderover><msub><mi>a</mi><mrow><mi>i</mi><mo>,</mo><msub><mi>σ</mi><mi>i</mi></msub></mrow></msub></mrow></mrow></math></td> </tr> </table> <br><br> <table dir="rtl"> <tr> <td></td> <th scope="col">maghreb style</th> <th scope="col">machrek style</th> <th scope="col">persian style</th></tr> <tr> <td>1</td> <td> <math dir="rtl" display="block"> <mrow> <msup> <mi>&#x1ee0e;</mi> <mn>٢</mn> </msup> <msup> <mi>&#x1ee11;</mi> <mn>٢</mn> </msup> </mrow> </ma...
Mozilla DOM Hacking Guide
node) setting up custom prototypes for those dom objects new image(), new option() window.history[index] document.<formname> how to add a new interface to an existing dom object for this section, we will use the simple example of the domimplementation dom object. this is a real-world case that was used to solve bug 33871 (the patch is not checked in yet, as of writing this document)...
...dom level 1 core spec. the requirements include that the global constructor domimplementation be accessible, that the tostring() method called on an instance of a domimplementation return "domimplementation", and that it implements the following methods: hasfeature() (dom1), createdocumenttype() and createdocument() (dom2). what there is to do implement your object in c++. this is not in the scope of this document. the best thing you can do is probably to copy existing code. a dom object is a simple xpcom object with domclassinfo. in our example, the implementation class is nsdomimplementation (in nsdocument.cpp). it implements the nsidomdomimplementation interface (which contains the three methods mentionned above). modify the queryinterface implementation of your xpcom object to include...
Measuring performance using the PerfMeasurement.jsm code module
the perfmeasurement.jsm javascript code module lets you take detailed performance measurements of your code. note: the perfmeasurement.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on. the first thing you need to do is to import the module into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") you can then create a perfmeasurement object. you give the constructor a bit-mask of events you're interested in; see note: at present, perfmeasurement.jsm is only functional on linux, but it is planned to add support for windows (bug 583322) and osx (bug 583323) as well, and we welcome patches for other operating systems. for instance, let's measure instructions executed, cache references, and cache misses...
...sked for as properties: let report = "cpu cycles: " + monitor.cpu_cycles + "\n" + "cache refs: " + monitor.cache_references + "\n" + "cache misses: " + monitor.cache_misses + "\n"; monitor.reset(); alert(report); the reset() method clears all of the enabled counters, as you might expect. when you're done with your measurements, just let the monitor object go out of scope. ...
PR_CreateThread
creates a new thread. syntax #include <prthread.h> prthread* pr_createthread( prthreadtype type, void (*start)(void *arg), void *arg, prthreadpriority priority, prthreadscope scope, prthreadstate state, pruint32 stacksize); parameters pr_createthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread). start a pointer to the thread's root function, which is called as the root of the new thread. returning from this function is the only way to terminate a thread. ...
...system thread (pr_system_thread). start a pointer to the thread's root function, which is called as the root of the new thread. returning from this function is the only way to terminate a thread. arg a pointer to the root function's only parameter. nspr does not assess the type or the validity of the value passed in this parameter. priority the initial priority of the newly created thread. scope specifies your preference for making the thread local (pr_local_thread), global (pr_global_thread) or global bound (pr_global_bound_thread). however, nspr may override this preference if necessary. state specifies whether the thread is joinable (pr_joinable_thread) or unjoinable (pr_unjoinable_thread). stacksize specifies your preference for the size of the stack, in bytes, associated with t...
SpiderMonkey Internals
only jit code really depends on the layout--everything else in the engine interacts with values through functions like val.isdouble(). most parts of the jit also avoid depending directly on the layout: the files punboxassembler.h and nunboxassembler.h are used to generate native code that depends on the value layout. objects consist of a possibly shared structural description, called the map or scope; and unshared property values in a vector, called the slots. each property has an id, either a nonnegative integer or an atom (unique string), with the same tagged-pointer encoding as a jsval. the atom manager consists of a hash table associating strings uniquely with scanner/parser information such as keyword type, index in script or function literal pool, etc. atoms play three roles: as litera...
...on 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 exist) their underlying primitive types. they have similar structure, generally starting with class definitions and continuing with internal constructors, finalizers, and helper functions. jsobj.*, jsscope.* these two pairs declare and implement the js object system. all of the following happen here: creating objects by class and prototype, and finalizing objects; defining, looking up, getting, setting, and deleting properties; creating and destroying properties and binding names to them. the details of a native object's map (scope) are mostly hidden in jsscope.[ch]. jsatom.cpp, jsatom.h ...
JS::CloneFunctionObject
this article covers features introduced in spidermonkey 38 create a new function object from an existing jsfunction. syntax jsobject * js::clonefunctionobject(jscontext *cx, js::handleobject funobj); jsobject * js::clonefunctionobject(jscontext *cx, js::handleobject funobj, js::autoobjectvector &scopechain); 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. funobj js::handleobject the function to clone. scopechain js::autoobjectvector the new function's scope chain. description js::clonefunctionobject creates a new function object from funobj. ...
...nformation. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. funobj js::handleobject the function to clone. scopechain js::autoobjectvector the new function's scope chain. description js::clonefunctionobject creates a new function object from funobj. the new object has the same code and argument list as funobj. if scopechain is supplied, it uses scopechain as its enclosing scope. if scopechain is omitted, it creates a new function object in cx's global. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. the new object's prototype is function.prototype; js_newobject : choosing a default prototype explains exactly how this is computed.
JSAutoByteString
e encode* methods may fail and get null. so ensure the string is returned by operator!() before using ptr() method. examples use constructor arguments { jsstring *str = js::tostring(cx, strval); if (!str) return false; jsautobytestring bytes(cx, str); /* calls js_encodestring internally */ if (!bytes) return false; /* ...do something with bytes... ...
...ytes... */ /* when leaving this scope, the string returned by js_encodestring is freed. */ } use method to encode string { js::rootedstring str(cx, js::tostring(cx, strval)); if (!str) return false; jsautobytestring bytes; if (!bytes.encodeutf8(cx, str)) /* calls js_encodestringtoutf8 internally */ return false; /* ...do something with bytes... */ /* when leaving this scope, the string returned by js_encodestringtoutf8 is freed. */ } take ownership of other buffer { char *buff = cx->pod_malloc<char>(length + 1); if (!buff) return false; memcpy(buff, other_buff, length + 1) jsautobytestring bytes; bytes.initbytes(buff); /* ...do something with bytes... */ /* when leaving this scope, buff is freed. */ } see also mxr id search for jsautobyt...
JSAutoCompartment
syntax jsautocompartment(jscontext *cx, jsobject *target); jsautocompartment(jscontext *cx, jsscript *target); name type description cx jscontext * the context on which a cross-compartment call is needed. target jsobject * / jsscript * the object in a different compartment to be accessed. ...
... description every jscontext has a current compartment. only objects in the current compartment can be accessed, so to access an object in a different compartment, this containing compartment has to be entered first. compartments have to be entered and left in lifo order. ...
JS_ClearNewbornRoots
n the context. these newborn roots help native code protect newly-created gc-things from gc invocations activated before those things can be rooted using local or global roots. however, the newborn roots can also entrain great gobs of garbage, so the js_gc entry point clears them for the context on which gc is being forced. embeddings may need to do likewise for all contexts. ...
...ears them for the context on which gc is being forced. embeddings may need to do likewise for all contexts. see js_enterlocalrootscope for a better way to manage newborns in cases where native hooks (functions, getters, setters, etc.) create many gc-things, potentially without connecting them to predefined local roots such as *rval or argv[i] in an active jsnative function. using js_enterlocalrootscope disables updating of the context's per-gc-thing-type newborn roots, until control flow unwinds and leaves the outermost nesting local root scope. see also bug 572057 bug 659462 ...
JS_EvaluateScript
jsbool js_evaluateucscript(jscontext *cx, jsobject *obj, const jschar *src, unsigned int length, const char *filename, unsigned int lineno, jsval *rval); name type description cx jscontext * the context in which to run the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * 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. ...
...ile 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. 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 scr...
JS_EvaluateScriptForPrincipals
t *obj, jsprincipals *principals, const jschar *chars, unsigned int length, const char *filename, unsigned int lineno, jsval *rval, jsversion version); name type description cx jscontext * the context in which to run the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * the scope in which to execute the script. this parameter is documented in detail at js_executescript. principals 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. ...
... 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 and executes a script in the specified scope, obj. js_evaluateucscriptforprincipals 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...
JS_InitClass
sed as a prototype. js_initclass always creates a new prototype object that serves as the __proto__ for class instances; parent_proto becomes the __proto__ of that prototype object. clasp jsclass * pointer to the class structure to initialize. this structure defines the class for use by other api functions. constructor jsnative the constructor for the class. its scope matches that of the obj argument. if constructor is null, then static_ps and static_fs must also be null. unlike other jsnatives, this function must not call js_this or js_this_object. instead it must create a new object and return it. nargs unsigned number of arguments for the constructor. ps jspropertyspec * either null or a pointer to the first element of ...
...tructor; these are called "static methods" and "static properties" because they serve the same purpose and use the same syntax as static methods and fields in java. on success, js_initclass returns a pointer to a js object that is the prototype for the newly initialized class. if js_initclass fails, it returns null. the constructor for the class is built in the same context as cx, and in the same scope as obj. if you pass null as the constructor parameter, then a constructor is not built, and you cannot specify static properties and functions for the class. note: starting with spidermonkey 1.8, the prototype and constructor are set up with stub getter and setter operations instead of class operations. if you provide a constructor for the class, then you should also pass an object to parent_pr...
JS_SetOptions
the following table: option description jsoption_extra_warnings warn on dubious practice. mxr id search for jsoption_extra_warnings jsoption_werror convert warnings to errors. mxr id search for jsoption_werror 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 things. the former creates a property on the global object. the latter creates a property on obj. with this flag, both create a global property. mxr id search for jsoption_varobjfix ...
...option_private_is_nsisupports mozilla extension. the context's private data points to an xpcom object (see nsisupports). this is only meaningful if spidermonkey is built with xpconnect. mxr id search for jsoption_private_is_nsisupports jsoption_compile_n_go caller of js_compilescript et al promises to execute the compiled script once only, in the same scope object used for compilation. the caller may not modify objects on the scope chain between compilation and execution. this enables compile-time scope chain resolution of consts (a performance optimization). mxr id search for jsoption_compile_n_go jsoption_atline //@line number ["filename"] option supported for the xul preprocessor and kindred beasts. mxr id ...
JS_ValueToObject
he result depends on the object. if v is a native javascript object, this calls the object's valueof method, if any. in any case, the result is not guaranteed to be the same object as v. ...
...s the object's valueof method, if any. in any case, the result is not guaranteed to be the same object as v. ...
Avoiding leaks in JavaScript XPCOM components
roots j. thus j is always reachable from a garbage collection root, and we have a cycle. i actually can't find an example of this simple leak pattern that occurred in mozilla's codebase. but it certainly could. however, it's easy to inadvertently create this same type of leak when using closures. in javascript, as in many interpreted languages, functions have access to the variables that are in scope where they are created. a closure is a code × environment pair: function objects are not just the code; they're also the environment. since all the variables in that environment are reachable from the function object, the objects referenced by those variables are reachable from the function. to understand closures a little better before examining how they can cause leaks, consider the following...
...ldren = radiochildren; in this example, the iterator object is an xpcom object that is wrapped so the javascript code can use it. the _filterradiogroup object is a javascript function that is wrapped so that xpcom code can use it. the reason closures matter here is that the _filterradiogroup function has access to the iterator variable. (var declarations inside javascript functions are function-scope, including the part of the function before the declaration.) this means that the value of iterator, the wrapper for the native tree walker, is reachable from the function. but the tree walker owns a reference to the wrapper for that function, so the wrapper maintains a garbage collection root to keep the function from being destroyed, so we have a cycle that prevents both objects from being freed...
Mozilla internal string guide
rn value if the nsresult indicates failure. unfortunately mozilla::result is not versatile enough to be used here.) bulkwrite() returns a mozilla::bulkwritehandle<t>, where t is either char or char16_t. the actual writes are performed through this handle. you must not access the string except via the handle until you call finish() on the handle in the success case or you let the handle go out of scope without calling finish() in the failure case, in which case the destructor of the handle puts the string in a mostly harmless but consistent state (containing a single replacement character if a capacity greater than 0 was requested, or in the char case if the three-byte utf-8 representation of the replacement character doesn't fit, an ascii substitute). mozilla::bulkwritehandle<t> autoconverts ...
...); 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) 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"); t...
Components.utils.Sandbox
ll components.utils.sandbox: var sandbox = components.utils.sandbox(principal[, options]); using new components.utils.sandbox(...) to create a sandbox has the same effect as calling sandbox(...) without new. the created sandbox is simply an empty javascript object marked as having been created by the restricted privilege principal. you can then use it with evalinsandbox() to make it the global scope object for the specified script. principal the security principal defined for a sandbox determines what code running in that sandbox will be allowed to do. the principal may be one of four types: the system principal, a content principal, an expanded principal, or a null principal. see security checks for more information on security principals. system principal to specify the system princip...
...remaining references to the sandbox or the code it contains. however, in some cases it can be difficult to remove all references. for example, the code in the sandbox might be a third-party library that sets expando properties or adds event listeners to a window. in this case, components.utils.nukesandbox can be used to force the sandbox to be freed immediately. example executing in current tab scope more ways to load scripts into a sandbox can be found on the loading scripts page. this example is to be run from scratchpad with environemnt set to browser. it alerts the dollar sign function. this code was tested on twitter.com and gets access to the jquery $. var sandboxscript = 'alert($)'; var options = { sandboxprototype: content, wantxrays: false // only set this to false if you ...
Components.utils.evalInSandbox
on json. you can also find firefox 3.5 specific information in using json in firefox. use to use evalinsandbox(), you must first create a sandbox object using its constructor, components.utils.sandbox. in the constructor you define the security principal for code running in the sandbox, and can make various properties available to code running in the sandbox. the sandbox will become the global scope object when you pass it to evalinsandbox(text, sandbox). you can import functions or objects into the sandbox simply by assigning them to the sandbox object. for example: function double(n) { return n * 2; } // create new sandbox instance var mysandbox = new components.utils.sandbox("http://www.example.com/"); mysandbox.y = 5; // insert property 'y' with value 5 into global scope. mysandb...
...ance var mysandbox = new components.utils.sandbox("http://www.example.com/"); mysandbox.y = 5; // insert property 'y' 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...
Components object
manager results array of known result codes by name returncode pending result for current call stack current javascript call stack utils provides access to several useful features utils.atline provides access to the value of the atline property in the javascript environment. utils.createobjectin creates a new object in the scope of the specified object's compartment. may only be called from javascript code. utils.evalinsandbox runs javascript code in a sandbox, usually used to run code with restricted privileges. utils.forcegc forces a garbage collection cycle. utils.getglobalforobject returns the global object with which a given object is associated (through its prototyp...
...forcegc forces a garbage collection cycle. utils.getglobalforobject returns the global object with which a given object is associated (through its prototype chain at birth, for example). utils.getweakreference gets a weak reference for the object passed in. utils.import loads a javascript module into the current script, without sharing a scope. utils.lookupmethod looks up a native (i.e. declared in the interface) method or property of an xpcom object. serves the same purpose as xpcnativewrapper. utils.makeobjectpropsnormal ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. may only be called from javascript code. utils.methodjit obsole...
IAccessibleText
. lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed. servers should document their life cycle strategy as this will be of interest to assistive technology or script engines accessing data out of process or from other threads. servers only need to save the last inserted block of text() and a scope of the entire application is adequate. [propget] hresult newtext( [out] ia2textsegment newtext ); parameters newtext the text() that was just inserted. return value s_false if there is nothing to return, [out] value is null. s_ok. nselections() returns the number of active non-contiguous selections. [propget] hresult nselections( [out] long nselections ); parameters nselections missing d...
...n. lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed. servers should document their life cycle strategy as this will be of interest to assistive technology or script engines accessing data out of process or from other threads. servers only need to save the last removed block of text() and a scope of the entire application is adequate. [propget] hresult oldtext( [out] ia2textsegment oldtext ); parameters oldtext the text() that was just removed. return value s_false if there is nothing to return, [out] value is null. s_ok. removeselection() unselects a range of text(). hresult removeselection( [in] long selectionindex ); parameters selectionindex index of selection() to remove (0 ...
nsIAbstractWorker
used to implement the web workers architecture. ...
...e web workers architecture. ...
nsIMsgIncomingServer
overridden to be false. if isps want to modify this value, they should do that in their rdf file by using this attribute. please look at mozilla/mailnews/base/ispdata/aol.rdf for usage example. displaystartuppage boolean dobiff boolean downloadmessagesatstartup boolean read only. downloadonbiff boolean downloadsettings nsimsgdownloadsettings emptytrashonexit boolean filterscope nsmsgsearchscopevalue read only. hostname acstring hostname of the server. incomingduplicateaction long isdeferredto boolean read only. issecure boolean issecureserver boolean read only. key acstring internal pref key - guaranteed to be unique across all servers. limitofflinemessagesize boolean localpath nsilocalfile localstoretype acstring the schema for the local mail ...
...t set. realhostname acstring real hostname of the server (if server name is changed it is stored here) realusername acstring real username of the server (if username is changed it is stored here) redirectortype string obsolete since gecko 1.9 rememberpassword boolean retentionsettings nsimsgretentionsettings rootfolder nsimsgfolder rootmsgfolder nsimsgfolder read only. searchscope nsmsgsearchscopevalue read only. serverbusy boolean serverrequirespasswordforbiff boolean read only. serveruri acstring read only. sockettype long spamfilterplugin nsimsgfilterplugin read only. spamsettings nsispamsettings spam settings. read only. supportsdiskspace boolean read only. type acstring protocol type, that is "pop3", "imap", "nntp", "none", and so on. used to constr...
nsIWorkerMessageEvent
; parameters atypearg the event type. ...
... atypearg the event type. acanbubblearg whether or not the event can bubble. ...
Mozilla
e) are much slower. any performance metrics gathered by such builds are largely unrelated to what would be found in a release browser. browser chrome tests the browser chrome test suite is an automated testing framework designed to allow testing of application chrome windows using javascript. it currently allows you to run javascript code in the same scope as the main firefox browser window and report results using the same functions as the mochitest test framework. as all tests, they won't work in a build with tests disabled (--disable-tests). browser security an important aspect of developing code for any browser, including firefox, as well as any web-oriented project, is its security. th...
...process communication) protocol definition language", is a mozilla-specific language allowing c++ code to pass messages between processes or threads in an organized and secure way. all messages for multi-process plugins and tabs in firefox are declared in the ipdl language. javascript code modules javascript code modules let multiple privileged javascript scopes share code. for example, a module could be used by firefox itself as well as by extensions, in order to avoid code duplication. javascript libraries from mozilla projects in addition to firefox and other applications, mozilla developers have created a number of useful javascript libraries you can use in your projects. documentation for these libraries can be found here. ...
Browser Console - Firefox Developer Tools
on for a single content tab, it logs information for all content tabs, for add-ons, and for the browser's own code. if you also want to use the other web developer tools in the regular web toolbox with add-on or browser code, consider using the browser toolbox. similarly, you can execute javascript expressions using the browser console. but while the web console executes code in the page window scope, the browser console executes them in the scope of the browser's chrome window. this means you can interact with all the browser's tabs using the gbrowser global, and even with the xul used to specify the browser's user interface. nb: the browser console command line (to execute javascript expressions) is disabled by default. to enable it set the devtools.chrome.enabled preference to true in ab...
... the web console, the command line interpreter enables you to evaluate javascript expressions in real time:also like the web console's command line interpreter, this command line supports autocomplete, history, and various keyboard shortcuts and helper commands. if the result of a command is an object, you can click on the object to see its details. but while the web console executes code in the scope of the content window it's attached to, the browser console executes code in the scope of the chrome window of the browser. you can confirm this by evaluating window: this means you can control the browser: opening, closing tabs and windows and changing the content that they host, and modify the browser's ui by creating, changing and removing xul elements. controlling the browser the command...
Use watchpoints - Firefox Developer Tools
breakpoint at a particular line, you can discover where that access occurs. there are three types of watchpoints: get, set, and get or set. a get watchpoint pauses whenever a property is read; a set watchpoint pauses whenever a property value changes; a get or set watchpoint pauses whenever a property value is accessed in either way. set a watchpoint run and then pause the debugger. in the scopes pane on the right side of the debugger user interface, find an object you want to watch, and right-click it to open its context menu. choose break on, and then one of property set property get property get or set a watchpoint icon appears to the right of the property in the scopes pane. set watchpoint icons are blue, get watchpoint icons are reddish, and get or set watchpoin...
... click the watchpoint icon, or right-click and choose remove watchpoint. the watchpoint is removed. ...
Debugger.Memory - Firefox Developer Tools
debugger instance, then the methods and accessor properties of dbg.memory control howdbg observes its debuggees’ memory use. the dbg.memory object is an instance of debugger.memory; its inherited accesors and methods are described below. allocation site tracking the javascript engine marks each new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a debuggee of some debugger instancedbg; and dbg.memory.trackingallocationsites is set to true. a bernoulli trial succeeds, with probability equal to the maximum of d.memory.allocationsamplingprobability of all debugger instances d that are observing the global that this object is allocated within the scope of. given a debugger.object instancedobj referr...
...ngprobability 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”. the default is 1, or logging every allocation. note that in the presence of multiple debugger instances observing the same allocations within a global’s scope, the maximum allocationsamplingprobability of all the debuggers is used. maxallocationsloglength the maximum number of allocation sites to accumulate in the allocations log at a time. this accessor can be both fetched and stored to. its default value is 5000. allocationslogoverflowed returns true if there have been more than [maxallocationsloglength][#max-alloc-log] allocations since the la...
Debugger.Script - Firefox Developer Tools
instance refers to webassembly code, throw a typeerror. 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 typeerror. 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 global directly, not via a wrapper or a windowproxy (“outer window”, in firefox). if the instance refers to webassembly code, throw a typeerror. format if the instance refers to a jsscript, "js". if the instance refers to webassembly code, "wasm". function properties of the debugger.script prototype object the functions described below...
...r. note that, if breakpoints using other handler objects are set at the same location(s) ashandler, they remain in place. clearallbreakpoints([offset]) if the instance refers to a jsscript, remove all breakpoints set in this script. ifoffset is present, remove all breakpoints set at that offset in this script; ifoffset is not a valid bytecode offset in this script, throw an error. isincatchscope([offset]) if the instance refers to a jsscript, this is true if this offset falls within the scope of a try block, and false otherwise. if the instance refers to webassembly code, throw a typeerror. source metadata generated from file: js/src/doc/debugger/debugger.script.md watermark: sha256:8816a4e8617be32c4ce7f3ae54970fe9c8a7d248175d215a8990ccff23e6efa9 changeset: 5572465c08...
Index - Firefox Developer Tools
, and so on. 18 debugger when called as a constructor, the debugger object creates a new debugger instance. 19 debugger.environment a debugger.environment instance represents a lexical environment, associating names with variables. each debugger.frame instance representing a debuggee frame has an associated environment object describing the variables in scope in that frame; and each debugger.object instance representing a debuggee function has an environment object representing the environment the function has closed over. 20 debugger.frame a debugger.frame instance represents a visible stack frame. given a debugger.frame instance, you can find the script the frame is executing, walk the stack to older frames, find the lexical en...
... 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 article is a quick tour of the main sections of the javascript debugger's user interface. the ui is split vertically into three panels 139 using the debugger map scopes feature this feature is useful when debugging source-mapped code. it enables you to see the variables from the original source. it’s also possible to inspect variables from the generated scopes (e.g., a bundle file with all concatenated module files). 140 the web developer menu add-ons, debugging, tools, web developer the web developer menu is the main way to ac...
The JavaScript input interpreter - Firefox Developer Tools
lete the editor has autocomplete: enter the first few letters and a popup appears with possible completions: press enter, tab, or the right arrow key to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don't like any of the suggestions. console autocomplete suggestions are case-insensitive. the console suggests completions from the scope of the currently executing stack frame. this means that if you've hit a breakpoint in a function you get autocomplete for objects local to the function. you get autocomplete suggestions for array elements, as well: you can enable or disable autocompletion via the settings ("gear") menu in the web console toolbar. the menuitem enable autocompletion has a checkmark next to it when the feature i...
...tiated the reverse search, you can use shift + f9 on windows or linux ( ctrl+s on mac) to search forward in the list of matches. you can also use the ⋀ and ⋁ icons in the expression search bar. when you find the expression you want, press enter (return) to execute the statement. working with iframes if a page contains embedded iframes, you can use the cd() function to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. there are three ways to select an iframe using cd(): you can pass the iframe dom element: var frame = document.getelementbyid("frame1"); cd(frame); you can pass a css selector that matches the iframe: cd("#frame1"); you can pass the iframe's global window object: var frame = document.gete...
AbsoluteOrientationSensor - Web APIs
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. ...
...rs 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([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "magnetometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ... } else { console.log("no permissions to use absoluteorientationsensor."); } }); specifications specification status comment generic sensor api candidate recommendation defines sensors in genera...
AnalyserNode.fftSize - Web APIs
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 indexsizeerror is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount ; var dataarray = new uint...
...ation, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... ...
AnalyserNode.getByteTimeDomainData() - Web APIs
ill be copied to. if the array has fewer elements than the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. return value void | none 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). const audioctx = new (window.audiocontext || window.webkitaudiocontext)(); const analyser = audioctx.createanalyser(); ... analyser.fftsize = 2048; const bufferlength = analyser.fftsize; const dataarray = new uint8ar...
...ormation, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). const audioctx = new (window.audiocontext || window.webkitaudiocontext)(); const analyser = audioctx.createanalyser(); ... ...
AudioWorkletProcessor - Web APIs
in turn, an audioworkletnode based on it runs on the main thread. constructor the audioworkletprocessor and classes that derive from it cannot be instantiated directly from a user-supplied code. instead, they are created only internally by the creation of an associated audioworkletnodes. ...
...assed into the process() method of the processor for you to shape the node output accordingly. processing audio an example algorithm of creating a custom audio processing mechanism is: create a separate file; in the file: extend the audioworkletprocessor class (see "deriving classes" section) and supply your own process() method in it; register the processor using audioworkletglobalscope.registerprocessor() method; load the file using addmodule() method on your audio context's audioworklet property; create an audioworkletnode based on the processor. the processor will be instantiated internally by the audioworkletnode constructor. connect the node to the other nodes. examples in the example below we create a custom audioworkletnode that outputs white noise. first, we ...
BaseAudioContext.createAnalyser() - Web APIs
time and frequency data and create data visualisations. note: for more on using this node, see the analysernode page. syntax var analysernode = baseaudiocontext.createanalyser(); returns an analysernode. example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() 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 audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8...
...mation, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... ...
Cache - Web APIs
Web › API › Cache
you don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. an origin can have multiple, named cache objects. you are responsible for implementing how your script (e.g. in a serviceworker) handles cache updates. ...
...ippet also shows a best practice for versioning caches used by the service worker. though there's only one cache in this example, the same approach can be used for multiple caches. it maps a shorthand identifier for a cache to a specific, versioned cache name. the code also deletes all caches that aren't named in current_caches. in the code example, caches is a property of the serviceworkerglobalscope. it holds the cachestorage object, by which it can access the cachestorage interface. this is an implementation of the windoworworkerglobalscope mixin. note: in chrome, visit chrome://inspect/#service-workers and click on the "inspect" link below the registered service worker to view logging statements for the various actions the service-worker.js script is performing. var cache_version = 1; va...
Clients.claim() - Web APIs
Web › API › Clients › claim
this triggers a "controllerchange" event on navigator.serviceworker in any clients that become controlled by this service worker. when a service worker is initially registered, pages won't use it until they next load. the claim() method causes those pages to be controlled immediately. be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. ...
...immediately. be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. return value a promise that resolves to undefined. example the following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker. self.addeventlistener('activate', event => { event.waituntil(clients.claim()); }); specifications specification status comment service workersthe definition of 'claim()' in that specification. working draft initial definition. ...
console - Web APIs
Web › API › Console
it's exposed as window.console, and can be referenced as simply console. ...
...it's exposed as window.console, and can be referenced as simply console. ...
ContentIndex.add() - Web APIs
Web › API › ContentIndex › add
ontaining the following data: id: a unique string identifier. title: a string title for the item. used in user-visible lists of content. title: a string title of the item. used in user-visible lists of content. description: a string description of the item. used in user-visible lists of content. url: a string containing the url of the corresponding html document. needs to be under the scope of the current service worker. category: optional a string defining the category of content. can be: '' an empty string, this is the default. homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image. sizes: optional a string representation of the imag...
...dexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } the add method can also be used within the service worker scope. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; self.registration.index.add(item); specifications specification s...
Element - Web APIs
Web › API › Element
y to webextensions. element.slot returns the name of the shadow dom slot the element is inserted in. element.tabstop is a boolean indicating if the element can receive input focus via the tab key. element.tagname read only returns a string with the name of the tag for the given element. element.undomanager read only returns the undomanager associated with the element. element.undoscope is a boolean indicating if the element is an undo scope host, or not. note: dom level 3 defined namespaceuri, localname and prefix on the node interface. in dom4 they were moved to element. this change is implemented in chrome since version 46.0 and firefox since version 48.0. properties included from slotable the element interface includes the following property, defined on the slotabl...
...pecifications specification status comment css pseudo-elements level 4the definition of 'element' in that specification. working draft added the pseudo() method. web animations working draft added the getanimations() method. undomanager and domtransactionthe definition of 'element' in that specification. editor's draft added the undoscope and undomanager properties. pointer events – level 2the definition of 'element' in that specification. recommendation added the following event handlers: ongotpointercapture and onlostpointercapture. added the following methods: setpointercapture() and releasepointercapture(). pointer eventsthe definition of 'element' in that specification. obsolete added the f...
Fetch API - Web APIs
Web › API › Fetch API
quests and responses, or any kind of use case that might require you to generate your responses programmatically (that is, the use of computer program or personal programming instructions). it also defines related concepts such as cors and the http origin header semantics, supplanting their separate definitions elsewhere. for making a request and fetching a resource, use the windoworworkerglobalscope.fetch() method. it is implemented in multiple interfaces, specifically window and workerglobalscope. this makes it available in pretty much any context you might want to fetch resources in. the fetch() method takes one mandatory argument, the path to the resource you want to fetch. it returns a promise that resolves to the response to that request, whether it is successful or not. you can also o...
...the fetch api features in using fetch, and study concepts in fetch basic concepts. aborting a fetch browsers have started to add experimental support for the abortcontroller and abortsignal interfaces (aka the abort api), which allow operations like fetch and xhr to be aborted if they have not already completed. see the interface pages for more details. fetch interfaces windoworworkerglobalscope.fetch() the fetch() method used to fetch a resource. headers represents response/request headers, allowing you to query them and take different actions depending on the results. request represents a resource request. response represents the response to a request. fetch mixin body provides methods relating to the body of the response/request, allowing you to declare what its content t...
HTMLElement - Web APIs
the given node is absent for the purposes of user interaction events, in-page text searches ("find in page"), and text selection. htmlelement.innertext represents the "rendered" text content of a node and its descendants. as a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard. htmlelement.itemscope is a boolean representing the item scope. htmlelement.itemtype read only returns a domsettabletokenlist… htmlelement.itemid is a domstring representing the item id. htmlelement.itemref read only returns a domsettabletokenlist… htmlelement.itemprop read only returns a domsettabletokenlist… htmlelement.itemvalue returns a object representing the item value. htmlelement...
...n status comment css object model (cssom) view modulethe definition of 'htmlelement' in that specification. working draft added the following properties: offsetparent, offsettop, offsetleft, offsetwidth, and offsetheight. html living standardthe definition of 'htmlelement' in that specification. living standard added the following properties: translate, itemscope, itemtype, itemid, itemref, itemprop, properties, and itemvalue. added the following method: forcespellcheck(). moved the onxyz attributes to the globaleventhandlers interface and added an inheritance from it. html5the definition of 'htmlelement' in that specification. recommendation added the following properties: dataset, hidden, tabindex, accesskey, accesskeylabel, dragg...
HTMLStyleElement - Web APIs
tion medium for style information. htmlstyleelement.type is a domstring representing the type of style being applied by this statement. htmlstyleelement.disabled is a boolean value representing whether or not the stylesheet is disabled (true) or not (false). linkstyle.sheet read only returns the stylesheet object associated with the given element, or null if there is none htmlstyleelement.scoped is a boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true). methods no specific method; inherits properties from its parent, htmlelement, and linkstyle. specifications specification status comment html living standardthe definition of 'htmlstyleelement' in that specification. living standard ...
...cations specification status comment html living standardthe definition of 'htmlstyleelement' in that specification. living standard html 5.1the definition of 'htmlstyleelement' in that specification. recommendation html5the definition of 'htmlstyleelement' in that specification. recommendation the following property has been added: scoped. document object model (dom) level 2 html specificationthe definition of 'htmlstyleelement' in that specification. obsolete added a second inheritence, the linkstyle interface. document object model (dom) level 1 specificationthe definition of 'htmlstyleelement' in that specification. obsolete initial definition ...
IDBTransaction.objectStore() - Web APIs
every call to this method on the same transaction object, with the same name, returns the same idbobjectstore instance. if this method is called on a different transaction object, a different idbobjectstore instance is returned. 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. ...
...lable 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 notfounderror the requested object store is not in this transaction's scope. invalidstateerror the request was made on a source object that has been deleted or removed, or if the transaction has finished. example in the following code snippet, we open a read/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 ev...
IDBTransaction - Web APIs
transaction.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 transaction. 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, thi...
...ctstore 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 made. commit() can be used to start the commit process without waiting for events from outstanding requests to be dispatched. ...
IDBTransactionSync - Web APIs
en this method is called, the browser durably stores all the changes performed to the objects of the database since this transaction was created. void commit( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if this transaction has already been committed or aborted. recoverable_err if this transaction's scope is dynamic, and the browser cannot commit all of the changes due to another transaction. objectstore() returns an object store that has already been added to the scope of this transaction. idbobjectstoresync objectstore( in domstring name ) raises (idbdatabaseexception); parameters name the name of the requested object store. returns idbobjectstoresync an object for accessing th...
...tion. idbobjectstoresync objectstore( in domstring name ) raises (idbdatabaseexception); parameters name the name of the requested object store. returns idbobjectstoresync an object for accessing the requested object store. exceptions the method can raise an idbdatabaseexception with the following code: not_found_err if the requested object store is not in this transaction's scope. ...
InstallEvent - Web APIs
as a child of extendableevent, it ensures that functional events such as fetchevent are not dispatched during installation. this interface inherits from the extendableevent interface. ...
...ect. properties inherits properties from its ancestor, event. installevent.activeworker read only returns the serviceworker that is currently controlling the page. methods inherits methods from its parent, extendableevent. examples this code snippet is from the service worker prefetch sample (see prefetch running live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall and delays treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully. the promise resolves when all resources have been fetched and cached, or when any exception occurs. the code snippet also shows a best practice for versioning caches used by the service worker. although this example has only one cache, you can use this approa...
MessageEvent - Web APIs
server-sent events (see eventsource.onmessage). web sockets (see the onmessage property of the websocket interface). cross-document messaging (see window.postmessage() and window.onmessage). channel messaging (see messageport.postmessage() and messageport.onmessage). cross-worker/document messaging (see the above two entries, but also worker.postmessage(), worker.onmessage, serviceworkerglobalscope.onmessage, etc.) broadcast channels (see broadcastchannel.postmessage()) and broadcastchannel.onmessage). webrtc data channels (see rtcdatachannel.onmessage). the action triggered by this event is defined in a function set as the event handler for the relevant message event (e.g. using an onmessage handler as listed above). note: this feature is available in web workers. <div id="interf...
...the ports associated with that worker are accessible in the connect event's ports property — we then use messageport start() method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.addeventlistener('message', function(e) { v...
NotificationEvent - Web APIs
this interface inherits from the extendableevent interface. constructor notificationevent() creates a new notificationevent object. properties inherits properties from its ancestor, event. notificationevent.notification read only returns a notification object representing the notification that was clicked to fire the event. ...
... client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment notifications apithe definition of 'notificationevent' in that specification. living standard living standard. note: this interface is specified in the notifications api, but accessed through serviceworkerglobalscope. 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 iossamsung internetnotificationev...
Performance API - Web APIs
conds). however, if the browser is unable to provide a time value accurate to 5 microseconds (because, for example, due to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond. methods the performance interface has two methods. the now() method returns a domhighrestimestamp whose value that depends on the navigation start and scope. if the scope is a window, the value is the time the browser context was created and if the scope is a worker, the value is the time the worker was created. the tojson() method returns a serialization of the performance object, for those attributes that can be serialized. properties the performance interface has two properties. the timing property returns a performancetiming object containing ...
...urcetiming provides methods and properties for retrieving and analyzing detailed network timing data regarding the loading of an application's resources. specifications specification status comment high resolution time recommendation initial definition. high resolution time level 2 recommendation adds performance attribute on window and workerglobalscope. high resolution time level 3 editor's draft add timeorigin property to performance interface. frame timing draft adds performanceframetiming interface. navigation timing recommendation adds the performancetiming and performancenavigation interfaces. adds timing and navigation properties to the performance interface. navigation timing level 2 ...
RelativeOrientationSensor - Web APIs
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. ...
... } }); 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([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ... } else { console.log("no permissions to use relativeorientationsensor."); } }); specifications specification status comment orientation sensorthe definition of 'relativeorientationsensor' in that spe...
Request - Web APIs
Web › API › Request
est() constructor (for an image file in the same directory as the script), then return some property values of the request: const request = new request('https://www.mozilla.org/favicon.ico'); const url = request.url; const method = request.method; const credentials = request.credentials; you could then fetch this request by passing the request object in as a parameter to a windoworworkerglobalscope.fetch() call, for example: fetch(request) .then(response => response.blob()) .then(blob => { image.src = url.createobjecturl(blob); }); in the following snippet, we create a new request using the request() constructor with some initial data and body content for an api request which need a body payload: const request = new request('https://example.com', {method: 'post', body: '{"foo":...
...equest.method; const credentials = request.credentials; const bodyused = request.bodyused; note: the body type can only be a blob, buffersource, formdata, urlsearchparams, usvstring or 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 sta...
ServiceWorkerContainer - Web APIs
curs 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 updates a serviceworkerregistration for the given scripturl. serviceworkercontainer.getregistration() gets a serviceworkerregistration object whose scope matches the provided document url. the method returns a promise that resolves to a serviceworkerregistration or undefined. serviceworkercontainer.getregistrations() returns all serviceworkerregistration objects associated with a serviceworkercontainer in an array. the method returns a promise that resolves to an array of serviceworkerregistration. serviceworkercontainer.startmessages() ex...
...ce workers. if supported, the code registers the service worker and determines if the page is actively controlled by the service worker. if it isn't, it prompts the user to reload the page so the service worker can take control. the code also reports any registration failures. 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); // 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 re...
onnotificationclose - Web APIs
the serviceworkerglobalscope.onnotificationclose property is an event handler called whenever the notificationclose event is dispatched on the serviceworkerglobalscope object, that is when a user closes a displayed notification spawned by serviceworkerregistration.shownotification(). 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) { ... })...
... ...
ServiceWorkerRegistration.unregister() - Web APIs
the unregister() method of the serviceworkerregistration interface unregisters the service worker registration and returns a promise. the promise will resolve to false if no registration was found, otherwise it resolves to true irrespective of whether unregistration happened or not (it may not unregister if someone else just called serviceworkercontainer.register() with the same scope.) the service worker will finish any ongoing operations before it is unregistered. note: this feature is available in web workers. syntax serviceworkerregistration.unregister().then(function(boolean) { }); parameters none. return value promise resolves with a boolean indicating whether the service worker has unregistered or not. example the following simple example registers a service worker example, b...
...eworkerregistration.unregister().then(function(boolean) { }); parameters none. return value promise resolves with a boolean indicating whether the service worker has unregistered or not. ...
ServiceWorkerRegistration - Web APIs
egistration is beyond that of the serviceworkerregistration objects that represent them within the lifetime of their corresponding service worker clients. the browser maintains a persistent list of active serviceworkerregistration objects. note: this feature is available in web workers. properties also implements properties from its parent interface, eventtarget. serviceworkerregistration.scope read only returns a unique identifier for a service worker registration. this must be on the same origin as the document that registers the serviceworker. serviceworkerregistration.installing read only returns a service worker whose state is installing. this is initially set to null. serviceworkerregistration.waiting read only returns a service worker whose state is installed. this is ini...
...e state is installing. this is initially set to null. serviceworkerregistration.waiting read only returns a service worker whose state is installed. this is initially set to null. serviceworkerregistration.active read only returns a service worker whose state is activated. this is initially set to null. an active worker will control a serviceworkerclient if the client's url falls within the scope of the registration (the scope option set when serviceworkercontainer.register is first called.) serviceworkerregistration.navigationpreload read only returns the instance of navigationpreloadmanager associated with the current service worker registration. serviceworkerregistration.pushmanager read only returns a reference to the pushmanager interface for managing push subscriptions includi...
SharedWorker() - Web APIs
onkey 2.7) and later accept data uris, that's not the case in all other browsers. syntax var myworker = new sharedworker(aurl, name); var myworker = new sharedworker(aurl, options); parameters aurl a domstring representing the url of the script the worker will execute. it must obey the same-origin policy. name optional a domstring specifying an identifying name for the sharedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. options optional an object containing option properties that can set when creating the object instance. available properties are as follows: type: a domstring specifying the type of worker to create. the value can be classic or module. if not specified, the default used is classic. credentials: a domstrin...
...er to create. the value can be classic or module. if not specified, the default used is classic. credentials: a domstring specifying the type of credentials to use for the worker. the value can be omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring specifying an identifying name for the sharedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. return value the created worker. exceptions a securityerror is raised if the document is not allowed to start workers, for example if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be...
WebGL best practices - Web APIs
n shaders, and you need it to have 32-bits, you must use highp or you will have portability problems. ...
... while you can use mediump float instead, but be aware that this often results in corrupted r...
Visualizations with Web Audio API - Web APIs
y, we then call the data collection method we want, with the array passed as it's argument. for example: analyser.getbytetimedomaindata(dataarray); we now have the audio data for that moment in time captured in our array, and can proceed to visualize it however we like, for example by plotting it onto an html5 <canvas>. let's go on to look at some specific examples. ...
...lection method we want, with the array passed as it's argument. for example: analyser.getbytetimedomaindata(dataarray); we now have the audio data for that moment in time captured in our array, and can proceed to visualize it however we like, for example by plotting it onto an html5 <canvas>. let's go on to look at some specific examples. ...
Web Audio API - Web APIs
udioworklet, and lets you add modules to the audio worklet to be executed off the main thread. audioworkletnode the audioworkletnode interface represents an audionode that is embedded into an audio graph and can pass messages to the corresponding audioworkletprocessor. ...
...rface represents an audionode that is embedded into an audio graph and can pass messages to the corresponding audioworkletprocessor. audioworkletprocessor the audioworkletprocessor interface represents audio processing code running in a audioworkletglobalscope that generates, processes, or analyses audio directly, and can pass messages to the corresponding audioworkletnode. audioworkletglobalscope the audioworkletglobalscope interface is a workletglobalscope-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using javascript in a worklet thread rather than on the main thread. obsolete: script processor nodes before audio worklets were defined, the web audio a...
Worker - Web APIs
Web › API › Worker
rom abstractworker. event handlers abstractworker.onerror 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. ...
... 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. ...
Variable fonts guide - CSS: Cascading Style Sheets
uently encountered, and common enough that the authors of the specification felt it was worth standardizing. the five currently registered axes are weight, width, slant, italic, and optical size. the w3c has undertaken mapping them to existing css attributes, and in one case introduced a new one, which you'll see below. custom axes are in fact limitless: the typeface designer can define and scope any axis they like, and are just required to give it a four-letter tag to identify it within the font file format itself. you can use these four-letter tags in css to specify a point along that axis of variation, as will be show in the code examples below. registered axes and existing css attributes in this section we'll demonstrate the five registered axes defined with examples and the corr...
...rom attempting to render an axis outside that range if you are using the appropriate attribute (i.e. font-weight or font-stretch), but will not block you from supplying an invalid value via font-variation-settings, so use with care. working with older browsers variable font support can be checked with css feature queries (see @supports), so it's possible to use variable fonts in production and scope the css calling the variable fonts inside a feature query block. h1 { font-family: some-non-variable-font-family; } @supports (font-variation-settings: 'wdth' 115) { h1 { font-family: some-variable-font-family; } } sample pages the following example pages show two different ways to structure your css. the first uses the standard attributes wherever possible. the second example uses css...
Pseudo-classes - CSS: Cascading Style Sheets
html living standard living standard defines when particular selectors match html elements. selectors level 4 working draft defined :any-link, :blank...
...arget :target-within :user-invalid :valid :visited :where() specifications specification status comment fullscreen api living standard defined :fullscreen. html living standard living standard defines when particular selectors match html elements. selectors level 4 working draft defined :any-link, :blank, :local-link, :scope, :drop, :current, :past, :future, :placeholder-shown, :user-invalid, :nth-col(), :nth-last-col(), :is() and :where(). changed :empty to behave like :-moz-only-whitespace . no significant change for other pseudo-classes defined in selectors level 3 and html5 (though semantic meaning not taken over). html5 recommendation copies the relevant section from the canonical (whatwg...
Content categories - Developer guides
categories, which describe common rules shared by many elements. form-related content categories, which describe rules common to form-related elements. specific content categories, which describe rare categories shared only by a few elements, sometimes only in a specific context. note: a more detailed discussion of these content categories and their comparative functionalities is beyond the scope of this article; for that, you may wish to read the relevant portions of the html specification. main content categories metadata content elements belonging to the metadata content category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other out of band information. elements belonging to this category are <base>, <command>,...
...tion>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <svg>, <table>, <template>, <textarea>, <time>, <ul>, <var>, <video>, <wbr> and text. a few other elements belong to this category, but only if a specific condition is fulfilled: <area>, if it is a descendant of a <map> element <link>, if the itemprop attribute is present <meta>, if the itemprop attribute is present <style>, if the scoped attribute is present sectioning content elements belonging to the sectioning content model create a section in the current outline that defines the scope of <header> elements, <footer> elements, and heading content. elements belonging to this category are <article>, <aside>, <nav> and <section>. do not confuse this content model with the sectioning root category, which isolates its content...
HTML attribute reference - HTML: Hypertext Markup Language
r the list should be displayed in a descending order instead of a ascending. rows <textarea> defines the number of rows in a text area. rowspan <td>, <th> defines the number of rows a table cell should span over. sandbox <iframe> stops a document loaded in an iframe from using certain features (such as submitting forms or opening new windows). scope <th> defines the cells that the header test (defined in the th element) relates to. scoped <style> selected <option> defines a value which will be selected on page load. shape <a>, <area> size <input>, <select> defines the width of the element (in pixels). if the element's type attribute is text or password then it's the number o...
...s restrictions on the allowed values of boolean attributes: if the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ascii case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace. the following examples are valid ways to mark up a boolean attribute: <div itemscope> this is valid html but invalid xml. </div> <div itemscope=itemscope> this is also valid html but invalid xml. </div> <div itemscope=""> this is valid html and also valid xml. </div> <div itemscope="itemscope"> this is also valid html and xml, but perhaps a bit verbose. </div> to be clear, the values "true" and "false" are not allowed on boolean attributes. to represent a false value, the attrib...
<dfn>: The Definition element - HTML: Hypertext Markup Language
Web › HTML › Element › dfn
<a> with the href attribute set to "#definition-dfn" to set up the link back to the definition. result the resulting content looks like this: using abbreviations and definitions together in some cases, you may wish to use an abbreviation for a term when defining it. ...
...this can be done by using the <dfn> and <abbr> elements in tandem, like this: html <p>the <dfn><abbr title="hubble space telescope">hst</abbr></dfn> is among the most productive scientific instruments ever constructed. it has been in orbit for over 20 years, scanning the sky and returning data and photographs of unprecedented quality and detail.</p> <p>indeed, the <abbr title="hubble space telescope">hst</abbr> has arguably done more to advance science than any device ever built.</p> note the <abbr> element nested inside the <dfn>. the former establishes that the term is an abbreviation ("hst") and specifies the full term ("hubble space telescope") in its title attribute. the latter indicates that the abbreviated term represents a term being defined. result the output of the above code lo...
<style>: The Style Information element - HTML: Hypertext Markup Language
Web › HTML › Element › style
ce a cryptographic nonce (number used once) used to whitelist inline styles in a style-src content-security-policy. the server must generate a unique nonce value each time it transmits a policy. it is critical to provide a nonce that cannot be guessed as bypassing a resource’s policy is otherwise trivial. title this attribute specifies alternative style sheet sets. deprecated attributes scoped this attribute specifies that the styles only apply to the elements of its parent(s) and children. this attribute may be re-introduced in the future per https://github.com/w3c/csswg-drafts/issues/3547. if you want to use the attribute now, you can use a polyfill. examples a simple stylesheet in the following example, we apply a very simple stylesheet to a document: <!doctype ...
... permitted content text content matching the type attribute, that is text/css. tag omission neither tag is omissible. permitted parents any element that accepts metadata content. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlstyleelement ...
JavaScript Guide - JavaScript
javascript and gives an overview of the language. if you need exhaustive information about a language feature, have a look at the javascript reference. ...
... grammar and types basic syntax & comments declarations variable scope variable hoisting data structures and types literals control flow and error handling if...else switch try/catch/throw error objects loops and iteration for while do...while break/continue for..in for..of functions defining functions calling functions function scope closures arguments & parameters arrow functions expressions and operators assignment & comparisons arithmetic operators bitwise & logical operators conditional (ternary) operator numbers and dates number literals number object math object date object text formatting string literals string object template literals internationalization regular expr...
Memory Management - JavaScript
ment, an object is said to reference another object if the former has access to the latter (either implicitly or explicitly). for instance, a javascript object has a reference to its prototype (implicit reference) and to its properties values (explicit reference). in this context, the notion of an "object" is extended to something broader than regular javascript objects and also contain function scopes (or the global lexical scope). reference-counting garbage collection this is the most naive garbage collection algorithm. this algorithm reduces the problem from determining whether or not an object is still needed to determining if an object still has any other objects referencing it. an object is said to be "garbage", or collectible if there are zero references pointing to it. example var ...
... so it cannot be freed. z = null; // the 'a' property of the object originally in x // has zero references to it. it can be garbage collected. limitation: circular references there is a limitation when it comes to circular references. in the following example, two objects are created with properties that reference one another, thus creating a cycle. they will go out of scope after the function call has completed. at that point they become unneeded and their allocated memory should be reclaimed. however, the reference-counting algorithm will not consider them reclaimable since each of the two objects has at least one reference pointing to them, resulting in neither of them being marked for garbage collection. circular references are a common cause of memory leaks. fu...
Array.prototype[@@iterator]() - JavaScript
urn value the initial value given by the values() iterator. by default, using arr[symbol.iterator] will return the values() function. ...
...od. this could be a built-in object like string object or a custom object. ...
Function.prototype.bind() - JavaScript
ter to the target function func when the bound function is called. the value is ignored if the bound function is constructed using the new operator. when using bind to create a function (supplied as a callback) inside a settimeout, any primitive value passed as thisarg is converted to object. if no arguments are provided to bind , or if the thisarg is null or undefined, the this of the executing scope is treated as the thisarg for the new function. arg1, arg2, ...argn optional arguments to prepend to arguments provided to the bound function when invoking func. return value a copy of the given function with the specified this value, and initial arguments (if provided). description the bind() function creates a new bound function, which is an exotic function object (a term from ecmascript...
... object is usually lost. creating a bound function from the function, using the original object, neatly solves this problem: this.x = 9; // 'this' refers to global 'window' object here in a browser const module = { x: 81, getx: function() { return this.x; } }; module.getx(); // returns 81 const retrievex = module.getx; retrievex(); // returns 9; the function gets invoked at the global scope // create a new function with 'this' bound to module // new programmers might confuse the // global variable 'x' with module's property 'x' const boundgetx = retrievex.bind(module); boundgetx(); // returns 81 partially applied functions the next simplest use of bind() is to make a function with pre-specified initial arguments. these arguments (if any) follow the provided this value and a...
Symbol.unscopables - JavaScript
@@unscopables symbol (symbol.unscopables) can be defined on any object to exclude property names from being exposed as lexical variables in with with environment bindings. note that if using strict mode, with statements are not available and will likely also not need this symbol. setting a property to true in an unscopables object will make it unscopable and therefore it won't appear in lexical scope variables. setting a property to false will make it scopable and thus it will appear in lexical scope variables. property attributes of symbol.unscopables writable no enumerable no configurable no examples scoping in with statements the following code works fine in es5 and below. however, in ecmasc...
... code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environment "keys" would now be the method and not the variable. that's when the unscopables symbol was introduced. a built-in unscopables setting is implemented as array.prototype[@@unscopables] to prevent that some of the array methods are being scoped into the with statement. var keys = []; with (array.prototype) { keys.push('something'); } object.keys(array.prototype[symbol.unscopables]); // ["copywithin", "entries", "fill", "find", "findindex", // "includes", "keys", "values"] unscopables in objects you can also set unscopables for your own objects. var obj = { foo: 1, bar: 2 }; obj[symbol.unscopables] = { foo: false, bar...
instanceof - JavaScript
c // true since c.prototype is now in o3's prototype chain note that the value of an instanceof test can change based on changes to the prototype property of constructors. it can also be changed by changing an object's prototype using object.setprototypeof. it is also possible using the non-standard __proto__ property. instanceof and multiple context (e.g. frames or windows) different scopes have different execution environments. this means that they have different built-ins (different global object, different constructors, etc.). this may result in unexpected results. for instance, [] instanceof window.frames[0].array will return false, because array.prototype !== window.frames[0].array and arrays inherit from the former. this may not make sense at first, but for scripts dealing w...
... obj instanceof xpcominterface (e.g. components.interfaces.nsifile) calls obj.queryinterface(xpcominterface) and returns true if queryinterface succeeded. a side effect of such call is that you can use xpcominterface's properties on obj after a successful instanceof test. unlike standard javascript globals, the test obj instanceof xpcominterface works as expected, even if obj is from a different scope. examples demonstrating that string and date are of type object and exceptional cases the following code uses instanceof to demonstrate that string and date objects are also of type object (they are derived from object). however, objects created with the object literal notation are an exception here: although the prototype is undefined, instanceof object returns true. let simplestr = 'this ...
import - JavaScript
t will refer to the named imports. description the name parameter is the name of the "module object" which will be used as a kind of namespace to refer to the exports. the export parameters specify individual named exports, while the import * as name syntax imports all of them. below are examples to clarify the syntax. import an entire module's contents this inserts mymodule into the current scope, containing all the exports from the module in the file located in /modules/my-module.js. import * as mymodule from '/modules/my-module.js'; here, accessing the exports means using the module name ("mymodule" in this case) as a namespace. for example, if the module imported above includes an export doalltheamazingthings(), you would call it like this: mymodule.doalltheamazingthings(); import...
...module imported above includes an export doalltheamazingthings(), you would call it like this: mymodule.doalltheamazingthings(); import a single export from a module given an object or value named myexport which has been exported from the module my-module either implicitly (because the entire module is exported) or explicitly (using the export statement), this inserts myexport into the current scope. import {myexport} from '/modules/my-module.js'; import multiple exports from module this inserts both foo and bar into the current scope. import {foo, bar} from '/modules/my-module.js'; import an export with a more convenient alias you can rename an export when importing it. for example, this inserts shortname into the current scope. import {reallyreallylongmoduleexportname as shortname} ...
try...catch - JavaScript
en 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 logmyerrors(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 throw three types of exceptions } catch (e) { if (e instanceof typeerror) { // statements to handle typeerror exceptions } else if (e instanceof rangeerror) { // statements to handle rangee...
...// statements to handle this very common expected error } else { throw e; // re-throw the error unchanged } } the exception identifier when an exception is thrown in the try-block, exception_var (i.e., the e in catch (e)) holds the exception value. you can use this identifier to get information about the exception that was thrown. this identifier is only available in the catch-block's scope. function isvalidjson(text) { try { json.parse(text); return true; } catch { return false; } } the finally-block the finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. note that the finally-block executes regardless of whether an exception is thrown. also, if an exc...
Statements and declarations - JavaScript
executed. switch evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case. throw throws a user-defined exception. try...catch marks a block of statements to try, and specifies a response, should an exception be thrown. declarations var declares a variable, optionally initializing it to a value. let declares a block scope local variable, optionally initializing it to a value. const declares a read-only named constant. functions and classes function declares a function with the specified parameters. function* generator functions enable writing iterators more easily. async function declares an async function with the specified parameters. return specifies the value to be returned by a function. class ...
...t used to export functions to make them available for imports in external modules, and other scripts. import used to import functions exported from an external module, another script. import.meta an object exposing context-specific metadata to a javascript module. label provides a statement with an identifier that you can refer to using a break or continue statement. with extends the scope chain for a statement. specifications specification ecmascript (ecma-262)the definition of 'ecmascript language: statements and declarations' in that specification. ...
serviceworker - Web app manifests
type object mandatory no the serviceworker member describes a service worker that the developer intends to install to control the pwa. examples "serviceworker": { "src": "./serviceworker.js", "scope": "/app", "type": "", "update_via_cache": "none" } values service worker contain the following values (only src is required): member description src the url to download the service worker script from. this is the only required member of the serviceworker member. ...
...l to control the pwa. examples "serviceworker": { "src": "./serviceworker.js", "scope": "/app", "type": "", "update_via_cache": "none" } values service worker contain the following values (only src is required): member description src the url to download the service worker script from. this is the only required member of the serviceworker member. scope a string representing a url that defines a service worker's registration scope; that is, what range of urls a service worker can control. this is usually a relative url, relative to the base url of the application. by default, the scope value for a service worker registration is set to the directory where the service worker script is located. type ? update_via_cache ...
<xsl:variable> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › variable
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:variable> element declares a global or local variable in a stylesheet and gives it a value. because xslt permits no side-effects, once the value of the variable has been established, it remains the same until the variable goes out of scope syntax <xsl:variable name=name select=expression > template </xsl:variable> required attributes name gives the variable a name. optional attributes select defines the value of the variable through an xpath expression. if the element contains a template, this attribute is ignored. type top-level or instruction. if it occurs as a top-level element, the variable is global in scope, and can be accessed throughout the document. if it occurs w...
... name gives the variable a name. optional attributes select defines the value of the variable through an xpath expression. if the element contains a template, this attribute is ignored. type top-level or instruction. if it occurs as a top-level element, the variable is global in scope, and can be accessed throughout the document. if it occurs within a template, the variable is local in scope, accessible only within the template in which it appears. defined xslt, section 11. gecko support supported. ...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
is intelligent structuring is particularly important as more and more data transfers are automated and take place between highly heterogeneous machines linked by a network. 14 an overview needshelp, needsmarkupwork, transforming_xml_with_xslt, xml, xslt the extensible stylesheet language/transform is a very powerful language, and a complete discussion of it is well beyond the scope of this article, but a brief discussion of some basic concepts will be helpful in understanding the description of netscape's capabilities that follows. 15 for further reading needscontent, needshelp, transforming_xml_with_xslt, xml, xslt http://www.amazon.com/xslt-programme.../dp/0764543814 16 resources extensions, needscontent, needsexample, needslivesample, ...
...th expression, converts it to a string, and writes that string to the result tree. 52 <xsl:variable> element, reference, xslt, variable the <xsl:variable> element declares a global or local variable in a stylesheet and gives it a value. because xslt permits no side-effects, once the value of the variable has been established, it remains the same until the variable goes out of scope 53 <xsl:when> element, reference, xslt, when the <xsl:when> element always appears within an <xsl:choose> element, acting like a case statement. 54 <xsl:with-param> element, reference, xslt, with-param the <xsl:with-param> element sets the value of a parameter to be passed into a template. ...
Communicating With Other Scripts - Archive of obsolete content
t.documentelement.dispatchevent(event); } finally, the page script "page-script.js" listens for the message and logs the greeting to the web console: window.addeventlistener("addon-message", function(event) { console.log(event.detail.greeting); }, false); after firefox 30: clone the message object this technique depends on being able to share the message payload between the content script scope and the page script scope. from firefox 30 this sharing requires an extra step: the content script needs to explicitly clone the message payload into the page script's scope using the global cloneinto() function: var messenger = document.getelementbyid("message"); messenger.addeventlistener("click", sendcustomevent, false); function sendcustomevent() { var greeting = {"greeting" : "hello worl...
Content Processes - Archive of obsolete content
ble to acces code with chrome privileges, so we use specialized wrappers, called security wrappers, 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 a...
Module structure of the SDK - Archive of obsolete content
existing property // will fail, or throw an exception in strict mode self.data = "foo"; using modules from outside the add-on sdk you can use commonjs modules outside the add-on sdk, in any environment where you can use components.utils.import. just call the following: const { require } = cu.import("resource://gre/modules/commonjs/toolkit/require.js", {}) this will import require() into your scope. you can then use that to import commonjs modules. you can import sdk modules in just the same way you could from an sdk add-on: // import the sdk's base64 module var base64 = require("sdk/base64"); base64.encode("hello"); // "agvsbg8=" you can import other commonjs modules, too, as long as you know the path to them: // import my module var mymodule = require("resource://path/to/my/module.j...
simple-storage - Archive of obsolete content
it's a normal javascript object, and you can treat it as you would any other. ...
core/heritage - Archive of obsolete content
ecurity measures are required to guarantee that documented behavior can't be 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: func...
lang/type - Archive of obsolete content
isjson({ fn: function () {} ); // false parameters value : mixed the variable to check. returns boolean : boolean indicating if value is an array/flat object containing only atomic values and other flat objects. instanceof(value, type) returns true if value is an instance of a given type. this is similar to the instanceof operator. the difference is that the type constructor can be from a scope that has a different top level object: for example, it could be from a different iframe, module or sandbox. let { instanceof } = require('sdk/lang/type'); instanceof(new class(), class); // true function class() {} parameters value : object the variable to check. type : object the constructor to compare to value returns boolean : boolean indicating if value is an instance of type. sourc...
Displaying annotations - Archive of obsolete content
a new page is loaded the function assigned to onattach is called. this function: initializes the content script instance with the current set of annotations provides a handler for messages from that content script, handling the three messages - show, hide and detach - that the content script might send adds the worker to an array, so we it can send messages back later. ...
Storing annotations - Archive of obsolete content
ll cover three topics relating to persistent storage: using simple-storage to persist objects handling exhaustion of the storage quota allocated to you respecting private browsing storing new annotations in this section we are only touching the main.js file. first, import the simple-storage module with a declaration like: var simplestorage = require('sdk/simple-storage'); in the module scope, initialize an array which will contain the stored annotations: if (!simplestorage.storage.annotations) simplestorage.storage.annotations = []; now we'll add a function to the module scope which deals with a new annotation. the annotation is composed of the text the user entered and the "annotation anchor", which consists of the url, element id and element content: function handlenewannotati...
File I/O - Archive of obsolete content
rfaces var file = services.dirsvc.get("profd", ci.nsifile); // append the file name. file.append("data.txt"); // note: "file" is an object that implements nsifile. if you want the // file system path, use file.path note: file is an object that implements nsifile. if you want the file system path, use file.path, . here are some of the special locations the directory service supports: (scope: d = product-wide, f = profile wide) string scope meaning achrom d %curprocd%/chrome aplugns d %curprocd%/plugins (deprecated - use aplugnsdl) aplugnsdl d comsd n/a %curprocd%/components curprocd n/a current working directory (usually the application's installation directory). defproflrt d...
Forms related code snippets - Archive of obsolete content
onstant statement) is not part of ecmascript 5. it is supported in firefox & chrome (v8) and partially supported in opera 9+ and safari. it is not supported in internet explorer 6-9, or in the preview of internet explorer 10. const is going to be defined by ecmascript 6, but with different semantics. similar to variables declared with the let statement, constants declared with const will be block-scoped. we used it only for didactic purpose. if you want a full browser compatibility of this library, please replace all the const statements with the var statements. this date-picker code snippet will automatically create an html code like the following: <table id="zdp-cal-1" class="zdp-calendar" style="z-index: 1026; position: absolute; left: 294px; top: 47px;"> <caption><span id="zdp-decr-yea...
Post data to window - Archive of obsolete content
length); var postdata = cc["@mozilla.org/network/mime-input-stream;1"]. ...
Rosetta - Archive of obsolete content
by default, the only possible standardized scripting language for html is ecmascript. hence, if you are going to use another scripting language you might expect that most of the browsers will not recognize it. also, regarding some languages (like c), it is even not well defined the meaning of part of their semantics in respect to a scope that is more restricted than the full access to the resources they usually deal with – imagine, for example, the meaning of a c pointer within a html page! nevertheless, the increasing computational power of modern browsers together with the introduction of typed arrays in ecmascript allow us, in theory, to build full virtual machines in pure ecmascript. therefore, it is also possible, in theory, to use ecmascript for a smaller task: parsing exotic programmi...
View Source for XUL Applications - Archive of obsolete content
importing gviewsourceutils xul applications wanting to show the source code for documents should import the viewsourceutils.js script instead of attempting to open the viewsource.xul window themselves: <script type="application/javascript" src="chrome://global/content/viewsourceutils.js"/> viewsourceutils.js exposes a gviewsourceutils global into the scope of the window that imports that script. method overview gviewsourceutils exposes several methods, but the only one you should be using directly is the viewsource method. the rest of those methods should be considered private, and might become inaccessible in the future. void viewsource(aobject); methods viewsource opens a viewer to the source code for some document or uri. parameters the viewsource method takes an o...
Extension Versioning, Update and Compatibility - Archive of obsolete content
php signing update manifests if you wish to serve your update rdf over regular http, gecko 1.9 based applications will require that you digitally sign the update manifest to ensure that it's information isn't tampered with between you creating it and applications retrieving it. the mccoy tool should be used to sign the update rdf. the technical details of the signing mechanism are beyond the scope of this document however the basics are as follows: step 1 - done once, before you publish your add-on the target: adding updatekey in install.rdf the add-on author creates a public/private rsa cryptographic key pair. the public part of the key is der encoded and then base 64 encoded and added to the add-on's install.rdf as an updatekey entry. step 2 - done every time you change your "update...
Appendix F: Monitoring DOM changes - Archive of obsolete content
worth noting, however, that while the animation-based implementation will fire any time an element which previously did not match the given selector is changed so that it does (when a class is added, for instance), the fallback will only match nodes when they are inserted into the dom tree. minor changes are also required if one wishes to support other browsers, or to run in non-chrome-privileged scopes. /** * watches for nodes matching the given css selector to become * available. * * @param {string} selector the css selector of nodes about which you * want to be notified. * @param {function(event)} callback the function which is to be called * when matching nodes become available. * @param {document} doc the document in which to watch for new nodes. * @optional @default ...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
the demo of this is seen at jsfiddle :: jsontodom example var json = ['html:div', {style:'background-color:springgreen'}, ['html:form', {id:'myfirstform'}, ['html:input', {type:'text', value:'my field'}], ['html:button', {id:'mybtn'}, 'button text content'] ], ['html:form', {id:'mysecondform'}, ['html:input', {...
The Essentials of an Extension - Archive of obsolete content
stringbundle.getstring("xulschoolhello.greeting.label"); window.alert(message); } and, finally, this is our function declaration. three lines of code are all we need for it to work. the first line in the body of the function declares a variable that will hold the stringbundle element defined in the overlay. the variable is declared using let, which is similar to var but with more restricted scope. here you can read more about let declarations. just like in regular js, we can use the dom (document object model) in order to manipulate the xul document. first we get a reference of the stringbundle element in the document. this is a special element that allows us to obtain localized strings dynamically, by only providing a "key" that identifies the string. this is what we do on the second li...
Firefox addons developer guide - Archive of obsolete content
should we keep this part ? gen's opinion: yes, because it is important for developers to make informed ...
Creating a dynamic status bar extension - Archive of obsolete content
eived() function configures the request to call inforeceived() when the response is received from the server. finally, we send the request to the server and return. inforeceived() when the server responds to our request, our the inforeceived() function, which is embedded inside refreshinformation(), gets called automatically. we embed this function inside refreshinformation() so that its variable scope includes the variables used by that function. due to the way javascript works, if inforeceived() were outside refreshinformation(), it would not have access to the same variable scope. in fact, even the this value would not match, so we couldn't get at the same variables and functions that way. function inforeceived() { var samplepanel = document.getelementbyid('stockwatcher'); var output = h...
JXON - Archive of obsolete content
onstant statement) is not part of ecmascript 5. it is supported in firefox & chrome (v8) and partially supported in opera 9+ and safari. it is not supported in internet explorer 6-9, or in the preview of internet explorer 10. const is going to be defined by ecmascript 6, but with different semantics. similar to variables declared with the let statement, constants declared with const will be block-scoped. we used it only for didactic purpose. if you want a full browser compatibility of this library, please replace all the const statements with the var statements. usage the obtained non-native jxon global object will have two methods: method description jxon.build(document[, verbosity[, freeze[, nesteattributes]]]) returns a javascript object based on the given xml docu...
Bypassing Security Restrictions and Signing Code - Archive of obsolete content
these privilege manager feature was not used much (aside from abuse), and its complexity made performance improvements difficult. signed script segregation was removed in bug 726125, the enableprivilege prompt was removed in bug 750859, and enableprivilege itself was nerfed in bug 757046. the privilege manager has been deprecated in firefox 12 and disabled in firefox 17. ...
No Proxy For configuration - Archive of obsolete content
iguration issues, testing and bugs. audience mozilla users, mozilla developers, mozilla testers. overview as browsers rapidly grew in popularity in the mid-90's, many network administrators added proxy servers. initially, proxy servers were used for access control and performance. many networks had limited access to the public network via proxy servers. because the public network was small in scope and connections were slow, a caching proxy could often improve the overall performance. this feature was originally designed as a "blacklist" of sites or domains that was within the intranet, and should not be accessed via the proxy server. due to various limitations, this feature should be used for only the most simple blacklist scenarios. in almost all cases, pac gives better control and flexi...
Working with BFCache - Archive of obsolete content
w in the current tab with a new page, what is the fate of the nsidomwindow supporting the view they click on? or: what happens when they hit the 'back' button? a: the outer nsidomwindow (the |window| object in content js, aka the <browser>'s contentwindow object in the parent document) stays right where it is. it just has its inner window and document replaced. the inner nsidomwindow (the global scope object in content js) is either thrown away when gc happens, or frozen and placed in the bfcache. when the user hits the 'back' button, either the window in bfcache is thawed or a new inner window is created, depending on whether there's a window in the bfcache. q: is the page reloaded? loaded from cache? or is the dom saved in some way as if the window was there but invisible? are scripts recomp...
Making it into a static overlay - Archive of obsolete content
a codebase (in which case it is no longer an extension but rather part of the default mozilla distribution) and to package it into an installer that users can run from within mozilla to add the extension to their mozilla installation. most extensions are distributed as installer packages, and that's how we'll distribute our extension. integrating extensions into the mozilla codebase is beyond the scope of this tutorial, but for more information see mozilla.org's hacking documentation. mozilla installer packages are called xpis (pronounced "zippies"), which stands for cross-platform installer. the packages are just standard zip archives of the files to be installed along with a javascript script that performs the installation and some rdf files that describe the components being installed for th...
Creating a Skin for Mozilla - Archive of obsolete content
the interface. what is a skin? a skin does not totally change the interface, it just defines how it looks. you cannot change what happens when the user right clicks on an image, but you can change the look of the right click menu (make it blue with pink polka dots, for example). if you want to change the functionality of mozilla, you'll have to look into modifying the chrome. that is beyond the scope of this document. contents getting started setup changing borders and colours changing images creating the install script in-depth system colours mozilla css commands how do i know what to modify? organizing images adding an image to the right of a toolbar jar file installer utility (provided by neil marshall) frequently asked questions links ...
JavaScript Client API - Archive of obsolete content
r last because it requires the least code. your class must derive from the syncengine class, defined in services-sync/modules/engines.js. syncengine contains a lot of code which handles logic for the core sync algorithm, but your subclass won't need to call any of this directly, unless you are overriding part of the sync algorithm to provide custom sync behavior (an advanced technique outside the scope of this article). a sample engine class: function fooengine() { weave.syncengine.call(this, "foo"); } fooengine.prototype = { __proto__: weave.syncengine.prototype, _recordobj: foorecord, _storeobj: foostore, _trackerobj: footracker }; as you can see, there isn't actually any new code here at all; the prototype simply defines some metadata such as the store and tracker classes to use...
Jetpack Snippets - Archive of obsolete content
d.js'); document.body.appendchild(firebug); (function(){if(window.firebug.version){firebug.init();}else{settimeout(arguments.callee);}})();void(firebug); ]]></script> </body></html>, width: 800, //wide enough to use firebug onselect: function(slide) { slide.slide(800, true); }}); calling into a slidebar from the global jetpack scope jetpack.slidebar.append({ onready: function (slide) { // call out to a global function, passing the slidebar object exinitslidebar(slide); }, ...});function exinitslidebar(aslidebar) { // this variable will now be global slider = aslidebar;} // then, accessing the slidebar htmlvar tl = slider.contentdocument.getelementbyid("thumblist"); // or calling slidebar api methods or acces...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
vascript debugger the javascript debugger can debug javascript running in the mozilla browser window. it supports such standard debugging features as breakpoint management, call stack inspection, and variable/object inspection. all features are accessible through the user interface or through the debugger's interactive console. with the console, you can execute arbitrary javascript in the same scope as the javascript currently being debugged. css differences mozilla-based products have the strongest support for cascading style sheets (css), including most of css1, css2.1 and parts of css3, compared to internet explorer as well as all other browsers. for most issues mentioned below, mozilla will add an error or warning entry into the javascript console. check the javascript console if you ...
RDF Datasource How-To - Archive of obsolete content
mponent. as such, it must (currently, see [1]) have: an xpcom clsid to identify the data source implementation an implementation class (that corresponds to the clsid) whose code lives in a dll. the dll must be located in the xpcom components directory a factory that is registered to an xpcom progid in order to be instantiated from the repository. constructing a dll for a component is beyond the scope of this document; the reader is referred to the rdf factory as a guideline. registering an rdf datasource is fairly simple: in the dll's nsregisterself() method, you simply call the component manager's registercomponent() method: extern "c" pr_implement(nsresult) nsregisterself(nsisupports* aservicemanager, const char* apath) { nsresult rv; ... // assume compmgr refers to the component m...
SpiderMonkey coding conventions - Archive of obsolete content
spidermonkey c++ coding style page on wikimo which is more up to date and the canonical source. the spidermonkey project owners enforce coding conventions pretty strictly during code reviews. naming conventions public function names begin with js_ followed by capitalized "intercaps", e.g. js_newobject. extern but library-private function names use a js_ prefix and mixed case, e.g. js_searchscope. most static function names have unprefixed, mixed-case names: getchar. but static native methods of js objects have lowercase, underscore-separated or intercaps names, e.g., str_indexof. and library-private and static data use underscores, not intercaps (but library-private data do use a js_ prefix). scalar type names are lowercase and js-prefixed: jsdouble. aggregate type names a...
DOM Interfaces - Archive of obsolete content
turn value element - the return value of getanonymouselementbyattribute is an anonymous descendant of the given element with matching attribute name and value. getbindingparent the getbindingparent method is used to obtain the bound element with the binding attached that is responsible for the generation of the specified anonymous node. this method enables an author to determine the scope of any content node. when content at the document-level scope is passed in as an argument, the property's value is null. parameters node - the node for which the bound element responsible for generation is desired. return value element - the return value of getbindingparent is the element responsible for the given anonymous node. loadbindingdocument the loadbindingdo...
Elements - Archive of obsolete content
he document layout was locked down, so that attempting to get layout information from within the constructor could return out of date information. in firefox 3 and later, the constructor is called when reflow can take place, which results in up-to-date information being returned. see bug 398404 for details. note: all properties of the binding are "imported" as local variables in a constructor's scope. see bug 407314 for more details. destructor the code inside the destructor is called when a binding is being removed from an element. you can use this to unload resources to free memory. however the destructor is often not called when it should, see bug 230086. the destructor tag must be placed inside the implementation tag. id - the id attribute is a document-unique identifier. method <...
Creating XPI Installer Modules - Archive of obsolete content
ectories and editing them with a text editor has been replaced by something a lot of developers find more confusing and esoteric. this article describes the new packaging scheme of mozilla and offers a tutorial for creating a new package that can then be redistributed, installed, and made available to users. the xpi packaging scheme a complete description of the new packaging scheme is beyond the scope of this article. the reader is referred to jar packaging, which describes the design, goals, and options available for jar packaging in some depth. what follows is a very brief overview of the design and a description of what mozilla expects in installable packages. resources are collected in jar archives whose contents are specified in contents.rdf files at their own top level. the contents.rdf ...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
of xul and css. we assume that you're also familiar with the basics of creating firefox extensions and have the hello world extension working. another tutorial, which walks you through the entire process from the beginning, is also available. creating an overlay the first step is to create an overlay for the document containing the toolbar you wish to enhance. explaining overlays is beyond the scope of this tutorial -- you can read about them in the xul tutorial. to overlay a document, you need to know its uri. you can find a list of uris for the most commonly overlaid documents at the bottom of this page. note: some people overlay chrome://messenger/content/mailwindowoverlay.xul. that should cause the button to appear on all windows that mailwindowoverlay.xul is applied to (i.e. main wind...
Document Object Model - Archive of obsolete content
code 'name = 7', without having to specify any object to use. in a browser context, the window is the global object, and the same is also true for xul. naturally, this global object will be different for each window. each frame will also have a separate window object. the window is often referred to using the window property, although this is optional. sometimes, this is done just to clarify the scope of the method you are referring to. for example, the following two lines which open a new window are functionally equivalent: window.open("test.xul","_new"); open("test.xul","_new"); when you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object. in xul, each function you declare will be set a...
XUL Accesskey FAQ and Policies - Archive of obsolete content
er word in the prompt. finally, use any non-silent letter in an action word (do these after the rest of the dialog has accesskeys chosen). common elements that don't get accesskeys ok buttons. cancel buttons. close buttons. tab panel labels. toolbar buttons tree items list items column headers are there any crucial bugs i should know about? bug 143065 - scope of accesskeys is not limited to the current tab panel. where do accesskeys need to be added? look for dependencies of bug 129179 (the xul accesskey hookup meta bug), or look for bugs with "accesskey" or "mnemonic" in the summary, or look for dialogs where there are no elements with underlined letters. file bugs under the keyboard navigation component, and make meta bug 129179 dependent on them. ...
2006-10-13 - Archive of obsolete content
rs 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 about why the bug https://bugzilla.m...
NPAPI plugin reference - Archive of obsolete content
ier. the lifetime of npidentifiers is controlled by the browser. npn newstream requests the creation of a new data stream produced by the plug-in and consumed by the browser. npn_createobject allocates a new npobject. npn_destroystream closes and deletes a stream. npn_enumerate gets the names of the properties and methods of the specified npobject. npn_evaluate evaluates a script in the scope of the specified npobject. npn_forceredraw asks the plugin host to immediately (synchronously) repaint invalid areas. npn_getauthenticationinfo the function is called by plugins to get http authentication information from the browser. npn_getintidentifier returns an opaque identifier for the integer that is passed in. npn_getproperty gets the value of a property on the specified npobject.
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
ment gives the (current) total number of comments made for the item -- for the blog post. although not necessary, people also often use other rss modules to get at (and read) the comments (since rss does not currently provide facilities for this either). some use the well-formed web rss module for this. and some are now using atomic rss for this. (using either of these 2 rss modules is out of the scope of this article.) in reality, an item's comments count could change at any given time. people can (potentially) post new comments to an item at any given time. and (spam) comments could get deleted. and thus the comments count that the <slash:comments> element provides is only a snapshot; it was only the comment count at a moment in time. one of the shortcomings of the <slash:comments> element is...
Introduction to Public-Key Cryptography - Archive of obsolete content
ample have these meanings: uid: user id e: email address cn: the user's common name o: organization c: country dns may include a variety of other name-value pairs. they are used to identify both certificate subjects and entries in directories that support the lightweight directory access protocol (ldap). the rules governing the construction of dns can be quite complex and are beyond the scope of this document. for comprehensive information about dns, see a string representation of distinguished names] at the following url: https://www.ietf.org/rfc/rfc1485.txt a typical certificate every x.509 certificate consists of two sections: the data section includes the following information: the version number of the x.509 standard supported by the certificate. the certificate's...
Introduction to SSL - Archive of obsolete content
client using public-key techniques, then allows the client and the server to cooperate in the creation of symmetric keys used for rapid encryption, decryption, and tamper detection during the session that follows. optionally, the handshake also allows the client to authenticate itself to the server. the exact programmatic details of the messages exchanged during the ssl handshake are beyond the scope of this document. however, the steps involved can be summarized as follows (assuming the use of the cipher suites listed in "cipher suites with rsa key exchange"): the client sends the server the client's ssl version number, cipher settings, randomly generated data, and other information the server needs to communicate with the client using ssl. the server sends the client the server's ssl ve...
Creating a Skin for Firefox - Archive of obsolete content
is a skin? a skin does not totally change the interface; instead, it just defines how the interface looks. you can't change what happens when the user right clicks on an image, but you can change the look of the right click menu (make it blue with pink polka dots, for example). if you want to change the functionality of firefox, you'll have to look into modifying the chrome, which is beyond the scope of this document. contents getting started original document information author(s): neil marshall and tucker lee other contributors: brent marshall, cdn (http://themes.mozdev.org), jp martin, boris zbarsky, asa dotzler, wesayso, david james, dan mauch, anders conbere, tim regula (http://www.igraphics.nn.cx) copyright information: copyright 2002-2003 neil marshall, permission given to mdc ...
Processing XML with E4X - Archive of obsolete content
cting nodes within a document that match specific criteria. these filter operations are specified using an expression contained in parentheses: var html = <html> <p id="p1">first paragraph</p> <p id="p2">second paragraph</p> </html>; alert(html.p.(@id == "p1")); // alerts "first paragraph" nodes matching the path before the expression (in this case the paragraph elements) are added to the scope chain before the expression is evaluated, as if they had been specified using the with statement. consequently, filters can also run against the value of a single node contained within the current element: var people = <people> <person> <name>bob</name> <age>32</age> </person> <person> <name>joe</name> <age>46</age> </person> </people>; alert(people.person.(name == "joe...
Namespaces - Archive of obsolete content
you can also change namespaces at any time, by repeating the statement. ...
Debug - Archive of obsolete content
chronous operation was canceled. 2 debug.ms_async_op_status_error the asynchronous operation resulted in an error. 3 properties debug.debuggerenabled determines whether debugging is enabled for the script context. debugging may be enabled or disabled whether or not a debugger is attached. debug.setnonusercodeexceptions determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled. functions debug.mstraceasynccallbackcompleted indicates that the callback stack associated with a previously specified asynchronous operation has completed. debug.mstraceasynccallbackstarting associates the callback stack with a previously specified asynchronous operation. debug.mstraceasyncoperationcompleted indicates that an asynchr...
arguments.caller - Archive of obsolete content
the obsolete arguments.caller property used to provide the function that invoked the currently executing function. this property has been removed and no longer works. description this property is not available anymore, but you can still use function.caller. function whocalled() { if (whocalled.caller == null) console.log('i was called from the global scope.'); else console.log(whocalled.caller + ' called me!'); } examples the following code was used to check the value of arguments.caller in a function, but doesn't work anymore. function whocalled() { if (arguments.caller == null) console.log('i was called from the global scope.'); else console.log(arguments.caller + ' called me!'); } specifications not part of any standard. implemented in javascri...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
otexposed() { 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 statement is of the form <functionname>.proxy = true. ...
Sharp variables in JavaScript - Archive of obsolete content
tandard syntax for creating or serializing cyclic data graphs that used to be supported only by mozilla's spidermonkey js engine. this feature has been removed in bug 566700, firefox 12. form sharp variables have the form of a sharp sign (#) immediately followed by one or more digits. the number represented by the digits serves as the variable's unique identifier, but leading 0s are ignored. scope sharp variables are only in scope in the statement in which they are defined. usage to create a sharp variable, simply assign an object to it in a line of code using an equal sign. you cannot assign primitives (including strings) to sharp variables. make sure you don't put in any spaces before the equal sign though. #1 = {}; // this doesn't do much since the sharp variable is out of sco...
Archived open Web documentation - Archive of obsolete content
the guide section links to an interesting document discussing how to create and use private variables in objects, which is great if you want to protect the various properties within an object from being poked at accidentally. i also just read a document on proper inheritance using apply(). well if you combine the two, you can have inherited private variables: scope cheatsheet javascript with mozilla extensions has both function-scoped vars and block-scoped lets. along with hoisting and dynamic behavior, scope in javascript is sometimes surprising. server-side javascript here's a radical idea: use one language to write entire web apps -- the same language which billions of web pages already use, every day.
2D collision detection - Game development
example without canvas or external libraries. separating axis theorem this is a collision algorithm that can detect a collision between any two *convex* polygons. it's more complicated to implement than the above methods but is more powerful. the complexity of an algorithm like this means we will need to consider performance optimization, covered in the next section. ...
Bounding volume collision detection with THREE.js - Game development
a similar fashion as before, there is a sphere.intersectssphere method to perform this test. knotbsphere.intersectssphere(othersphere); sphere vs. box3 unfortunately this test is not implemented in three.js, but we can patch sphere to implement a sphere vs. aabb intersection algorithm. ...
Efficient animation for web games - Game development
ed firefox to need to redraw everything (they were fine in other browsers, as it happens — that particular issue is now fixed). some of the third party code we were using was poorly optimised. a take-away to help combat poor animation performance, chris lord wrote animator.js, a simple, easy-to-use animation library, heavily influenced by various parts of clutter, but with a focus on avoiding scope-creep. it does one thing, and it does it well. animator.js is a fire-and-forget style animation library, designed to be used with games, or other situations where you need many, synchronised, custom animations. it includes a handful of built-in tweening functions, the facility to add your own, and helper functions for animating object properties. puzzowl uses it to drive all the drawing updates a...
Closure - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, functions create a closure context. ...
Function - MDN Web Docs Glossary: Definitions of Web-related terms
tion is a code snippet that can be called by other code or by itself, or a variable that refers to the function. when a function is called, arguments are passed to the function as input, and the function can optionally return a value. a function in javascript is also an object. a function name is an identifier included as part of a function declaration or function expression. the function name's scope depends on whether the function name is a declaration or expression. different types of functions an anonymous function is a function without a function name. only function expressions can be anonymous, function declarations must have a name: // when used as a function expression (function () {}); // or using the ecmascript 2015 arrow notation () => {}; the following terms are not used in th...
Local variable - MDN Web Docs Glossary: Definitions of Web-related terms
a variable whose name is bound to its value only within a local scope. example var global = 5; //is a global variable function fun(){ var local = 10; //is a local variable } ...
Mixin - MDN Web Docs Glossary: Definitions of Web-related terms
s well as those it defines itself. all of the methods and properties are used exactly the same regardless of whether they're implemented in the mixin or the interface or class that implements the mixin. the advantage of mixins is that they can be used to simplify the design of apis in which multiple interfaces need to include the same methods and properties. for example, the windoworworkerglobalscope mixin is used to provide methods and properties that need to be available on both the window and workerglobalscope interfaces. the mixin is implemented by both of those interfaces. learn more general knowledge mixin on wikipedia ...
Namespace - MDN Web Docs Glossary: Definitions of Web-related terms
in an operating system a directory is a namespace. ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
tantiated with our first statement after finding it, the expression is evaluated, foo is replaced by 5 and the javascript engine passes that value to the functions as an argument before executing the statements inside the functions' bodies, javascript takes a copy of the originally passed argument (which is a primitive) and creates a local copy. these copies, existing only inside the functions' scopes, are accessible via the identifiers we specified in the functions' definitions (num for addtwo, foo for addtwo_v2) then, the functions' statements are executed: in the first function, a local num variable had been created. we are increasing its value by 2, not the original foo's value! in the second function, a local foo variable had been created. we are increasing its value by 2, not ...
HTML: A good basis for accessibility - Learn web development
he header rows are and if they are heading up rows, columns, etc. this can only be done visually for the above table (see bad-table.html and try the example out yourself). now have a look at our punk bands table example — you can see a few accessibility aids at work here: table headers are defined using <th> elements — you can also specify if they are headers for rows or columns using the scope attribute. this gives you complete groups of data that can be consumed by screen readers as single units. the <caption> element and <table> summary attribute both do similar jobs — they act as alt text for a table, giving a screen reader user a useful quick summary of the table's contents. the <caption> element is generally preferred as it makes it's content accessible to sighted users too, wh...
HTML: A good basis for accessibility - Learn web development
he header rows are and if they are heading up rows, columns, etc. this can only be done visually for the above table (see bad-table.html and try the example out yourself). now have a look at our punk bands table example — you can see a few accessibility aids at work here: table headers are defined using <th> elements — you can also specify if they are headers for rows or columns using the scope attribute. this gives you complete groups of data that can be consumed by screen readers as single units. the <caption> element and <table> summary attribute both do similar jobs — they act as alt text for a table, giving a screen reader user a useful quick summary of the table's contents. the <caption> element is generally preferred as it makes it's content accessible to sighted users too, wh...
Pseudo-classes and pseudo-elements - Learn web development
” or “paused”, when that element is “paused”. :read-only matches an element if it is not user-alterable. :read-write matches an element if it is user-alterable. :required matches form elements that are required. :right in paged media, matches right-hand pages. :root matches an element that is the root of the document. :scope matches any element that is a scope element. :valid matches an element such as an <input> element, in a valid state. :target matches an element if it is the target of the current url (i.e. if it has an id matching the current url fragment). :visited matches visited links. pseudo-elements selector description ::after matche...
Type, class, and ID selectors - Learn web development
ar elements you can create a selector that will target specific elements with the class applied. in this next example we will highlight a <span> with a class of highlight differently to an <h1> heading with a class of highlight. we do this by using the type selector for the element i want to target, with the class appended using a dot, with no white space in between. this approach reduces the scope of a rule as the rule will only apply to that particular element & class combination; so you would need to add another selector if you decided the rule should apply to other elements too. target an element if it has more than one class applied you can apply multiple classes to an element and target them individually, or only select the element when all of the classes in the selector are presen...
What are browser developer tools? - Learn web development
he page. in example.js, a breakpoint has been set on the statement listitems.push(inputnewitem.value); the final two sections only appear when the code is running. the call stack section shows you what code was executed to get to the current line. you can see that the code is in the function that handles a mouse click, and that the code is currently paused on the breakpoint. the final section, scopes, shows what values are visible from various points within your code. for example, in the image below, you can see the objects available to the code in the additemclick function. find out more 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 cons...
Client-side form validation - Learn web development
ed an exhaustive security measure! your apps should always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too easy to bypass, so malicious users can still easily send bad data through to your server. read website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. what is form validation? go to any popular site with a registration form, and you will notice that they provide feedback when you don't enter your data in the format they are expecting. you'll get messages such as: "this field is required" (you can't leave this field blank). "please enter your phone number in the format xxx-xxxx" (a specific d...
The HTML5 input types - Learn web development
an exhaustive security measure! your apps should always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too easy to turn off, so malicious users can still easily send bad data through to your server. read website security for an idea of what could 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...
HTML forms in legacy browsers - Learn web development
ometimes, dropping some functionality leads to a better user experience than having exactly the same functionality in all browsers. as a last reminder, just always think about the end users. conclusion as you can see, considering browser and operating system default form control appearance is important. there are many techniques to handle these issue; however mastering all of them is beyond the scope of this article. the basic premise is to consider whether altering the default implemenation is worth the work before embarking on the challenge. if you read all the articles of this html forms guide, you should now be at ease with using forms. ...
Sending form data - Learn web development
: django for python (a bit more heavyweight than flask, but with more tools and options). express for node.js. laravel for php. ruby on rails for ruby. it's worth noting that even using these frameworks, working with forms isn't necessarily easy. but it's much easier than trying to write all the functionality yourself from scratch, and will save you a lot of time. note: it is beyond the scope of this article to teach you any server-side languages or frameworks. the links above will give you some help, should you wish to learn them. a special case: sending files sending files with html forms is a special case. files are binary data — or considered as such — whereas all other data is text data. because http is a text protocol, there are special requirements for handling binary da...
Styling web forms - Learn web development
h as changing the width or margin of the control) you generally don't have the ability to style the controls' internal components (such as the date picker calendar, or the button on the <select> that causes the options list to display) making up those widgets. if you want to thoroughly customize those widgets, you really have to create your own using html, css, and javascript. this is beyond the scope of the core form articles, but we do look at this in an advanced article how to build custom form controls. note: there are some proprietary css pseudo-elements available that allow you to style internal components of these form controls, such as ::-moz-range-track, but these are not consistent across browsers, so can't be relied upon. we will mention these later as well. the good to style f...
JavaScript basics - Learn web development
s styles; collecting and manipulating a video stream from a user's webcam, or generating 3d graphics and audio samples. third-party apis that allow developers to incorporate functionality in sites from other content providers, such as twitter or facebook. third-party frameworks and libraries that you can apply to html to accelerate the work of building sites and applications. it's outside the scope of this article—as a light introduction to javascript—to present the details of how the core javascript language is different from the tools listed above. you can learn more in mdn's javascript learning area, as well as in other parts of mdn. the section below introduces some aspects of the core language, and offers an opportunity to play with a few browser api features too. have fun! a hel...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
already partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better. note: table headings come with some default styling — they are bold and centered even if you don't add your own styling to the table, to help them stand out. tables headers also have an added benefit — along with the scope attribute (which we'll learn about in the next article), they allow you to make tables more accessible by associating each header with all the data in the same row or column. screenreaders are then able to read out a whole row or column of data at once, which is pretty useful. allowing cells to span multiple rows and columns sometimes we want cells to span multiple rows or columns. take the fol...
Introduction to events - Learn web development
.onclick = functionb; the second line overwrites the value of onclick set by the first line. this would work, however: myelement.addeventlistener('click', functiona); myelement.addeventlistener('click', functionb); both functions would now run when the element is selected. in addition, there are other powerful features and options available with this event mechanism. these are a little out of scope for this article, but if you want to read them, visit the addeventlistener() and removeeventlistener() reference pages. what mechanism should i use? of the three mechanisms, you shouldn't use the html event handler attributes — these are outdated, and bad practice, as mentioned above. the other two are relatively interchangeable, at least for simple uses: event handler properties have les...
Looping code - Learn web development
ion) we would recommend for, at least to begin with, as it is probably the easiest for remembering everything — the initializer, condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them. note: there are other loop types/features too, which are useful in advanced/specialized situations and beyond the scope of this article. if you want to go further with your loop learning, read our advanced loops and iteration guide. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: loops. conclusion this article has revealed t...
JavaScript building blocks - Learn web development
essential concept in coding is functions. functions allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. in this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define functions, scope, and parameters. build your own function with most of the essential theory dealt with previously, this article provides a practical experience. here you'll get some practice with building up your own custom function. along the way, we'll also explain some further useful details of dealing with functions. function return values the last essential concept you must know about a function is retur...
What went wrong? Troubleshooting JavaScript - Learn web development
t means "nothing", or "no value". so loworhi has been declared and initialised, but not with any meaningful value — it has no type or value. note: this error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the checkguess() { ... } block). as you'll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. in this case, the code was not run and the error was not thrown until the checkguess() function was run by line 86. have a look at line 78, and you'll see the following code: loworhi.textcontent = 'last guess was too high!'; this line is trying to set the textcontent property of the loworhi constant to a text string, but it's not working because loworhi does n...
Adding features to our bouncing balls demo - Learn web development
) { _this.y += _this.vely; } } so when a key is pressed, the event object's keycode property is consulted to see which key is pressed. if it is one of the four represented by the specified keycodes, then the evil circle will move left/right/up/down. for a bonus point, can you tell us why we've had to set let _this = this; in the position it is in? it is something to do with function scope. collisiondetect() this method will act in a very similar way to ball()'s collisiondetect() method, so you can use a copy of that as the basis of this new method. but there are a couple of differences: in the outer if statement, you no longer need to check whether the current ball in the iteration is the same as the ball that is doing the checking — because it is no longer a ball, it is th...
Working with JSON - Learn web development
called xmlhttprequest (often called xhr). this is a very useful javascript object that allows us to make network requests to retrieve resources from a server via javascript (e.g. images, text, json, even html snippets), meaning that we can update small sections of content without having to reload the entire page. this has led to more responsive web pages, and sounds exciting, but it is beyond the scope of this article to teach it in much more detail. to start with, we store the url of the json we want to retrieve in a variable. add the following at the bottom of your javascript code: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; to create a request, we need to create a new request object instance from the xmlhttprequest constructor, using ...
Object prototypes - Learn web development
n defined like this. for example you could add a property like so: person.prototype.fullname = 'bob smith'; this isn't very flexible, as the person might not be called that. it'd be much better to build the fullname out of name.first and name.last: person.prototype.fullname = this.name.first + ' ' + this.name.last; however, this doesn't work. that's because this will be referencing the global scope in this case, not the function scope. calling this property would return undefined. this worked fine on the method we defined earlier in the prototype because it is sitting inside a function scope, which will be transferred successfully to the object instance scope. so you might define constant properties on the prototype (i.e. ones that never need to change), but generally it works better to def...
Test your skills: JSON - Learn web development
code on a different origin. in the live code editor above, both the javascript code and the requested json file are on the same origin (the code sits on a github repo, and is embedded here in an <iframe>). if you put your code on codepen for example, it would fail because the json it is requesting is not on the same origin. you can get around these restrictions using cors, but this is beyond the scope of what we are teaching here. assessment or further help you can practice these examples in the interactive editor above. if you would like your work assessed, or are stuck and want to ask for help: write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for json skill test"...
Aprender y obtener ayuda - Learn web development
a hybrid approach is probably what you will end up with. and you'll probably come up with other methods than the three we covered above. making a plan it is a good idea to create a plan to help you achieve what you want to achieve through your learning. a goal statement it sounds silly, but why not start with a single sentence that says what you want to achieve? the following have different scopes, but are all realistic and achievable: i want to become a professional web developer in two years' time. i want to learn enough to build a website for my local amateur tennis club. i want to learn html and css so i can expand my job role to take over updating the content on our company website. the following are not quite as reasonable: i want to go from a complete beginner to becoming...
CSS performance optimization - Learn web development
s follow a specific rendering path: paint only occurs after layout, which occurs after the render tree is created, which in turn requires both the dom and the cssom trees. to optimize the cssom construction, remove unnecessary styles, minify, compress and cache it, and split css not required at page load into additional files to reduce css render blocking. optimizing for render blocking css can scope styles to particular conditions with media queries. media queries are important for a responsive web design and help us optimize a critical rendering path. the browser blocks rendering until it parses all of these styles but will not block rendering on styles it knows it will not use, such the print stylesheets. by splitting the css into multiple files based on media queries, you can prevent rend...
Ember app structure and componentization - Learn web development
now, as they are for adding interactivity and state manipulation. by default, generate component generates template-only components, because in large applications, template-only components end up being the majority of the components. header-test.js is for writing automated tests to ensure that our app continues to work over time as we upgrade, add features, refactor, etc. testing is outside the scope of this tutorial, although generally testing should be implemented as you develop, rather than after, otherwise it tends to be forgotten about. if you're curious about testing, or why you would want to have automated tests, check out the official ember tutorial on testing. before we start adding any component code, let’s create the scaffolding for the other components. enter the following line...
Getting started with React - Learn web development
t 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'; reactdom.render(<app />, document.getelementbyid('root')); variables and props next, we'll use a few of our javascript skills to get a bit more comfortable editing co...
Deployment and next steps - Learn web development
navigate to the root of your app and run npx vercel; the first time you do it, you'll be prompted to enter your email address, and follow the steps in the email sent to that address, for security purposes. ...
Vue conditional rendering: editing existing todos - Learn web development
: string, required: true }, id: { type: string, required: true } }, data() { return { newlabel: this.label }; }, methods: { onsubmit() { if (this.newlabel && this.newlabel !== this.label) { this.$emit("item-edited", this.newlabel); } }, oncancel() { this.$emit("edit-cancelled"); } } }; </script> <style scoped> .edit-label { font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #0b0c0c; display: block; margin-bottom: 5px; } input { display: inline-block; margin-top: 0.4rem; width: 100%; min-height: 4.4rem; padding: 0.4rem 0.8rem; border: 2px solid #565656; } form { display: flex; flex-direction: row; flex-wrap: wra...
Getting started with Vue - Learn web development
./components/helloworld.vue'; export default { name: 'app', components: { //you can register components locally here. helloworld } }; note: if you want to use typescript syntax, you need to set the lang attribute on the <script> tag to signify to the compiler that you're using typescript — <script lang="ts">. <style> is where you write your css for the component. if you add a scoped attribute — <style scoped> — vue will scope the styles to the contents of your sfc. this works similar to css-in-js solutions, but allows you to just write plain css. note: if you select a css pre-processor when creating the project via the cli, you can add a lang attribute to the <style> tag so that the contents can be processed by webpack at build time. for example, <style lang="scss"> w...
Handling common accessibility problems - Learn web development
y for a screen reader user to associate rows or columns together as groupings of data — to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. this can only be done visually for such a table. if you instead look at our punk-bands-complete.html example (live, source), you can see a few accessibility aids at work here, such as table headers (<th> and scope attributes), <caption> element, etc. note: for more information about accessible tables, read accessible data tables. css css tends to provide a lot fewer fundamental accessibility features than html, but it can still do just as much damage to accessibility if used incorrectly. we have already mentioned a couple of accessibility tips involving css: use the correct semantic elements to mar...
Introduction to automated testing - Learn web development
of cross-browser testing. objective: to provide an understanding of what automated testing entails, how it can make your life easier, and how to make use of some of the commercial products that make things easier. automation makes things easy throughout this module we have detailed loads of different ways in which you can test your websites and apps, and explained the sort of scope your cross-browser testing efforts should have in terms of what browsers to test, accessibility considerations, and more. sounds like a lot of work, doesn't it? we agree — testing all the things we've looked at in previous articles manually can be a real pain. fortunately, there are tools to help us automate some of this pain away. there are two main ways in which we can automate the tests we'...
Handling common HTML and CSS problems - Learn web development
ng query will select the last 2 versions of all major browsers and versions of ie above 9. last 2 versions, ie > 9 autoprefixer can also be used in other, more convenient ways — see autoprefixer usage. for example, you can use it with a task runner/build tool such as gulp or webpack to automatically add prefixes once development has been done. (explaining how these work is somewhat beyond the scope of this article.) you can also use a plugin for a text editor such as atom or sublime text. for example, in atom: you can install it by going to preferences > install, searching for autoprefixer, then hitting install. you can set a browser query by pressing the autoprefixer settings button and entering the query in the text field in the settings section on the page. in your code, you can se...
Setting up your own test automation environment - Learn web development
ur scripts to it using the url you choose to expose it at. integrating selenium with ci tools as another point, it is also possible to integrate selenium and related tools like lambdatest, and sauce labs with continuous integration (ci) tools — this is useful, as it means you can run your tests via a ci tool, and only commit new changes to your code repository if the tests pass. it is out of scope to look at this area in detail in this article, but we'd suggest getting started with travis ci — this is probably the easiest ci tool to get started with and has good integration with web tools like github and node. to get started, see for example: travis ci for complete beginners building a node.js project (with travis) using lambdatest with travis ci using lambdtest with circleci usi...
Deploying our app - Learn web development
that tests are not limited to javascript; tests can be run against the rendered dom, user interactions, css, and even how a page looks. however, for this project we’re going to create a small test that will check the third-party nasa data feed and ensure it's in the correct format. if not, the test will fail and will prevent the project from going live. to do anything else would be beyond the scope of this module — testing is a huge subject that really requires its own separate module. we are hoping that this section will at least make you aware of the need for testing, and will plant the seed that inspires you to go and learn more. although the test for this project does not include a test framework, as with all things in the front-end development world, there are a slew of framework op...
Introducing a complete toolchain - Learn web development
parcel-bundler using future features the code for our project is using some new web features including features that are so new they aren't fully standardised yet. for example, instead of reaching for a tool like sass, this particular project uses the w3c proposal for css nesting. css nesting allows us to nest css selectors and properties inside one another thus creating more specific selector scope. sass was one of the first preprocessors to support nesting (if not the first) but now after many years, nesting looks like it will soon be standardised, which means that we will have it available in our browsers without needing build tools. until then, parcel will do the transformation between nested css and natively supported css with the help of postcss, which parcel works with out of the box...
Chrome Worker Modules
your module initialization is complete. the module loader supports cyclic calls to require(). however, if you have cyclic requirements, some of the modules involved in the cyclic requirements may become visible by the other modules before they are fully evaluated. no attempt is made to fully isolate modules from each other. in particular, globals (string, math, object, self) and the worker global scope itself (this) are shared between workers. in other words, the true isolation unit is the worker itself, not the module. ...
How Mozilla's build system works
is just the default framework we've established for our build system. legacy content the content below is considered legacy. it is preserved for historical reasons until this entire page is rewritten. makefile basics makefiles can be quite complicated, but mozilla provides a number of built-in rules that should enable most makefiles to be simpler. complete documentation for make is beyond the scope of this document but is available here. one concept you will need be familiar with is variables in make. variables are defined by the syntax variable = value, and the value of a variable is referenced by writing $(variable). all variables are strings. all makefile.in files in mozilla have the same basic format: depth = ../../../.. topsrcdir = @top_srcdir@ srcdir = @sr...
ESLint
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 to the whole directory. my script is a frame-script, or includes items that loaded into content scripts: add a line to tell eslint to use the frame-script environment: /* eslint-env mozilla/frame-script */ my script is a w...
Cross Process Object Wrappers
ome process runs the firefox ui, any responsiveness problems affect the whole browser. by making the chrome process block on the content process, cpows break this principle and allow unresponsive content process to make the whole browser unresponsive. see safe and unsafe cpows for more on this. performance although the wrapper looks just like an object completely contained in the chrome script scope, it's really just a reference to an object in the content process. when you access a property of the wrapper, it sends a synchronous message to the content process and returns the result. this means it is many times slower to use than an object. message ordering cpows can violate assumptions you might make about message ordering. consider this code: mm.addmessagelistener("gotloadevent", functi...
Process scripts
process scripts are new in firefox 38. if you're using the addon sdk you can use the remote/parent module's remoterequire instead. when you need to run code in the content process in order to access web content, then you should use frame scripts. however, a problem with frame scripts is that they can be loaded multiple times in the content process, in multiple scopes that are insulated from each other. for example, if you call the global frame message manager's loadframescript() function, then the script will be loaded separately into all open tabs. this can then cause a problem the frame scripts are interacting with a global service in the content process. for example, in multiprocess firefox, if you need to use nsicontentpolicy to register a content policy, you must do this in ...
Message manager overview
agers are designed to enable code in one process to communicate with code in a different process. at the top level, there are two different sorts of message managers: frame message managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) in the content process. these scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. if chrome code wants to run code in the content process so it can access web content, this is usually the sort of message manager to use. process message managers: these correspond to process boundaries, and enable code running in the parent (chrome) process to communicate with code running in the child (content) process. from firefox 38 onwards, they also enable co...
Performance best practices for Firefox front-end engineers
tions to figure out which css styles will apply to each element. this happens the first time the page loads and the css is initially applied, but can happen again if javascript modifies the dom. javascript code might, for example, change dom node attributes (either directly or by adding or removing classes from elements), and can also add, remove, or delete dom nodes. because styles are normally scoped to the entire document, the cost of doing these style calculations is proportional to the number of dom nodes in the document (and the number of styles being applied). it is expected that over time, script will update the dom, requiring us to recalculate styles. normally, the changes to the dom just result in the standard style calculation occurring immediately after the javascript has finished...
Chrome-only API reference
Mozilla › Gecko › Chrome › API
chrome code on firefox desktop (version 47 and above).chromeworkerif you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object. it works exactly like a standard worker, except that it has access to js-ctypes via a global ctypes object available in the global scope of the worker. examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below. to use a postmessage with callback version of chromeworker that features promises, see promiseworker. ...
Overview of Mozilla embedding APIs
ll. x, y, cx, cy); // initial dimensions... if (ns_failed(rv)) return rv; // create the child window for the webbrowser. rv = basewindow->create(); if (ns_failed(rv)) return rv; // at this point webbrowser contains the new initialized instance // of the nswebbrowser component... // save webbrowser before it goes out of scope :-) web navigation the nsiwebnavigation interface is used to load uris into the webbrowser and provide access to session history capabilities - such as back and forward. clipboard the webbrowser exposes access to the system clipboard via the nsiclipboardcommands interface. this interface supports cut/copy/paste operations on the current selection within the webbrowser window. printing (not yet ...
Embedding Tips
eturn 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 want to create your component multiple times within the browser window, you can use a javascript constructor instead of a javascript property: catman->addcategoryentry("javascript global constructor", "my_prop_name", "my_prop_contract_id", pr_true, pr_true, getter_copies(previous)); that way you will be able to do: var my_comp = new my...
IPDL Tutorial
see ipdl processes and threads for more details. because protocol messages are represented as c++ methods, it's easy to forget that they are in fact asynchronous messages: by default the c++ method will return immediately, before the message has been delivered. the parameters of the recv* methods (const nscstring& pluginpath in the example) are references to temporary objects,...
Addon
-on. operations my be restricted based on system policies (e.g., the system administrator may not allow certain add-ons to be uninstalled), add-on type (e.g., themes may not be disabled), or add-on state (e.g., an incompatible add-on cannot be enabled). providesupdatessecurely read only boolean true if the add-on has a secure means of updating or cannot be updated at all. scope read only integer indicates what scope the add-on is installed in, per profile, user, system, or application. type read only string the type of the add-on. userdisabled boolean true if the user wants this add-on to be disabled. version read only string the version of the add-on. optional properties attribute type descrip...
Assert.jsm
the assert.jsm javascript code module 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. 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. method overview undefined ok(value, message); undefined equal(actual, expected, message); undefined notequal(actual, expected, message); undefined deepequal(actual, expected, message); undefined notdeepequal(actual, expected, message); undefined strictequal(actual, expected, message); ...
DeferredTask.jsm
firefox 28 note interface was changed in firefox 28, and old methods were removed. the deferredtask.jsm javascript code module offers utility routines for a task that will run after a delay. multiple attempts to run the same task before the delay will be coalesced. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/deferredtask.jsm"); use this, for instance, if you write data to a file and you expect that you may have to rewrite data very soon afterwards. with deferredtask, the task is delayed by a few milliseconds and, should a new change to the data occur during this period, only the final version of the data is actually written; a further grace delay is added to take into account other chan...
Dict.jsm
introduced in firefox 5, this is now obsolete and has been removed in firefox 40: use es2015 map. the dict.jsm javascript code module offers routines for managing dictionaries of key/value pairs. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/dict.jsm"); creating a dictionary you can create a new, empty dictionary by simply calling the dict() constructor: var newdict = new dict(); if you wish, you may also pass in an object literal of key/value pairs with which to initialize the dictionary: var someobj = {}; var newdict = new dict({key1: "foo", key2: someobj}); note that values may be any javascript object type. note: you can actually specify non-strings as keys; these are converted to strings...
DownloadLastDir.jsm
the downloadlastdir.jsm javascript code module lets you retrieve the path of the last directory into which a download occurred. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloadlastdir.jsm"); if you are using addon sdk, you can import the code module as: let { cu } = require("chrome"); let downloadlastdir = cu.import("resource://gre/modules/downloadlastdir.jsm").downloadlastdir; once you've imported the module, you can then use the downloadlastdir object it exports. using the downloadlastdir object to determine or set the path into which the last download occurred: // file is an nsifile var file = downloadlastdir.file; downloadlastdir.file = file; you can also set and retrieve this information ...
Downloads.jsm
the downloads.jsm javascript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloads.jsm"); method overview promise<download> createdownload(object aproperties); promise<void> fetch(asource, atarget, [optional] object aoptions); promise<downloadlist> getlist(atype); promise<downloadsummary> getsummary(atype); constants constant description public work on downloads that were not started from a private browsing window. pri...
FileUtils.jsm
the fileutils.jsm javascript code module offers utility routines dealing with files. ...
Geometry.jsm
the geometry.jsm javascript code module provides routines for performing common geometry operations on points and rectangles. it exports two classes: point and rect. to use these routines, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/geometry.jsm"); once you've imported the module, you can then use the point and rect classes. note: although this module is usable from mobile, and is present in firefox 4, it's currently not used in firefox 4 and attempting to use it may produce unreliable results there. ...
ISO8601DateUtils.jsm
the iso8601dateutils.jsm javascript code module provides methods that make it easy to convert javascript date objects into iso 8601 format date strings and back. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/iso8601dateutils.jsm"); once you've imported the module, you can then use the iso8601dateutils object it exports. using the iso 8601 date utilities to convert a date string into a date object, simply use: dateobj = iso8601dateutils.parse(datestring); to convert a date object into a date string: datestring = iso8601dateutils.create(dateobj); method overview string create(adate); date parse(adatestring); methods create creates an iso 8601 format date string, e.g. "2010-05-15t13:45:00z", from a java...
Log.jsm
different interfaces and behavior in different versions of the platform. progress is tracked in bugzilla using dependencies of bug 451283. the log.jsm javascript code module (formerly named log4moz.js) provides a log4j style api for logging log messages to various endpoints, such as the browser console or a file on disk. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/log.jsm"); basic usage components.utils.import("resource://gre/modules/log.jsm"); // get a logger, give it a name unique to this chunk of code. // use dots to create a hierarchy, this way you can later change // the log level of sets of loggers under some common root let log = log.repository.getlogger("myextension.myclass"); log.level = log.l...
NetUtil.jsm
the netutil.jsm javascript code module provides easy-to-use apis for performing common network related tasks. to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods. method overview nsiasyncstreamcopier asynccopy(nsiinputstream asource, nsioutputstream asink, [optional] acallback) void asyncfetch(asource, acallback) nsichannel newchannel(awhattoload, [optional] aorigincharset, [optional] nsiuri abaseuri) nsiuri newuri(atarget, [optional] aorigincharset, [optional] nsiuri abaseuri) string readinputstreamtostring(ainputstream, acount, aoptions) attributes attrib...
PerfMeasurement.jsm
the perfmeasurement.jsm javascript code module lets you take detailed performance measurements of your code. note: the perfmeasurement.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on. before you can use this module, you need to import it into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") see measuring performance using the perfmeasurement.jsm code module for details on how to use this api. note: at present, perfmeasurement.jsm is only functional on linux, but it is planned to add support for windows (bug 583322) and osx (bug 583323) as well, and we welcome patches for other operating systems. method overview static bool canmeasuresomething(); void reset(); void start(); void stop(...
PopupNotifications.jsm
the popupnotifications.jsm javascript code module provides a popup notification box service. this service is used, for example, to display geolocation related notifications. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/popupnotifications.jsm"); once you've imported the module, you can then use the popupnotifications object it exports; this object provides methods for creating and displaying popup notification panels. note: this code module is imported by firefox chrome windows, so you don't have to do it yourself in most extensions. method overview void locationchange(); notification getnotification(id, browser); void remove(notification); notification show(browser,...
Promise.jsm
module was used before dom promises were made globally available in gecko 29. its usage is not suggested for new code. if you just need a promise, consider using a dom promise instead. if you need a deferred, because you want to create a promise and manually resolve or reject it, consider using promiseutils.jsm instead. ...
PromiseUtils.jsm
this method was previously implemented as promise.defer(), which is obsolete since gecko 30. and promiseutils.defer uses dom promise instead of promise.jsm's promise. deferred defer(); parameters none. ...
Services.jsm
the services.jsm javascript code module offers a wide assortment of lazy getters that simplify the process of obtaining references to commonly used services. to use it, you first need to import the code module into your javascript scope: const {services} = chromeutils.import("resource://gre/modules/services.jsm"); then you can obtain references to services by simply accessing them from the services object exported by the code module. for example, to obtain a reference to the preferences service: var prefsservice = services.prefs; provided service getters service accessor service interface service name androidbridge nsiandroidbridge 1 appinfo nsixulappinfo nsixulruntime application information service appshell nsiappshellservi...
Sqlite.jsm
and read. javascript-y api. sqlite.jsm feels like a pure javascript module. the complexities of xpcom are mostly hidden from view. javascript programmers should feel right at home using sqlite.jsm. note: the sqlite.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on. before you can use this module, you need to import it into your scope: components.utils.import("resource://gre/modules/sqlite.jsm") obtaining a connection sqlite.jsm exports the sqlite symbol. this symbol is an object with a single function: openconnection. this function takes an object defining connection options: path (required) the database file to open. this can be an absolute or relative path. if a relative path is given, it is interpreted as relative t...
Task.jsm
tasks are built upon generator functions and promises. ...
Using workers in JavaScript code modules
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. ...
openLocationLastURL.jsm
this component has been removed from the platform in firefox 29. (bug 953124) the openlocationlasturl.jsm javascript code module lets you set and retrieve the url most recently opened using the "open location" option in the file menu. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource:///modules/openlocationlasturl.jsm"); once you've imported the module, you can then use the openlocationlasturl object it exports. this object lets you fetch and change the url that is placed in the "open location" dialog box when it opens. if the user is not in private browsing mode, this automatically updates the value of the general.open_location.last_url preference. note: this module automatically handles private browsing mode for you. the...
source-editor.jsm
this component has been removed from the platform in firefox 28. the source-editor.jsm javascript code module implements an editor specifically tailored for editing source code; its primary purpose is to provide support for web developer tools to display and edit web site code. the editor provided is eclipse orion. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource:///modules/source-editor.jsm"); warning: much of the functionality of the source editor is implemented by a secondary code module (by default, source-editor-orion.jsm). you must not directly import that code module; it is essentially an implementation detail. its functionality is all exposed through source-editor.jsm. method overview initialization and dest...
JavaScript code modules
for example, a module could be used by firefox itself as well as by extensions, in order to avoid code duplication. general topics using javascript code modules an introduction to how to use javascript code modules. components.utils.import how to import a javascript code module. components.utils.unload how to unload a javascript code module. ...
Localization sign-off reviews
y generating a diff between the new release revision being considered and the previously approved release revision. focuses on technical accuracy and completion of l10n work, not translation quality. evaluates new release revisions, not entire l10n repos. does not need to be approved before revision merge between release channels, although it is recommended. sign-off review criteria since the scope of each qa review process varies, the criteria used to evaluate a localizer's work also varies. in principle, they share basic elements, but sign-off reviews are only for evaluating the changes between your latest approved revision and the new revision you've submitted for release approval. hence, unless a localizer makes a change within the new revision that nullifies the approved work in the pr...
Mozilla MathML Status
t schemata element [- attribute] notes msub implemented. msup implemented. msubsup implemented. munder implemented. mover implemented. munderover implemented. mmultiscripts implemented. tabular math element [- attribute] notes mtable implemented. mtable - alignmentscope not implemented. see bug 122253. mtable - columnspacing, rowspacing, framespacing implemented. see bug 330964. mtable - columnwidth not implemented. see bug 958953. mtable - equalrows, equalcolumns not implemented. see bug 958954. mtable - side, minlabelspacing not implemented. see bug 356870. mtr implemented. mlabeledtr n...
mozilla::MonitorAutoEnter
mozilla::monitorautoenter is an raii helper for mozilla::monitor. it is designed to make using mozilla::monitor safer and easier. to use mozilla::monitorautoenter, declare and initialize it with a reference to a mozilla::monitor. the mozilla::monitorautoenter constructor will enter() the underlying mozilla::monitor automatically. when the mozilla::monitorautoenter goes out of scope, its destructor will exit() the underlying mozilla::monitorautoenter. important: when a mozilla::monitorautoenter is live on the stack, your code is guaranteed to own the underlying mozilla::monitor. constructors monitorautoenter( in mozilla::monitor& monitor; ); this parameter is a reference so as to guarantee that your code has already properly constructed the mozilla::monitor. methods wait() nsresult wait( ...
mozilla::MutexAutoLock
mozilla::mutexautolock is an raii helper for mozilla::mutex. it is designed to make using mozilla::mutex safer and easier. to use mozilla::mutexautolock, declare and initialize it with a reference to an mozilla::mutex. the mozilla::mutexautolock constructor will lock() the underlying mozilla::mutex automatically. when the mozilla::mutexautolock goes out of scope, its destructor will unlock() the underlying mozilla::mutex. because of mozilla::mutexautounlock, the rule for determining if your code owns the mutex underlying the mutexautolock is slightly more complicated than that for monitorautoenter. this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautolock is the mutex raii wrapper most recently pushed on t...
mozilla::MutexAutoUnlock
mozilla::mutexautounlock is an raii helper for mozilla::mutex. it is designed to make using mozilla::mutex safer and easier. to use mozilla::mutexautounlock, declare and initialize it with a reference to a locked mozilla::mutex. the mozilla::mutexautounlock constructor will unlock() the underlying mozilla::mutex automatically. when the mozilla::mutexautounlock goes out of scope, its destructor will lock() the underlying mozilla::mutex. because of mozilla::mutexautolock, the rule for determining if your code does not own the mutex underlying the mutexautounlock is slightly more complicated than that for monitorautoenter. this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautounlock is the mutex raii wrapper m...
DMD
fig.common: moz_crashreporter_upload_full_symbols=1 launch on a local build, use mach run --dmd; use --mode to choose the mode. on a build done by the try server, follow these instructions instead. trigger follow the trigger instructions for linux. fennec in order to use dmd on fennec you will need root access on the android device. instructions on how to root your device is outside the scope of this document. build build with these options: ac_add_options --enable-dmd prep in order to prepare your device for running fennec with dmd enabled, you will need to do a few things. first, you will need to push the libdmd.so library to the device so that it can by dynamically loaded by fennec. you can do this by running: adb push $objdir/dist/bin/libdmd.so /sdcard/ second, you will n...
A brief guide to Mozilla preferences
l10n.js - defaults specific to the installed language of firefox. none of the other preference files contain locale-specific preferences. config. file a configuration file, usually with .cfg extension, may be called from a default pref file via the general.config.filename preference. this file allows preference locking via the lock_pref() function. details on the config file is beyond the scope of this document. user pref. files in the profile directory are two user pref files: prefs.js and user.js. prefs.js is automatically generated by the application and should not be edited manually, whereas user.js is an optional file the user can create to override preferences initialized by other preferences files. preferences loading and resolution on application launch, the applic...
NSPR's Position On Abrupt Thread Termination
a is recorded only on the stack, known only to the single thread (normally referred to as encapsulated). the problem with abrupt termination is that it can happen at any time, to a thread that is coded correctly to handle both normal and exceptional situations, but will be unable to do so since it will be denied the opportunity to complete execution. it can happen because it called out of its own scope into some lazily implemented library. nspr's answer to this is that there is no abrupt thread termination. all threads must unwind and return from their root function. if they cannot, because of some state corruption, then they must assume 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 th...
NSPR API Reference
s miscellaneous types size type pointer difference types boolean types status type for return values threads threading types and constants threading functions creating, joining, and identifying threads controlling thread priorities controlling per-thread private data interrupting and yielding setting global thread concurrency getting a thread's scope process initialization identity and versioning name and version constants initialization and cleanup module initialization locks lock type lock functions condition variables condition variable type condition variable functions monitors monitor type monitor functions cached monitors cached monitor functions i/o types directory type file descript...
Index
s name, an ip address, and a uri. issueraltnames non-critical name-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names * add crl number extension: the crl number is a non-critical crl extension which conveys a monotonically increasing sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. * add revocation reason code extension: ...
NSS tools : crlutil
mail address), a dns name, an ip address, and a uri. issueraltnames non-critical name-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names * add crl number extension: the crl number is a non-critical crl extension which conveys a monotonically increasing sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. * add revocation reason code extension: the reasoncode is a ...
NSS Tools crlutil
. issueraltnames non-critical name-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names add crl number extension: the crl number is a non-critical crl extension which conveys a monotonically increasing sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. add revocatio...
NSS tools : crlutil
Mozilla › Projects › NSS › tools › crlutil
s name, an ip address, and a uri. issueraltnames non-critical name-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names * add crl number extension: the crl number is a non-critical crl extension which conveys a monotonically increasing sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. * add revocation reason code extension: ...
Necko walkthrough
ritesegment passes bytes from msocketin->read to the transaction's pipe nspipeoutputstream::writesegments nspipe::advancewritecursor nspipeinputstream::oninputreadable so now the response is hitting the other end of the pipe, saying it has bytes to read nspipeevents::notifyinputready puts the callback object into an nspipeevents object. once this object goes out of scope, mcallback->oninputstreamready is called. note: this callback may be a proxy object, nsinputstreamreadyevent: it is a runnable that dispatches itself to a previously set target thread, and calls its internal mcallback->oninputstreamready function. remember that nspipeinputstream::asyncwait was called earlier, after the transaction was initially created and posted to the connection manage...
Rhino documentation
ng scripts running in rhino. javascript compiler compiling scripts into java class files. running the rhino tests running the javascript test suite with rhino. embedding rhino embedding tutorial a short tutorial on how to embed rhino into your application. api javadoc reference (link broken? try this at jarvana.) an annotated outline of the programming interface to rhino (tip only). scopes and contexts describes how to use scopes and contexts for the best performance and flexibility, with an eye toward multithreaded environments. serialization how to serialize javascript objects and functions in rhino. runtime a brief description of the javascript runtime. small footprint hints for those interested in small-footprint embeddings. examples a set of examples showing how to c...
Rhino Examples
t programs; it is a simplified version of the shell in the tools package. the programs may be specified as files on the command line or by typing interactively while the shell is running. primitivewrapfactory primitivewrapfactory.java is an example of a wrapfactory that can be used to control the wrapping behavior of the rhino engine on calls to java methods. multithreaded script execution dynamicscopes.java is a program that creates a single global scope object and then shares it across multiple threads. sharing the global scope allows both information to be shared across threads, and amortizes the cost of context.initstandardobjects by only performing that expensive operation once. implementing host objects first check out the tutorial if you haven't already. the foo class - extending scripta...
Scripting Java
java.awt.point, java.awt.rectangle, java.awt.dimension); ... with (swinggui) { var mybutton = new jbutton(test); var mypoint = new point(10, 10); var myframe = new jframe(); ... } previously such functionality was available only to embeddings that used org.mozilla.javascript.importertoplevel class as the top level scope. the class provides additional importpackage() and importclass() global functions for scripts but their extensive usage has tendency to pollute the global name space with names of java classes and prevents loaded classes from garbage collection. see bugzilla 245882 for details. java exceptions exceptions thrown by java methods can be caught by javascript code using try...catch statement. rhino...
SpiderMonkey Build Documentation
mingw32 note: you must have started your mozillabuild shell with the proper -x64.bat script in order for the 64-bit compilers to be in your path. whatever compiler and flags you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure. building your application while "how to build your complete application" is clearly out of scope for this document, here are some tips that will help get you on your way: the spidermonkey developers frequently and deliberately change the jsapi abi. you cannot use headers built for one version/configuration of jsapi to create object files which will be linked against another. support for js_threadsafe was recently removed, and threadsafe builds are now enabled by default. the js-config s...
GC Rooting Guide
ferent 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. there are some situations when using js::rooted<t> is not possible, or is undesirable for performance reasons. to c...
Exact Stack Rooting
r, nicely maintaining our lifo property. however, this does not hold true for temporaries: they are undeclared, after all. some compilers maintain lifo order, some do not. incorrect use of js::rootedt as a temporary will crash at run time. there is also a static constructor method frommarkedlocation() that creates a handle from an arbitrary location. this is used to make handles for things like scope chain objects, which aren't explicitly rooted themselves, but are always reachable from the implicit stack roots. every use of these should be commented to explain why they are guaranteed to be rooted. js::handle<t> typedef js::handle<t> js::handlet; -> handleobject, handlestring, handlescript, etc. any single gcthing is likely to get passed through a fairly deep call-stack before getting use...
Self-hosted builtins in SpiderMonkey
since firefox 17, spidermonkey has the ability to self-host built-in functions in javascript. these docs describe the current state as of nightly 45. differences from normal javascript all self-hosted code is strict, so self-hosted functions invoked in a null or undefined scope won't be run in the scope of the global object. self-hosted code has access to some functionality that's not available to normal js code. most importantly, it's possible to invoke any function within the scope of any object using the syntax callfunction(fun, receiver, ...args) (or callcontentfunction, see below), which causes fun to be called within the scope of receiver with ...args as its arguments. in contrast to function.prototype.call, this syntax makes it impossible for other code to interfere and gets compil...
Introduction to the JavaScript shell
you can use either from javascript programs or in interactive mode. note: this list is incomplete and overlaps with shell global objects. see js/src/shell/js.cpp (around shell_functions) for more. build() returns the date and time at which the javascript shell was built. note: clear() with no parameters really clears everything. this includes all these built-in functions. clone(function, [scope]) clones the specified function object. if scope isn't specified, the new object's parent is the same as the original object's. otherwise, the new object is placed in the scope of the object specified by scope. countheap([start[, kind]]) added in spidermonkey 1.8 count the number of live gc things in the heap, or things reachable from start when it is given and is not null. kind is either 'all...
JIT Optimization Outcomes
emove one of the object's properties. singleton one of the types present in the typeset was a singleton type, preventing the optimization from being enabled. notsingleton optimization failed because the object containing the property did not have a 'singleton' type. singleton types are assigned to objects that are "one of a kind", such as global objects, literal objects declared in the global scope, and top-level function objects. notfixedslot the property being accessed is not stored at a known location in the object. this can occur if one of the expected types of objects to be used in this operation has unknown properties, or if different instances of the object store the property at different locations (for example, some instances have the property assigned in a different order than ot...
JSAPI Cookbook
ing(somestring); // or: v = js::stringvalue(somestring); v.setnull(); // or: v = js::nullvalue(); v.setundefined(); // or: v = js::undefinedvalue(); v.setboolean(false); // or: v = js::booleanvalue(false); finding the global object many of these recipes require finding the current global object first. // javascript var global = this; there is a function, js_getglobalforscopechain(cx), that makes a best guess, and sometimes that is the best that can be done. but in a jsnative the correct way to do this is: /* jsapi */ bool mynative(jscontext *cx, unsigned argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); jsobject *global = js_getglobalforobject(cx, &args.callee()); ... } defining a function // javascript function justforfun() { ...
JS::AutoIdArray
lease the ownership. description js::autoidarray takes the ownership of jsidarray, and frees it in destructor by calling js_destroyidarray. examples { js::autoidarray ids(cx, js_enumerate(cx, obj)); if (!ids) // check the returned value from js_enumerate return false; for (int32_t i = 0, len = ids.length(); i < len; i++) { somefunc(cx, ids[i]); } /* when leaving this scope, the jsidarray returned by js_enumerate is freed. */ } see also mxr id search for js::autoidarray jsidarray js_destroyidarray js_enumerate bug 332648 ...
JS::CompileOptions
ompileoptions instance is allocated on the stack, and holds non-owning references to non-pod option values: strings; principals; objects; and so on. the code declaring the instance guarantees that such option values will outlive the compileoptions itself: objects are otherwise rooted; principals have had their reference counts bumped; strings will not be freed until the compileoptions goes out of scope. in this situation, compileoptions only refers to things others own, so it can be lightweight. in some cases, however, we need to hold compilation options with a non-stack-like lifetime. for example, js::compileoffthread needs to save compilation options where a worker thread can find them, and then return immediately. the worker thread will come along at some later point, and use the options. ...
JS::CurrentGlobalOrNull
name type description cx jscontext * the context for which to return the global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js::currentglobalornull() returns the global object for whatever function is currently running on the context. in other words, it returns the global object on the current scope chain. if there is no javascript running on the context, this returns the context's global, i.e., js_getglobalobject(cx). note that js_getglobalobject() and context globals are becoming obsolete. see also mxr id search for js::currentglobalornull js_getglobalforobject bug 899245 ...
JSClass.flags
nd js_setreservedslot. (the jsclass.reserveslots hook also allocates reserved slots to objects.) mxr id search for jsclass_has_reserved_slots jsclass_global_flags this flag is only relevant for the class of an object that is used as a global object. (ecmascript specifies a single global object, but in spidermonkey the global object is the last object in the scope chain, which can be different objects at different times. this is actually quite subtle. js_executescript and similar apis set the global object for the code they execute. js_setglobalobject sets an object which is sometimes used as the global object, as a last resort.) enable standard ecmascript behavior for setting the prototype of certain objects, such as function objects. if the global o...
JSDeletePropertyOp
see also mxr id search for jsdeletepropertyop bug 858677 jsclass ...
JSGetObjectOps
lows for a higher level of operation, which does not use the object's class except to find the class's jsobjectops struct, by calling clasp->getobjectops, and to finalize the object. if this seems backwards, that's because it is! api compatibility requires a jsclass *clasp parameter to js_newobject, etc. most host objects do not need to implement the larger jsobjectops, and can share the common jsscope code and data used by the native (js_objectops, see jsobj.c) ops. further extension to preserve api compatibility: if this function returns a pointer to jsxmlobjectops.base, not to jsobjectops, then the engine calls extended hooks needed for e4x. jsclass hooks jsclass offerd following hook: the jsclass.getobjectops hook is called each time an object is created. it returns a pointer to a js...
JSObjectPrincipalsFinder
sume check. for example, when a watchpoint triggers, the engine calls the callback, passing the watchpoint handler, to ensure that watchpoint handlers are invoked only when the watcher is permitted to watch the currently executing script. another example: when the function constructor is called, the javascript engine calls the object principals finder callback to obtain principals for the local scope object, to check that the caller has access to that object. the two debugger functions js_stackframeprincipals and js_evalframeprincipals also use this callback. since it is very common for jsobjectops.checkaccess or 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...
JS_AliasElement
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_deleteelement js_getarraylength js_getelement js_isa...
JS_AliasProperty
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_defineproperty js_definepropertywithtinyid js_deleteproperty js_getprop...
JS_CloneFunctionObject
ormation. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. funobj jsobject * the function to clone. parent jsobject * the new function's parent. description js_clonefunctionobject creates a new function object from funobj. the new object has the same code and argument list as funobj, but uses parent as its enclosing scope. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. the new object's prototype is function.prototype; js_newobject: choosing a default prototype explains exactly how this is computed. js_clonefunctionobject takes care to choose a prototype that shares a global object with the given parent whenever possible. funobj must...
JS_CompileScript
script); 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. obj js::handleobject the global object, or null. if the jsoption_compile_n_go option is set in cx, the resulting script must be executed in this scope, and at most once. obsolete since jsapi 39 ascii or chars const char * or const char16_t * string containing the script to compile. length size_t the length, in characters, of source. options js::compileoptions &amp; compile options. script js::mutablehandlescript out parameter. on success, script receives the result script. descr...
JS_ConvertArguments
ely useless, because the resulting jsfunction is not a real function object and therefore cannot be safely passed to any other jsapi function. that includes js_callfunction() and js_getfunctionobject(). a jsfunction represents only the compiled code and not the environment of the function. unless the function happens to be a native function, this means it isn't attached to 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. v jsval argument value (no conversion) * n/a none. if an asterisk (*) is present in format, it tells the conversion routine to skip c...
JS_ConvertValue
outines based on the type argument. converting any value to jstype_void always succeeds. the result is undefined value. converting to jstype_object works exactly like js::toobject if v.isnullorundefined() is false, otherwise the result is nullptr. converting to jstype_function works like js_valuetofunction, but better: the result 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 u...
JS_DeleteElement
element 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
om 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_DeleteProperty
return true on success, regardless of whether a property was actually deleted, and false on error or exception. (in javascript 1.2 and earlier, attempting to delete a permanent property caused an error. there is no longer any way to get this behavior.) internally, property deletion is implemented by the jsobjectops.deleteproperty callback. to remove all properties from an object, call js_clearscope. see also mxr id search for js_deleteproperty mxr id search for js_deletepropertybyid js_deleteproperty2 js_deletepropertybyid2 bug 461163 bug 1113369 -- added result parameter and js_deleteucproperty ...
JS_DeleteProperty2
dless of whether a property was actually deleted. on error or exception, the return value is false, and the value left in *succeeded is unspecified. jsobjectops.deleteproperty implements this behavior. (in javascript 1.2 and earlier, attempting to delete a permanent property caused an error. there is no longer any way to get this behavior.) to remove all properties from an object, call js_clearscope. see also mxr id search for js_deleteproperty2 mxr id search for js_deleteucproperty2 mxr id search for js_deletepropertybyid2 bug 461163 bug 1113369 -- renamed to js_deleteproperty ...
JS_ExecuteScriptPart
jsexec_prolog, jsexec_main } jsexecpart; jsbool js_executescriptpart( jscontext *cx, jsobject *obj, jsscript *script, jsexecpart part, jsval *rval); name type description cx jscontext * the context in which to execute the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * the scope in which to execute the script. this parameter is documented in detail at js_executescript. script jsscript * the compiled script to execute. part jsexecpart the part of script to execute. rval jsval * out parameter. on success, *rval receives the value from the last executed expression statement in the script. description js_executescriptpart ex...
JS_GetParent
date, d has the same parent as date, ordinarily the global object. an object created by a script via implicit conversion (the ecmascript toobject operator), an object initializer ({a: 1, b: 2}), or an array initializer ([1, 2, 3]), has the global object as its parent. the parent of a function created by evaluating a function declaration or function expression in a script depends on the lexical scope of the function. if there is no enclosing function, with statement, or block scope, then the function's parent is the global object. otherwise, the parent is implementation-defined. it may be a call, with, or block object representing the function's dynamic scope, or it may be the global object. in any case the global object is guaranteed appear on the new function's parent chain. the initia...
JS_NewGlobalObject
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 mxr id search for js_newglobalobject mxr id search for onnewglobalhookoption bug 897322 bug 880917 bug 759585 bug 570040 bug 755186 bug 1239666 - options is no longer optional ...
JS_NewObject
supply one yourself. if the new object's class (here, clasp) is a built-in class, then its associated prototype is used as the new object's prototype. otherwise, object.prototype is used as the new object's prototype. previous behaviour obsolete since jsapi 45 here's how the process works in detail: first, we must identify a global object. if the parent is non-null, we assume it is part of a scope chain, walk to the end of that chain, and use the global object we find there. if the parent is null, we use the global object at the end of the scope chain in which the context is currently executing. in other words, the context's current scope acts as a default parent. if the context is not currently executing any code, we use js_getglobalobject to find a global object associated with the con...
JS_NewScriptObject
ry jsscript object has an associated jsobject script object. as long as the script object is reachable, the jsscript and its components are protected from garbage collection; when the script object is collected, the jsscript and its contents are freed. once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using js_addroot or js_enterlocalrootscope). a script object has no properties, and its prototype is object.prototype. so a script object can be used to expose a jsscript to javascript code, but the code can't do much of anything with it. on success, js_newscriptobject returns a pointer to the script's object. otherwise it returns null. (the name "js_newscriptobject" suggests that the script object is freshly allocated; this was the ca...
JS_ValueToFunction
ely useless, because the resulting jsfunction is not a real function object and therefore cannot be safely passed to any other jsapi function. that includes js_callfunction() and js_getfunctionobject(). a jsfunction represents only the compiled code and not the environment of the function. unless the function happens to be a native function, this means it isn't attached to 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. if v is null, undefined, a boolean, a number, or a string, a typeerror is reported and js_valuet...
JSDBGAPI
pctolinenumber js_linenumbertopc js_getfunctionscript js_getfunctionnative js_getfunctionfastnative js_getscriptprincipals typedef jsstackframe js_frameiterator js_getframescript js_getframepc js_getscriptedcaller js_stackframeprincipals js_evalframeprincipals js_getframeannotation js_setframeannotation js_getframeprincipalarray js_isnativeframe js_getframeobject js_getframescopechain js_getframecallobject js_getframethis js_getframefunction js_getframefunctionobject js_isconstructorframe js_isdebuggerframe js_getframereturnvalue js_setframereturnvalue js_getframecalleeobject js_getscriptfilename js_getscriptbaselinenumber js_getscriptlineextent js_getscriptversion js_gettopscriptfilenameflags js_getscriptfilenameflags js_flagscriptfilenameprefix ...
Zest implementation
the first version of zest has been released but is intentionally very basic. future versions of zest are planned which will significantly increase the scope of the language. the first version is aimed at creating scripts for reproducing basic security vulnerabilities includes a java reference implementation, which conforms to jsr 223 has been included in a proof-of-concept owasp zap add-on the next version is underdevelopment - more details soon. related links zest overview ...
Using RAII classes in Mozilla
raii classes are useful when two operations (e.g., lock/unlock, addref/release, pushstate/popstate) must be paired. ensuring raii classes are not used as temporaries a common mistake when using raii classes is to accidentally forget to name object, which causes its scope to be different from what is intended. for example, instead of writing: autolock lock(mmutex); which causes the lock to be held until the end of the block, one might write: autolock(mmutex); which erroneously causes the lock to be released 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 ...
A Web PKI x509 certificate primer
be a root or an intermediate for another root in the browsers key store (when roots create intermediates for each other it is called cross-signing). extensions while rfc 5280 defines 16 extensions for webpki in this document we will be describing the six extensions we considered critical for understanding. certificates can have other extensions not described on rfc 5280, but that is out of the scope of this document. extensions can be marked as critical or non-critical, conforming certificate verification libraries should stop processing verification when encountering a critical extension that they do not understand ( and should continue processing if the extension is marked as non-critical) mozila::pkix has this behavior. subject alternate name this extension defines what other names (suc...
Aggregating the In-Memory Datasource
asopurce> ds = do_queryinterface(minner); rv = ds->assert(/* something useful here */); // etc... return ns_ok; } it may be tempting to keep a pointer to the aggregate's nsirdfdatasource in a member variable, butyou can't do that. why? because if you did, you'd hold a circular reference that would never unwind. notes describing all of the vagaries of xpcom aggregation is beyond the scope of this document. the basic idea is to overload queryinterface(), allowing it to return adelegate object that supports the interface. there is some trickery involved on the delegate's part to ensure that reference counting is done sanely, and that the reflexive, symmetric, and transitive properties of queryinterface() are preserved. if you're really interested, i'd recommend reading about it in a...
Building the WebLock UI
lock.lock(); wlocked = 1; } function wunlock() { // check to see if locking is on or off weblock.unlock(); wlocked = 0; } an important preliminary of these functions is that the weblock component be made available to the javascript in the form of the weblock object being used in the snippets above. as you can see, weblock is initialized as a global javascript variable, available in the scope of these functions and others: var weblock = components.classes["@dougt/weblock"] .getservice() .queryinterface(components.interfaces.iweblock); in addition to this basic setup, you must also write javascript that uses the addsite method to add new sites to the white list. this is a bit more complicated, because it requires that you work with the...
Setting up the Gecko SDK
e for unix on linux, the equivalent project settings are typically handled in a makefile. the makefile allows you to specify any number of options for your build environment, including the path and configuration updates you need to build with the gecko sdk. below is a listing for a makefile that configures your compiler to work with the sdk. explaining the details of the makefile is outside the scope of this appendix, but it modifies the same properties that are configured in the visual c++ project (see building a microsoft visual cpp project). for a listing of the commands that appear in this listing, see the make manual. sample makefile for the gecko sdk module = mozshim # change this to point at your gecko sdk directory. gecko_sdk_path ?= $(home)/tmp/xr xpidl ?= $(gecko_sdk_pat...
Detailed XPCOM hashtable guide
there are many different types of hash functions. mozilla has tuned a good general-purpose hash algorithm for strings and nsid. original document information author(s): benjamin smedberg <benjamin@smedbergs.us> ...
How to build a binary XPCOM component using Visual Studio
keep it simple) use a custom build step for the xpcom idl file (spawns xpidl-build.bat to process the idl with mozilla toolset, not midl) vc++ express project: xpcom-test.zip note: the project uses xpcom_glue. it also uses frozen linkage (dependent on xpcom). i am not defining xpcom_glue and i am linking against xpcomglue_s.lib create an xpcom component a full tutorial of xpcom is beyond the scope of this posting. check out the resources at the end of the tutorial for more information on the world of xpcom. ok then, on with the basic, oversimplified example. your xpcom component is made up of 3 parts: component interface described using idl. the interface defines the methods, including arguments and return types, of the component. component implementation using c++. the implementation i...
Introduction to XPCOM for the DOM
true most of the time). you would like to manipulate that object with a method defined on the nsifoo interface. the goal is to retrieve a pointer to the nsifoo interface. to do so, there are two main techniques, and the context should tell you what to use. the first technique is to use a "getter", the second is to use a static cast on the "this" pointer. a getter is a function defined in global scope or in class scope that will "return" a pointer to the required interface. generally getters work like this: first, declare a pointer to an interface, ifooptr without assigning it. pass the address of the pointer to the getter function. the getter function will then assign to the pointer the correct address and will queryinterface the pointer to that interface. ifooptr is now a pointer to an inter...
Components.utils.importGlobalProperties
imports various objects into a system scope. system scopes such as jsms and frame scripts don't have certain objects, such as indexeddb and xmlhttprequest, that are available to dom window globals. using this api you can import these objects into such a system scope. this function is not intended for sandboxes but for system-privileged scopes. to import these objects into a sandbox, use the wantglobalproperties option in the sandbox constructor. this function is passed an array of strings. each string is the name of an object to import, and will be defined on the importing scope's global. the following strings are supported: string/object xpcom component atob blob btoa crypto css fetch ...
Components.utils.makeObjectPropsNormal
ensures that the specified object's methods are all in the object's scope, and aren't cross-component wrappers. syntax void components.utils.makeobjectpropsnormal(obj); parameters obj the object for which to ensure all methods are in its scope. example for an example, see components.utils.createobjectin(). ...
IAccessibleTable
have a large number of children and thus it's possible that the child objects for those controls would only be created as needed. servers should document their life cycle strategy as this will be of interest to assistive technology or script engines accessing data out of process or from other threads. servers only need to save the most recent row and column values associated with the change and a scope of the entire application is adequate. [propget] hresult modelchange( [out] ia2tablemodelchange modelchange ); parameters modelchange a struct of (type(insert, delete, update), firstrow, lastrow, firstcolumn, lastcolumn). return value s_false if there is nothing to return, [out] value is null. s_ok. ncolumns() returns the total number of columns in table. [propget] hresult ncolumns( [out] ...
IAccessibleTable2
have a large number of children and thus it's possible that the child objects for those controls would only be created as needed. servers should document their life cycle strategy as this will be of interest to assistive technology or script engines accessing data out of process or from other threads. servers only need to save the most recent row and column values associated with the change and a scope of the entire application is adequate. [propget] hresult modelchange( [out] ia2tablemodelchange modelchange ); parameters modelchange a struct of (type(insert, delete, update), firstrow, lastrow, firstcolumn, lastcolumn). return value s_false if there is nothing to return, [out] value is null. s_ok. ncolumns() returns the total number of columns in table. [propget] hresult ncolumns( [out] ...
nsIContentFrameMessageManager
tring. attributes content nsidomwindow: the current top level window in the frame or null. read only. docshell nsidocshell: the top level docshell or null. read only. examples once you obtain the conten frame messge manager, you can send messages to listeners who registered with services.mm.addmessagelistener get content message manager from browser this could would run in a nsidomwindow scope. var acfmm = gbrowser.selectedbrowser._docshell.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsicontentframemessagemanager); get content message manager from content window window here is a html window or any window inside a tab, this code would run from a framescript. var acfmm = window.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidoc...
nsIDOMXPathEvaluator
ted. resolver a name space resolver created by creatensresolver(), or a user defined name space resolver. read more on implementing a user defined namespace resolver if you wish to take the latter approach. return value an xpath expression, as an nsidomxpathexpression object. creatensresolver() creates an nsidomxpathexpression which resolves name spaces with respect to the definitions in scope for a specified node. it is used to resolve prefixes within the xpath itself, so that they can be matched with the document. null is common for html documents or when no name space prefixes are used. nsidomxpathnsresolver creatensresolver( in nsidomnode noderesolver ); parameters noderesolver the node to be used as a context for name space resolution. return value a name space resolv...
nsIJetpack
allbacks previously registered with registerreceiver() for a particular message. void unregisterreceivers( in astring amessagename ); parameters amessagename the name of the message to unregister all callbacks from. evalscript() this asynchronously sends code to the jetpack process for evaluation. the code will be evaluated using at least javascript 1.8.1. when evaluated, the script's global scope will include all privileged apis. individual lines of the form //@line 1 "foo.js" can be used to specify filename and line number information for debugging purposes. void evalscript( in astring ascript ); parameters ascript the full contents of the script to evaluate in the jetpack process. createhandle() this creates an opaque handle that can transparently be exchanged between processes. ns...
nsIMsgFilterCustomAction
ports { /* globally unique string to identify this filter action. * recommended form: extensionname@example.com#actionname */ readonly attribute acstring id; /* action name to display in action list. this should be localized. */ readonly attribute astring name; /** * is this custom action valid for a particular filter type? * * @param type the filter type * @param scope the search scope * * @return true if valid */ boolean 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 filte...
nsINavBookmarksService
s can be nested, observers will only be notified when all batches begin/end. it is extremely important that you call endupdatebatch() for each call to beginupdatebatch. 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 changebookmark...
nsINavHistoryResult
historyresultobserver aobserver); attributes attribute type description root nsinavhistorycontainerresultnode the root of the results. this container gives you access to all the results in the tree. note: keep in mind that you need to open containers for their results to be valid. when a result goes out of scope it will continue to observe changes till it is cycle collected. while the result waits to be collected it will stay in memory, and continue to update itself, potentially causing unwanted additional work. when you close the root node the result will stop observing changes, so it is good practice to close the root node when you are done with a result, since that will avoid unwanted performance hits...
nsIPropertyBag
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:"yes" geolocation:geolocation language:"en-us" mimetypes:mimetypearray mozalarms:null mozapps:xpcwrappednative_nohelper mozcameras:camerama...
nsIWebContentHandlerRegistrar
ut contentwindow under construction. ...
nsIWorkerMessagePort
gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void postmessage(in domstring amessage); methods postmessage() posts a message into the event queue. void postmessage( in domstring amessage ); parameters amessage the message to post. see also using web workers nsiworkermessageevent nsiworkerglobalscope nsiworkerscope nsiabstractworker nsiworker ...
XPCOM Interface Reference by grouping
et nsistylesheetservice url nsiuri nsiurl util nsidomserializer nsidomxpathevaluator nsidomxpathexception nsidomxpathexpression nsidomxpathresult xslt nsixsltexception nsixsltprocessor download nsidownload nsidownloadmanager nsidownloadprogresslistener element internal nsiworker nsiworkerglobalscope nsiworkermessageevent nsiworkermessageport nsiworkerscope tree nsitreeboxobject nsitreecolumn nsitreecolumns nsitreecontentview nsitreeselection nsitreeview xform nsixformsmodelelement nsixformsnsinstanceelement nsixformsnsmodelelement xmlhttprequest nsixmlhttprequesteventtarget favicon nsifavicondatacallback ...
NS_CStringContainerInit
as been initialized via ns_cstringcontainerinit, it may be used as an ordinary nsacstring object. with ns_cstringcontainerinit, the coder is required to call ns_cstringcontainerfinish when done with the nscstringcontainer object. therefore, it is generally better to use nsembedcstring, to instantiate a nsacstring object, since it automatically releases allocated memory when the object goes out of scope. example nscstringcontainer str; if (ns_succeeded(ns_cstringcontainerinit(str))) { // now, |str| can be used with any function taking a nsacstring parameter. // call this function to release any memory owned by |str| when done. ns_cstringcontainerfinish(str); } history this function was finalized for mozilla 1.7. see bug 239123 for details. see also ns_cstringcontainerfinish, nsac...
NS_CStringContainerInit2
ary 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 coding directly to ns_cstringcontainerinit2 because those classes take care of cleaning up the string object when it goes out of scope. when ns_cstringcontainerinit2 is told to copy adata, the copy it creates is null-terminated. this is significant as it allows the programmer to be certain that ns_cstringgetdata will return a null-terminated character array. the ns_cstringcontainerinit function is equivalent to calling ns_cstringcontainerinit with adata=nsnull and aflags=0. history this function was finalized for mozilla 1.8.
NS_StringContainerInit
nary 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 with the nsstringcontainer object. therefore, it is generally better to use nsembedstring, to instantiate a nsastring object, since it automatically releases allocated memory when the object goes out of scope. example code nsstringcontainer str; if (ns_succeeded(ns_stringcontainerinit(str))) { // now, |str| can be used with any function taking a nsastring parameter. // be sure to call this function to release any memory owned by |str| when done. ns_stringcontainerfinish(str); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_stringcontain...
Address Book examples
e address book user interface? there are several hooks in the address book code exposed to add-on developers to help extend the behavior of the address book. load and save listeners edit dialogs for both contacts and mailing lists expose functions for registering load and save listeners. for example, in order to register a load listener for a contact, the following should take place within the scope of the contact editor dialog: /* an example load listener for a contact * acard the nsiabcard being loaded * adocument a reference to the contact editor document */ function foo(acard, adocument) { // do something useful, like disabling // input fields that cards for this // address book type do not support. } registerloadlistener(foo); save listeners are functions that take the sam...
Filelink Providers
js file have examples of this. management interface once an account has been created, it is manageable from within the preferences dialog, in the attachment pane, in the outgoing tab. the content to the right of the menulist is an iframe, pointed at a url read from the providers managementurl attribute, which should point to an xhtml page. the xhtml page should have a function in the global scope called onloadprovider. this function is called automatically once the dom content is done loading, and is passed a single parameter - the provider instance whose data is being displayed. ...
Using js-ctypes
before you can use js-ctypes, you need to import the ctypes.jsm code module. this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use. on windows, for example, you might load the system user32 library like this: var lib = ctypes.open("user32.dll"); on mac os x, you can load the core foundation library from the core foundation framework like this: var corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); the returned object is a library object that you use to declare functions and data types for use with...
ABI
w they revert. http://en.wikipedia.org/wiki/x86_calling_conventions abi abi stands for "application binary interface". http://en.wikipedia.org/wiki/application_binary_interface os specific windows https://msdn.microsoft.com/en-us/library/k2b2ssfy.aspx https://msdn.microsoft.com/en-us/library/9b372w95.aspx details with respect to js-ctypes this explains how to use it in the js-ctypes scope. three different abis exist: ctypes.default_abi, ctypes.stdcall_abi, and ctypes.winapi_abi. ctypes.default_abi corresponds to cdecl; standard libraries use this abi. you can also use this for various system calls,including those on mac os x and linux. ctypes.thiscall_abi more information is available at bugzilla :: 552533. ctypes.stdcall_abi used for calling functions declared with stdca...
CData
implementation-defined javascript expressions intended to represent the type of the cdata object and its value, respectively. string tosource() parameters none. return value a string that, ideally, should be able to be evaluated to produce a new cdata object containing a copy of the original object. however, this only works if the object's type happens to be bound to an appropriate name in scope. in theory, in other words, the following javascript expression should return a copy of the original cdata object: eval(dataobject.tosource()); tostring() returns a string identifying the data. string tostring(); parameters none. return value a string identifying the data. methods available on string objects these methods must be called on objects that are arrays or pointers to 8-b...
DOM Inspector internals - Firefox Developer Tools
is loaded in its place. in this way, the panelset and panels function like a frameset and frames. this comparison turns out to be quite apt, since each panel actually contains an anonymous browser, and individual viewers exist in separate documents loaded in the browser. this separation allows for viewers to be self-contained, with a viewer's xul defined in its own document and loaded in its own scope, without fear of collisions in the xul, css, or js. another convenient consequence of this is that if you use a properly set up development profile, then for the most part, the effects of development changes can be seen by simply switching away from the current viewer and back. knowing this about the way viewers are written, we should now be at a place where we can look at the way the dom inspec...
Access debugging in add-ons - Firefox Developer Tools
pt panel loaded. window.addeventlistener("debugger:editorunloaded") relevant files: chrome://browser/content/devtools/debugger-controller.js chrome://browser/content/devtools/debugger-toolbar.js chrome://browser/content/devtools/debugger-view.js chrome://browser/content/devtools/debugger-panes.js unfortunately there is not yet any api to evaluate watches/expressions within the debugged scope, or highlight elements on the page that are referenced as variables in the debugged scope. (currently a work in progress, see bug 653545.) ...
Examine, modify, and watch variables - Firefox Developer Tools
se it, you can, for now, switch back to the old debugger by visiting about:config and setting the "devtools.debugger.new-debugger-frontend" preference to false. to see the docs for the old debugger, please visit debugger (before firefox 52). examine variables when the code has stopped at a breakpoint, you can examine its state in the variables pane of the debugger: variables are grouped by scope: in function scope you'll see the built-in arguments and this variables as well as local variables defined by the function like user and greeting. similarly, in global scope you'll see global variables you've defined, like greetme, as well as built-in globals like localstorage and console. each object can be expanded, using a disclosure triangle, to show its properties. pointing your cursor at ...
Set a breakpoint - Firefox Developer Tools
kpoint is a conditional breakpoint, you'll get an option edit condition, which allows you to change the previously set condition. inline variable preview new in firefox 71, the source pane now gives you an inline preview of the variables on each line of code you've stepped through: this is a very useful timesaver when stepping through your code. previously you’d have to scroll through the scopes panel to find variable values, or hover over a variable in the source pane. now when execution pauses, you can view relevant variables immediately. note: there is also a new option in the context menu for the actual code in the source pane — hide inline preview/show inline preview — which allows you to turn the inline variables on/off. ...
Set a logpoint - Firefox Developer Tools
cedures, such as when you are debugging popup windows, or executing focus-related logic. to create a logpoint: right click on a line number in the debugger panel and pick add log action from the context menu. create an expression inline. the result is logged in the console panel every time the line with the logpoint executes. you can use any variable or function available in the current scope. working with logpoints when you set a logpoint, the indicator is purple, rather than the blue of an unconditional breakpoint or the orange of a conditional breakpoint. you can view the list of logpoints in the breakpoints side panel. when execution hits a logpoint, the message you have defined is logged to the console. you can make it easier to see the message by opening a split console...
Set an XHR breakpoint - Firefox Developer Tools
ter a key word instead of a url, code execution will pause on any call to a url that contains that keyword. when your code breaks on an xhr request, the righthand pane will have two additional sections: call stack the list of functions that were executed in order ot get to the currently executing code. click on an item in the call stack to jump to the associated line in the code display. scopes a list of the values that are in scope in the function, method, or event handler where the break occurred. inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
Debugger.Source - Firefox Developer Tools
bugger is an inherently single-threaded facility: its debuggees must all run in the same thread. since the global that created the worker is in a different thread, it is guaranteed not to be a debuggee of the debugger instance that owns this source; and thus the creating call is never “in debuggee code”. relating a worker to its creator, and other multi-threaded debugging concerns, are out of scope for debugger. if the instance refers to webassembly code, introductionscript is the debugger.script instance referring to the same underlying webassembly module. introductionoffset is undefined. source metadata generated from file: js/src/doc/debugger/debugger.source.md watermark: sha256:5ca245813db96628aab1c78b803355eb2aa8c575839c67eb7d7bde177898df88 changeset: e91b2c85aacd ...
Debugger-API - Firefox Developer Tools
ble names with storage locations. environments may belong to a running stack frame, captured by a function closure, or reflect some global object’s properties as variables. the debugger instance itself is not really a shadow of anything in the debuggee; rather, it maintains the set of global objects which are to be considered debuggees. a debugger observes only execution taking place in the scope of these global objects. you can set functions to be called when new stack frames are pushed; when new code is loaded; and so on. omitted from this picture are debugger.source instances, which represent javascript compilation units. a debugger.source can furnish a full copy of its source code, and explain how the code entered the system, whether via a call to eval, a <script> element, or otherwi...
Dominators - Firefox Developer Tools
t to another. the graph starts at a root node, indicated in these diagrams with "r". during garbage collection, the runtime traverses the graph, starting at the root, and marks every object it finds. any objects it doesn't find are unreachable, and can be deallocated. so when an object becomes unreachable (for example, because it is only referenced by a single local variable which goes out of scope) then any objects it references also become unreachable, as long as no other objects reference them: conversely, this means that objects are kept alive as long as some other reachable object is holding a reference to them. shallow and retained size this gives rise to a distinction between two ways to look at the size of an object: shallow size: the size of the object itself retained size...
Migrating from Firebug - Firefox Developer Tools
lays the function call stack within its stack side panel. in there the functions are listed together with their call parameters. in the devtools the function call stack is shown within the call stack side panel. to see the call parameters in the devtools, you need to have a look at the variables side panel. examine variables the watch side panel in firebug displays the window object (the global scope) by default. with the script execution halted it shows the different variable scopes available within the current call stack frame. furthermore, it allows you to add and manipulate watch expressions. the devtools have a variables side panel, which works basically the same. the main difference is that it is empty when the script execution is not stopped, i.e. it doesn't display the window object. ...
Split console - Firefox Developer Tools
nsole" command in the toolbar menu. the toolbox will now appear split, with the original tool above and the web console underneath. you can close the split console by pressing esc again, or by selecting the "hide split console" menu command. as usual, $0 works as a shorthand for the element currently selected in the inspector: when you use the split console with the debugger, the console's scope is the currently executing stack frame. so if you hit a breakpoint in a function, the scope will be the function's scope. you'll get autocomplete for objects defined in the function, and can easily modify them on the fly: ...
Firefox Developer Tools
wsers connect the developer tools to chrome on android and safari on ios. debugging the browser by default, the developer tools are attached to a web page or web app. but you can also connect them to the browser as a whole. this is useful for browser and add-on development. browser console see messages logged by the browser itself and by add-ons, and run javascript code in the browser's scope. browser toolbox attach the developer tools to the browser itself. migrating from firebug firebug has come to the end of its lifespan (see firebug lives on in firefox devtools for details of why), and we appreciate that some people will find migrating to another less familiar set of devtools to be challenging. to ease a transition from firebug to the firefox developer tools, we have written...
AnalyserNode.getFloatTimeDomainData() - Web APIs
be copied to. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. return value none. 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-float-data demo (see the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... analyser.fftsize = 1024; var bufferlength = analyser.fftsize; console.log(bufferlength); var dataarray = ne...
Attr.namespaceURI - Web APIs
Web › API › Attr › namespaceURI
ul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. if (attribute.localname == "value" && attribute.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul value } notes this is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. the namespace uri of an attribute is frozen at the attribute creation time. in firefox 3.5 and earlier, the namespace uri for html attributes in html documents is null. in later versions, in compliance with html5, it is https://www.w3.org/1999/xhtml as in xhtml. you can create an attribute with the specified namespaceuri using the dom level 2 method element.setattributens. per the namespaces...
AudioProcessingEvent - Web APIs
double the time when the audio will be played, as defined by the time of audiocontext.currenttime inputbuffer read only audiobuffer the buffer containing the input audio data to be processed. the number of channels is defined as a parameter, numberofinputchannels, of the factory method audiocontext.createscriptprocessor(). note the the returned audiobuffer is only valid in the scope of the onaudioprocess function. outputbuffer read only audiobuffer the buffer where the output audio data should be written. the number of channels is defined as a parameter, numberofoutputchannels, of the factory method audiocontext.createscriptprocessor(). note the the returned audiobuffer is only valid in the scope of the onaudioprocess function. example the fo...
AudioWorklet - Web APIs
access the audio context's instance of audioworklet through the baseaudiocontext.audioworklet property. ...
AudioWorkletNode() - Web APIs
essing. syntax var node = new audioworkletnode(context, name); var node = new audioworkletnode(context, name, options); parameters context the baseaudiocontext instance this node will be associated with. name a string, which represents the name of the audioworkletprocessor this node will be based on. a processor with the provided name must first be registered using the audioworkletglobalscope.registerprocessor() method. options optional an object based on the audioworkletnodeoptions dictionary, which contains zero or more optional properties to configure the new node. the result of the structured clone algorithm applied to the object is also internally passed into the associated audioworkletprocessor() constructor — this allows custom initialization of an underlying user-defined a...
BaseAudioContext.decodeAudioData() - Web APIs
ete 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 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 ca...
Using the Beacon API - Web APIs
and when that event is fired, the handler calls sendbeacon(). window.onsubmit = function send_analytics() { var data = json.stringify({ location: location.href, time: date() }); navigator.sendbeacon('/analytics', data); }; workernavigator.sendbeacon() the beacon api's workernavigator.sendbeacon() method works identically to the usual method, but is accessible from worker global scope. in the following example, a worker sends a beacon using the url and data from the global context. this code snippet is for the global context: function worker_send(url, data) { // create the worker object var myworker = new worker("worker-using.js"); // send the worker the url and data to beacon myworker.postmessage([url, data]); // set up a message handler to receive the success/...
Beacon API - Web APIs
s, the url and the data to send in the request. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method returns "true" and returns "false" otherwise. worker context the beacon api's navigator.sendbeacon() method is used to send a beacon of data to the server from the worker global scope. the method takes two arguments, the url and the data to send in the request. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method returns "true" and otherwise returns "false". ...
CSS Font Loading API - Web APIs
ts and interfaces for dynamically loading font resources. interfaces fontface represents a single usable font face. fontfaceset an interface loading font faces and checking their download statuses. fontfacesource a mixin providing all of the fonts used in font-related operations, unless defined otherwise. it defines the fontfacesources.fonts property available to document and workerglobalscope. fontfacesetloadevent fired whenever a fontfaceset loads. specifications specification status comment css font loading module level 3 working draft initial definition. ...
CSS Painting API - Web APIs
paintedimage); } the api defines paintworklet, a worklet that can be used to programmatically generate an image that responds to computed style changes. to find out more about how this is used, consult using the css painting api. interfaces paintworklet programmatically generates an image where a css property expects a file. access this interface through css.paintworklet. paintworkletglobalscope the global execution context of the paintworklet. paintrenderingcontext2d implements a subset of the canvasrenderingcontext2d api. it has an output bitmap that is the size of the object it is rendering to. paintsize returns the read-only values of the output bitmap's width and height. dictionaries paintrenderingcontext2dsettings a dictionary providing a subset of canvasrenderingcon...
CacheStorage - Web APIs
note: chrome and safari only expose `cachestorage` to the windowed context over https. window.caches will be undefined unless an ssl certificate is configured. maintains a mapping of string names to corresponding cache objects. ...
Using images - Web APIs
t try this before the image has loaded: var img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. it's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind. embedding an image via data: url another possible way to include images is via the data: url. data urls allow you to completely define an image as a base64 encoded string of characters directly in your code. var img = new image(); // create new img element img.src = 'data:image/gif;base64,r0lgodlhcwalaia...
ChildNode.after() - Web APIs
Web › API › ChildNode › after
see symbol.unscopables for more information. with(node) { after("foo"); } // referenceerror: after is not defined polyfill you can polyfill the after() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (it...
ChildNode.before() - Web APIs
Web › API › ChildNode › before
see symbol.unscopables for more information. with(node) { before("foo"); } // referenceerror: before is not defined polyfill you can polyfill the before() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { i...
ChildNode.remove() - Web APIs
Web › API › ChildNode › remove
hildnode.remove() method removes the object from the tree it belongs to. syntax node.remove(); example using remove() <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. with(node) { remove(); } // referenceerror: remove is not defined polyfill you can polyfill the remove() method in internet explorer 9 and higher with the following code: // from:https://github.com/jserz/js_piece/blob/master/dom/childnode/remove()/remove().md (function (arr) { arr.foreach(function (item) { if (ite...
ChildNode.replaceWith() - Web APIs
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 scoped into the with statement. see symbol.unscopables for more information. with(node) { replacewith("foo"); } // referenceerror: replacewith is not defined polyfill you can polyfill the replacewith() method in internet explorer 10+ and higher with the following code: function replacewithpolyfill() { 'use-strict'; // for safari, and ie > 10 var parent = this.parentnode, i = arguments.length...
Clients - Web APIs
Web › API › Clients
r a client matching a given id. clients.matchall() returns a promise for an array of client objects. an options argument allows you to control the types of clients returned. clients.openwindow() opens a new browser window for a given url and returns a promise for the new windowclient. clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. examples the following example shows an existing chat window or creates a new one when the user clicks a notification. addeventlistener('notificationclick', event => { event.waituntil(async function() { const allclients = await clients.matchall({ includeuncontrolled: true }); let chatclient; // let's see if we already have a chat window open: for (const client ...
ClipboardItem - Web APIs
the clipboarditem interface of the clipboard api represents a single item format, used when reading or writing data via the clipboard api. that is clipboard.read() and clipboard.write() respectively. the benefit of having the clipboarditem interface to represent data, is that it enables developers to cope with the varying scope of file types and data easily. access to the contents of the clipboard is gated behind the permissions api: the clipboard-write permission is granted automatically to pages when they are in the active tab. the clipboard-read permission must be requested, which you can do by trying to read data from the clipboard. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. note: you can only pass in ...
Console API - Web APIs
c was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior — although some implementations still have their own additional proprietary functions. find out about these at: google chrome devtools implementation safari devtools implementation usage is very simple — the console object — available via window.console, or workerglobalscope.console in workers; accessible using just console — contains many methods that you can call to perform rudimentary debugging tasks, generally focused around logging various values to the browser's web console. by far the most commonly-used method is console.log, which is used to log the current value contained inside a specific variable. interfaces console provides rudimentary debugging f...
ContentIndex.delete() - Web APIs
property and thus access the delete method. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } the delete method can also be used within the service worker scope. self.registration.index.delete('my-id'); specifications specification status comment unknownthe definition of 'delete' in that specification. unknown initial definition. ...
ContentIndex.getAll() - Web APIs
ontaining the following data: id: a unique string identifier. title: a string title for the item. used in user-visible lists of content. title: a string title of the item. used in user-visible lists of content. description: a string description of the item. used in user-visible lists of content. url: a string containing the url of the corresponding html document. needs to be under the scope of the current service worker. category: optional a string defining the category of content. can be: '' an empty string, this is the default. homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image. sizes: optional a string representation of the imag...
ContentIndex - Web APIs
us function, that removes an item from the content index. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker. they are accessible from the workerglobalscope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); specifications specification status comment unknownthe definition of 'contentindex' in that specification. unknown i...
ContentIndexEvent.id - Web APIs
nly id property of the contentindexevent interface is a string which identifies the deleted content index via it's id. syntax var id = contentindexevent.id; value a string representation of the deleted content index id. examples this example listens for the contentdelete event and logs the removed content index id. the contentindexevent is only available to the {domxref('serviceworkerglobalscope','global scope')}} of a serviceworker. self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); specifications specification status comment unknownthe definition of 'id' in that specification. unknown initial definition. ...
ContentIndexEvent - Web APIs
it contains the id of the indexed content to be removed. the contentdelete event is only fired when the deletion happens due to interaction with the browser's built-in user interface. it is not fired when the contentindex.delete method is called. constructor contentindexevent() creates and returns a new contentindexevent object whose type and other options are configured as specified. ...
Credential Management API - Web APIs
allow credentials to be retrieved from a different subdomain. for example, a password stored in login.example.com may be used to log in to www.example.com. to take advantage of this, a password must be explicitly stored by calling credentialscontainer.store(). this is sometimes referred to as public suffix list (psl) matching; however the spec only recommends using psl to determine the effective scope of a credential. it does not require it. hence browsers may vary in their implementation. interfaces credential provides information about an entity as a prerequisite to a trust decision. credentialscontainer exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. this interfaces is accessible from navigator.cre...
CustomEvent - Web APIs
ers' definitions vary. in addition, work is underway to change this to be a domhighrestimestamp instead. event.type read only the name of the event. case-insensitive. event.istrusted read only indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation method, like event.initevent). obsolete properties event.scoped read only obsolete; use composed instead. (a boolean indicating whether the given event will bubble across through the shadow root into the standard dom.) methods customevent.initcustomevent() initializes a customevent object. if the event has already being dispatched, this method does nothing. this interface inherits methods from its parent, event: event.createevent() ...
DOMHighResTimeStamp - Web APIs
let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the new page was acceptable. if neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current document took place. if the script's global object is a workerglobalscope (that is, the script is running as a web worker), the time origin is the moment at which the worker was created. in all other cases, the time origin is undefined. methods this type has no methods. usage notes you can get the current timestamp value—the time that has elapsed since the context was created—by calling the performance method now(). this method is available in both window and...
DOMMatrix - Web APIs
Web › API › DOMMatrix
s a 2d matrix; if the array has 16 values, the result is a 3d matrix. otherwise, a typeerror exception is thrown. frommatrix() creates a new mutable dommatrix object given an existing matrix or a dommatrixinit dictionary which provides the values for its properties. usage notes the matrix defined by the dommatrix interface is comprised of four rows of four columns each. while it's beyond the scope of this article to explain the mathematics involved, this 4×4 size is enough to describe any transformation you might apply to either 2d or 3d geometries. [m11m21m31m41m12m22m32m42m13m23m33m43m14m24m34m44]\left [ \begin{matrix} m_{11} & m_{21} & m_{31} & m_{41} \\ m_{12} & m_{22} & m_{32} & m_{42} \\ m_{13} & m_{23} & m_{33} & m_{43} \\ m_{14} & m_{24} & m_{34} & m_{44} \end{matrix} \right ] ...
Detecting device orientation - Web APIs
t are commonly capable of detecting devicemotionevent include sensors in laptops to protect moving storage devices. deviceorientationevent is more commonly found in mobile devices. processing orientation events all you need to do in order to begin receiving orientation change is to listen to the deviceorientation event: note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. this is useful for overcoming some of the differences in device support for device orientation. window.addeventlistener("deviceorientation", handleorientation, true); after registering your event listener (in this case, a javascript function called handleorientation()), your listener function periodically gets called with updated orientation data. the orientation even...
DeviceMotionEvent.accelerationIncludingGravity - Web APIs
ration which compensates for the influence of gravity, its value is the sum of the acceleration of the device as induced by the user and the acceleration caused by gravity. this value is not typically as useful as devicemotionevent.acceleration, but may be the only value available on devices that aren't able of removing gravity from the acceleration data, such as on devices that don't have a gyroscope. syntax var acceleration = devicemotionevent.accelerationincludinggravity; value the accelerationincludinggravity property is an object providing information about acceleration on three axis. each axis is represented with its own property: x represents the acceleration upon the x axis which is the west to east axis y represents the acceleration upon the y axis which is the south to nort...
Document.adoptNode() - Web APIs
thod's document. the adopted node and its subtree is removed from its original document (if any), and its ownerdocument is changed to the current document. the node can then be inserted into the current document. syntax const importednode = document.adoptnode(externalnode); parameters externalnode the node from another document to be adopted. return value the copied importednode in the scope of the importing document. after calling this method, importednode and externalnode are the same object. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.queryselector('iframe'); const iframeimages = iframe.contentdocument.queryselectorall('img'); const newparent = document.getelementbyid('images'); if...
Document.cookie - Web APIs
Web › API › Document › cookie
tain any commas, semicolons, or whitespace (which are disallowed in cookie values). some user agent implementations support the following cookie prefixes: __secure- signals to the browser that it should only include the cookie in requests transmitted over a secure channel. __host- signals to the browser that in addition to the restriction to only use the cookie from a secure origin, the scope of the cookie is limited to a path attribute passed down by the server. if the server omits the path attribute the "directory" of the request uri is used. it also signals that the domain attribute must not be present, which prevents the cookie from being sent to other domains. for chrome the path attribute must always be the origin. the dash is considered part of the prefix. these flags ...
Document.createNSResolver() - Web APIs
syntax nsresolver = document.creatensresolver(node); parameters node is the node to be used as a context for namespace resolution. return value nsresolver is an xpathnsresolver object. notes adapts any dom node to resolve namespaces so that an xpath expression can be easily evaluated relative to the context of the node where it appeared within the document. ...
Document.importNode() - Web APIs
ld always provide the deep argument for backward and forward compatibility. with gecko 28.0 (firefox 28 / thunderbird 28 / seamonkey 2.25 / firefox os 1.3), the console warns developers not to omit the argument. starting with gecko 29.0 (firefox 29 / thunderbird 29 / seamonkey 2.26)), a shallow clone is defaulted instead of a deep clone. return value the copied importednode in the scope of the importing document. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.queryselector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const newnode = document.importnode(oldnode, true); document.getelementbyid("container").appendchild(newnode); notes before they ...
Document.querySelectorAll() - Web APIs
l('.outer .inner'); inner.length; // 1, not 0! in this example, when selecting .outer .inner in the context the <div> with the class select, the element with the class .inner is still found, even though .outer is not a descendant of the base element on which the search is performed (.select). by default, queryselectorall() only verifies that the last element in the selector is within the search scope. the :scope pseudo-class restores the expected behavior, only matching selectors on descendants of the base element: var select = document.queryselector('.select'); var inner = select.queryselectorall(':scope .outer .inner'); inner.length; // 0 specifications specification status comment domthe definition of 'parentnode.queryselectorall()' in that specification. ...
Element.namespaceURI - Web APIs
ul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. if (element.localname == "browser" && element.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul browser } notes this is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. the namespace uri of a node is frozen at the node creation time. in firefox 3.5 and earlier, the namespace uri for html elements in html documents is null. in later versions, in compliance with html5, it is http://www.w3.org/1999/xhtml as in xhtml. you can create an element with the specified namespaceuri using the dom level 2 method document.createelementns. the dom does not handle or enfor...
Element.querySelectorAll() - Web APIs
r .inner'); inner.length; // 1, not 0! in this example, when selecting ".outer .inner" in the context the <div> with the class "select", the element with the class ".inner" is still found, even though .outer is not a descendant of the base element on which the search is performed (".select"). by default, queryselectorall() only verifies that the last element in the selector is within the search scope. the :scope pseudo-class restores the expected behavior, only matching selectors on descendants of the base element: var select = document.queryselector('.select'); var inner = select.queryselectorall(':scope .outer .inner'); inner.length; // 0 specifications specification status comment domthe definition of 'parentnode.queryselectorall()' in that specification. li...
Event.composed - Web APIs
Web › API › Event › composed
syntax const iscomposed = event.composed; value a boolean which is true if the event will cross from the shadow dom into the standard dom after reaching the shadow root. (that is, the first node in the shadow dom in which the event began to propagate.) all ua-dispatched ui events are composed (click/touch/mouseover/copy/paste, etc.). ...
Event - Web APIs
Web › API › Event
s' definitions vary. in addition, work is underway to change this to be a domhighrestimestamp instead. event.type read only the name of the event. case-insensitive. event.istrusted read only indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation method, like event.initevent). deprecated properties event.scoped read only a boolean indicating whether the given event will bubble across through the shadow root into the standard dom. use composed instead. methods event.composedpath() returns the event’s path (objects on which listeners will be invoked). this does not include nodes in shadow trees if the shadow root was created with its shadowroot.mode closed. event.preventdefault() cancels...
ExtendableMessageEvent - Web APIs
this interface inherits from the extendableevent interface. constructor extendablemessageevent() creates a new extendablemessageevent object instance. properties inherits properties from its parent, extendableevent. extendablemessageevent.data read only returns the event's data. it can be any data type. ...
FetchEvent.preloadResponse - Web APIs
onse read-only property of the fetchevent interface returns a promise that resolves to the navigation preload response if navigation preload was triggered or undefined otherwise. syntax var expectedresponse = fetchevent.preloadresponse; value a promise that resolves to a response or otherwise to undefined. example this code snippet is from the navigation preload page. the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code checks for a preloaded response. else it fetches a response from the network. addeventlistener('fetch', event => { event.respondwith(async function(...
FetchEvent.request - Web APIs
his property is non-nullable (since version 46, in the case of firefox.) if a request is not provided by some other means, the constructor init object must contain a request (see fetchevent.fetchevent().) syntax var recentrequest = fetchevent.request; value a request object. example this code snippet is from the service worker fetch sample (run the fetch sample live). the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the serviceworkerglobalscope.fetch operation. note that an http erro...
FetchEvent - Web APIs
it contains information about the fetch, including the request and how the receiver will treat the response. it provides the event.respondwith() method, which allows us to provide a response to this fetch. constructor fetchevent() creates a new fetchevent object. this constructor is not typically used. the browser creates these objects itself and provides them to fetch event callbacks. properties inherits properties from its ancestor, event. fetchevent.clientid read only the id of the same-origin client that initiated the fetch. ...
Using Fetch - Web APIs
method: 'post', body: form }); both request and response (and by extension the fetch() function), will try to intelligently determine the content type. a request will also automatically set a content-type header if none is set in the dictionary. feature detection fetch api support can be detected by checking for the existence of headers, request, response or fetch() on the window or worker scope. for example: if (window.fetch) { // run my fetch request here } else { // do something with xmlhttprequest? } polyfill to use fetch in unsupported browsers, there is a fetch polyfill available that recreates the functionality for non-supporting browsers. specifications specification status comment fetch living standard initial definition ...
FileSystemFlags - Web APIs
e may specify zero or more of these flags as fields in an object, like this: datadirectoryentry.getdirectory("workspace", { create: true }, function(entry) { }); here, we see that the create property is provided, with a value of true, indicating that the directory should be created if it's not already there. note that these option flags currently don't have any useful meaning when used in the scope of web content, where security precautions prevent the creation of new files or the replacement of existing ones. properties create optional if this property is true, and the requested file or directory doesn't exist, the user agent should create it. the default is false. the parent directory must already exist. exclusive optional if true, and the create option is also true, the file must...
Introduction to the File and Directory Entries API - Web APIs
equests for operations to happen, and get notified by callbacks. in contrast, the synchronous api does not use callbacks because the api methods return values. global methods of the asynchronous and synchronous apis. the asynchronous api has the following global methods: requestfilesystem() and resolvelocalfilesystemurl(). these methods are members of both the window object and the worker global scope. the synchronous api, on the other hand, uses the following methods: requestfilesystemsync() and resolvelocalfilesystemsyncurl(). 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 it...
GlobalEventHandlers - Web APIs
ed below. note: globaleventhandlers is a mixin and not an interface; you can't actually create an object of type globaleventhandlers. properties this interface doesn't include any properties except for the event handlers listed below. event handlers these event handlers are defined on the globaleventhandlers mixin, and implemented by htmlelement, document, window, as well as by workerglobalscope for web workers. globaleventhandlers.onabort is an eventhandler representing the code to be called when the abort event is raised. globaleventhandlers.onanimationcancel an eventhandler called when an animationcancel event is sent, indicating that a running css animation has been canceled. globaleventhandlers.onanimationend an eventhandler called when an animationend event is sent, in...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
xecution context: the global context is the execution context created to run the main body of your code; that is, any code that exists outside of a javascript function. each function is run within its own execution context. this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new execution context. each context is, in essence, a level of scope within your code. as one of these code segments begins execution, a new context is constructed in which to run it; that context is then destroyed when the code exits. consider the javascript program below: let outputelem = document.getelementbyid("output"); let userlanguages = { "mike": "en", "teresa": "es" }; function greetuser(user) { function localgreeting(user) { let greeting; ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
promises and the mutation observer api both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up. in order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the queuemicrotask() method is exposed on the window and worker interfaces through the windoworworkerglobalscope mixin. tasks vs microtasks to properly discuss microtasks, it's first useful to know what a javascript task is and how microtasks differ from tasks. this is a quick, simplified explanation, but if you would like more details, you can read the information in the article in depth: microtasks and the javascript runtime environment. tasks a task is any javascript code which is scheduled to be run...
The HTML DOM API - Web APIs
des the ability for web sites to store data either temporarily or permanently on the user's device for later re-use. storage storageevent web workers interfaces these interfaces are used by the web_workers_api both to establish the ability for workers to interact with an app and its content, but also to support messaging between windows or apps. broadcastchannel dedicatedworkerglobalscope messagechannel messageevent messageport sharedworker sharedworkerglobalscope worker workerglobalscope workerlocation workernavigator websocket interfaces these interfaces, defined by the html specification, are used by the websockets_api. closeevent websocket server-sent events interfaces the eventsource interface represents the source which sent or is sending server-sent e...
IDBDatabase.transaction() - Web APIs
.objectstore method, which you can use to access your object store. note: this feature is available in web workers. syntax idbdatabase.transaction(storenames); idbdatabase.transaction(storenames, mode); parameters "durability" -- the durability constrints for the transction. valid values are: "default", "strict", and "relaxed". storenames the names of object stores that are in the scope of the new transaction, declared as an array of strings. specify only the object stores that you need to access. if you need to access only one object store, you can specify its name as a string. therefore the following lines are equivalent: var transaction = db.transaction(['my-store-name']); var transaction = db.transaction('my-store-name'); if you need to access all object stores in the...
IDBDatabaseSync - Web APIs
ersion to store in the database. transaction() creates and returns a transaction, acquiring locks on the given database objects, within the specified timeout duration, if possible. idbtransactionsync transaction ( in optional domstringlist storenames, in optional unsigned int timeout ) raises (idbdatabaseexception); parameters storenames the names of object stores and indexes in the scope of the new transaction. timeout the interval that this operation is allowed to take to acquire locks on all the objects stores and indexes identified in storenames. returns idbtransactionsync an object to access the newly created transaction. exceptions this method can raise an idbdatabaseexception with the following code: timeout_err if reserving all the database objects identifie...
IDBEnvironment - Web APIs
the idbenvironment helper of the indexeddb api contains the indexeddb property, which provides access to indexeddb functionality. it is the top level indexeddb interface implemented by the window and worker objects. note: this feature is available in web workers. properties idbenvironment.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; contains an idbfactory object. ...
IDBTransaction.mode - Web APIs
is the mode to be read-only, or do you want to write to the object stores?) the default value is readonly. note: this feature is available in web workers. syntax var mycurrentmode = idbtransaction.mode; value an idbtransactionmode object defining the mode for isolating access to data in the current object stores: value explanation readonly allows data to be read but not changed. ...
IndexedDB API - Web APIs
he interface implemented by the global object indexeddb and is therefore the entry point for the api. idbopendbrequest represents a request to open a database. idbdatabase represents a connection to a database. it's the only way to get a transaction on the database. retrieving and modifying data idbtransaction represents a transaction. you create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want. idbrequest generic interface that handles database requests and provides access to results. idbobjectstore represents an object store that allows access to a set of data in an indexeddb database, looked up via primary key. idbindex also allows access to a subset of data...
LocalFileSystemSync - Web APIs
ing draft) drafted on april 19, 2011. this specification is more or less abandonned, failing to get significant traction. basic concepts you can request access to a sandboxed file system by requesting localfilesystemsync object from within a web worker. the global methods in the window object requestfilesystemsync() and resolvelocalfilesystemsyncurl() methods are exposed to the worker's global scope. calling window.requestfilesystemsync() for creates new storage for your web app. for more concepts, 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, se...
MediaDevices - Web APIs
a display (such as a window) to capture as a mediastream for sharing or recording purposes. returns a promise that resolves to a mediastream. getusermedia() with the user's 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. var video = document.queryselector('video'); var constraints = window.constraints = { audio: false, video: true }; var errorelement = document.queryselector('#errormsg'); navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var videotracks = stream.getvideotracks(); console.log('got stream with constraints:', constraints...
Metadata - Web APIs
Web › API › Metadata
properties modificationtime read only a date object indicating the date and time the entry was modified. ...
Node.namespaceURI - Web APIs
Web › API › Node › namespaceURI
the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. if (node.localname == "browser" && node.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul browser } notes this is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. the namespace uri of a node is frozen at the node creation time. in firefox 3.5 and earlier, the namespace uri for html elements in html documents is null. in later versions, in compliance with html5, it is https://www.w3.org/1999/xhtml as in xhtml. for nodes of any node.nodetype other than element_node and attribute_node the value of namespaceuri is always null. you can create an element wi...
NotificationAction - Web APIs
identify the clicked action similar to input names. notificationaction.title read only the string describing the action that is displayed to the user. notificationaction.icon read only the url of the image used to represent the notification when there is not enough space to display the notification itself. example notifications can fire notificationclick events on the serviceworkerglobalscope. here a service worker shows a notification with a single "archive" action, allowing users to perform this common task from the notification without having to open the website. the user can also click the main body of the notification to open their inbox instead. self.registration.shownotification("new mail from alice", { actions: [ { action: 'archive', title: 'archive' } ...
Notifications API - Web APIs
out more about using notifications in your own app, read using the notifications api. notifications interfaces notification defines a notification object. service worker additions serviceworkerregistration includes the serviceworkerregistration.shownotification() and serviceworkerregistration.getnotifications() method, for controlling the display of notifications. serviceworkerglobalscope includes the serviceworkerglobalscope.onnotificationclick handler, for firing custom functions when a notification is clicked. notificationevent a specific type of event object, based on extendableevent, which represents a notification that has fired. specifications specification status comment notifications api living standard living standard ...
OrientationSensor - Web APIs
ors 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([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "magnetometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ... } else { console.log("no permissions to use absoluteorientationsensor."); } }); specifications specification status comment orientation sensorthe definition of 'orientationsensor' in that specificati...
PaintWorklet - Web APIs
rted. <style> textarea { background-image: url(checkerboard); background-image: paint(checkerboard); } </style> <textarea></textarea> you can also use the @supports at-rule. @supports (background: paint(id)) { background-image: paint(checkerboard); } specifications specification status comment css painting api level 1the definition of 'paintworkletglobalscope' in that specification. working draft initial definition. ...
ParentNode.append() - Web APIs
Web › API › ParentNode › append
see symbol.unscopables for more information. let parent = document.createelement("div") with(parent) { append("foo") } // referenceerror: append is not defined polyfill you can polyfill the append() method in internet explorer 9 and higher with the following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (functi...
ParentNode.prepend() - Web APIs
see symbol.unscopables for more information. var parent = document.createelement("div"); with(parent) { prepend("foo"); } // referenceerror: prepend is not defined polyfill you can polyfill the prepend() method if it's not available: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/prepend()/prepend().md (function (arr) { arr.foreach(func...
ParentNode.querySelectorAll() - Web APIs
l('.outer .inner'); inner.length; // 1, not 0! in this example, when selecting .outer .inner in the context the <div> with the class select, the element with the class .inner is still found, even though .outer is not a descendant of the base element on which the search is performed (.select). by default, queryselectorall() only verifies that the last element in the selector is within the search scope. the :scope pseudo-class restores the expected behavior, only matching selectors on descendants of the base element: var select = document.queryselector('.select'); var inner = select.queryselectorall(':scope .outer .inner'); inner.length; // 0 specifications specification status comment domthe definition of 'parentnode.queryselectorall()' in that specification. ...
Using the Payment Request API - Web APIs
not installed. } }) .catch(function(ex1) { // unexpected error occurred. }); the payment handler would include the following code: self.addeventlistener('canmakepayment', function(evt) { // pre-authorize here. let preauthsuccess = ...; evt.respondwith(preauthsuccess); }); this payment handler would need to live in a service worker at https://example.com/preauth scope. note: see our pre-authorizing transactions demo for the full code. ...
Permissions.query() - Web APIs
Web › API › Permissions › query
syntax navigator.permissions.query(permissiondescriptor).then(function(permissionstatus) { ... }) parameters permissiondescriptor an object that sets options for the query operation consisting of a comma-separated list of name-value pairs. the available options are: name: the name of the api whose permissions you want to query. an up-to-date list of permission names can be found in the spec under the permissionname enum, but bear in mind that the actual permissions supported by browsers is currently much smaller than this. ...
Permissions - Web APIs
no support nochrome android full support 43firefox android ? opera android full support 30safari ios no support nosamsung internet android full support 4.0gyroscope permissionchrome full support 51edge full support 79firefox ? ie no support noopera ? safari no support nowebview android full support ...
PushEvent - Web APIs
Web › API › PushEvent
it contains the information sent from an application server to a pushsubscription. constructor pushevent.pushevent() creates a new pushevent object. properties inherits properties from its parent, extendableevent. additional properties: pushevent.data read only returns a reference to a pushmessagedata object containing data sent to the pushsubscription. methods inherits methods from its parent, extendableevent. ...
Response - Web APIs
Web › API › Response
constructor response() creates a new response object. ...
Sensor - Web APIs
Web › API › Sensor
interfaces that inherit from it. 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. interfaces based on sensor below is a list of interfaces based on the sensor interface. accelerometer 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.onerror called when an error o...
ServiceWorker - Web APIs
m its parent, worker, with the exception of worker.terminate — this should not be accessible from service workers. examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. ...
ServiceWorkerRegistration.active - Web APIs
the active property of the serviceworkerregistration interface returns a service worker whose serviceworker.state is activated. this property is initially set to null. an active worker controls a serviceworkerclient if the client's url falls within the scope of the registration (the scope option set when serviceworkercontainer.register is first called.) note: this feature is available in web workers. syntax var serviceworker = serviceworkerregistration.active; value a serviceworker object's property, if it is currently in an activated state. specifications specification status comment service workersthe definition of 'serviceworkerregistration.active' in that specification. working draft initial definition. ...
ServiceWorkerRegistration.getNotifications() - Web APIs
notifications created by one service worker on the same origin will not be available to other active services workers on that same origin. syntax s​erviceworkerregistration.getnotifications(options) .then(function(notificationslist) { ... ...
ServiceWorkerRegistration.showNotification() - Web APIs
you can also retrieve details of the notifications that have been fired from the current service worker using serviceworkerregistration.getnotifications(). specifications specification status comment notifications apithe definition of 'shownotification()' in that specification. living standard initial definition. ...
ServiceWorkerRegistration.update() - Web APIs
ceworkerregistration.update(); parameters none. return value a promise that resolves with a serviceworkerregistration object. ...
Storage Access API - Web APIs
age access grants are phased out after 30 days of browser usage passed without user interaction. this is currently a limitation of the firefox implementation, which we may address in a future version. in safari, successful use of the storage access api resets this counter. documentation for firefox's new storage access policy for blocking tracking cookies includes a detailed description of the scope of storage access grants. storage access api methods the storage api methods are implemented on the document interface: document.hasstorageaccess() returns a promise that resolves with a boolean value indicating whether the document has access to its first-party storage. document.requeststorageaccess() returns a promise that resolves if the access to first-party storage was granted, and r...
Streams API - Web APIs
g strategy that can be used when constructing streams. countqueuingstrategy provides a built-in chunk counting queuing strategy that can be used when constructing streams. extensions to other apis request when a new request object is constructed, you can pass it a readablestream in the body property of its requestinit dictionary. this request could then be passed to a windoworworkerglobalscope.fetch() to commence fetching the stream. body the response body returned by a successful fetch request is exposed by default as a readablestream, and can have a reader attached to it, etc. bytestream-related interfaces important: these are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented.
SyncEvent - Web APIs
Web › API › SyncEvent
this interface inherits from the extendableevent interface. ...
TextRange - Web APIs
Web › API › TextRange
ange.htmltext gets or sets the html content within the textrange. textrange.text gets or sets the plaintext content within the textrange. methods textrange.collapse() move the caret to the beginning or end of the current range. textrange.duplicate() returns a copy of textrange. textrange.execcommand() executes a command on the current document, the current selection, or the given scope. textrange.expand() expand the range to include the full range of specified units. for example, expanding a "word" means that the words at both ends of the range will completely included in the range. xpand to wor may become expand to words, etc. textrange.findtext() searches the specified text in the original range and adjusts the range to include the first match. textrange.inrange() retur...
WebGL2RenderingContext.beginQuery() - Web APIs
gl2renderingcontext.beginquery() method of the webgl 2 api starts an asynchronous query. the target parameter indicates which kind of query to begin. syntax void gl.beginquery(target, query); parameters target a glenum specifying the target of the query. possible values: gl.any_samples_passed: specifies an occlusion query: these queries detect whether an object is visible (whether the scoped drawing commands pass the depth test and if so, how many samples pass). gl.any_samples_passed_conservative: same as above above, but less accurate and faster version. gl.transform_feedback_primitives_written: number of primitives that are written to transform feedback buffers. query a webglquery object for which to start the querying. return value none. examples var query = gl.cre...
WebGL2RenderingContext.endQuery() - Web APIs
the webgl2renderingcontext.endquery() method of the webgl 2 api marks the end of a given query target. syntax void gl.endquery(target); parameters target a glenum specifying the target of the query. possible values: gl.any_samples_passed: specifies an occlusion query: these queries detect whether an object is visible (whether the scoped drawing commands pass the depth test and if so, how many samples pass). gl.any_samples_passed_conservative: same as above above, but less accurate and faster version. gl.transform_feedback_primitives_written: number of primitives that are written to transform feedback buffers. return value none. examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); // ... gl.endquery(gl.any_samples_passed); sp...
WebGL2RenderingContext.getQuery() - Web APIs
the webgl2renderingcontext.getquery() method of the webgl 2 api returns the currently active webglquery for the target, or null. syntax webglquery gl.getquery(target, pname); parameters target a glenum specifying the target of the query. possible values: gl.any_samples_passed: specifies an occlusion query: these queries detect whether an object is visible (whether the scoped drawing commands pass the depth test and if so, how many samples pass). gl.any_samples_passed_conservative: same as above above, but less accurate and faster version. gl.transform_feedback_primitives_written: number of primitives that are written to transform feedback buffers. pname a glenum specifying the query object target. must be gl.current_query. return value a webglquery object. e...
Clearing with colors - Web APIs
owser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } // run everything inside window load event handler, to make sure // dom is fully loaded and styled before trying to manipulate it, // and to not mess up the global scope. we are giving the event // handler a name (setupwebgl) so that we can refer to the // function object within the function itself. window.addeventlistener("load", function setupwebgl (evt) { "use strict" // cleaning after ourselves. the event handler removes // itself, because it only needs to run once. window.removeeventlistener(evt.type, setupwebgl, false); // references to the docu...
Matrix math for the web - Web APIs
tion, this dimension is called the perspective, and is represented by the letter w. for a typical position, setting w to 1 will make the math work out. after adding the w component to the point, notice how neatly the matrix and the point line up: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] [4, 3, 2, 1] // point at [x, y, z, w] the w component has some additional uses that are out of scope for this article. check out the webgl model view projection article for a look into how it comes in handy. multiplying a matrix and a point in our example code we have defined a function to multiply a matrix and a point — multiplymatrixandpoint(): // point • matrix function multiplymatrixandpoint(matrix, point) { // give a simple variable name to each part of the matrix, a column and row...
Lighting in WebGL - Web APIs
is article will cover some of the basics. this example uses the glmatrix library to perform its matrix and vertex math. you'll need to include it if you create your own project based on this code. our sample loads a copy from a cdn in our html's <head>. simulating lighting and shading in 3d although going into detail about the theory behind simulated lighting in 3d graphics is far beyond the scope of this article, it's helpful to know a bit about how it works. instead of discussing it in depth here, take a look at the article on phong shading at wikipedia, which provides a good overview of the most commonly used lighting model or if you'd like to see a webgl based explanation see this artcle. there are three basic types of lighting: ambient light is the light that permeates the scene; it...
Introduction to WebRTC protocols - Web APIs
connection such as resolution, formats, codecs, encryption, etc. so that both peers can understand each other once the data is transferring. this is, in essence, the metadata describing the content and not the media content itself. technically, then, sdp is not truly a protocol, but a data format used to describe connection that shares media between devices. documenting sdp is well outside the scope of this documentation; however, there are a few things worth noting here. structure sdp consists of one or more lines of utf-8 text, each beginning with a one-character type, followed by an equals sign ("="), followed by structured text comprising a value or description, whose format depends on the type. the lines of text that begin with a given letter are generally referred to as "letter-lines...
Using DTMF with WebRTC - Web APIs
tones have been sent, a tonechange event with its tone property set to "" (an empty string) is delivered to the connection object. if you'd like to know more about how this works, read rfc 3550: rtp: a transport protocol for real-time applications and rfc 4733: rtp payload for dtmf digits, telephony tones, and telephony signals. the details of how dtmf payloads are handled on rtp are beyond the scope of this article. instead, we'll focus on how to use dtmf within the context of an rtcpeerconnection by studying how an example works. simple example this simple example constructs two rtcpeerconnections, establishes a connection between them, then waits for the user to click a "dial" button. when the button is clicked, a dtmf string is sent over the connection using rtcdtmfsender.insertdtmf(). ...
Writing WebSocket servers - Web APIs
capable of berkeley sockets, such as c(++), python, php, or server-side javascript. this is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server. this article assumes you're already familiar with how http works, and that you have a moderate level of programming experience. depending on language support, knowledge of tcp sockets may be required. the scope of this guide is to present the minimum knowledge you need to write a websocket server. note: read the latest official websockets specification, rfc 6455. sections 1 and 4-7 are especially interesting to server implementors. section 10 discusses security and you should definitely peruse it before exposing your server. a websocket server is explained on a very low level here. websocket servers...
Geometry and reference spaces in WebXR - Web APIs
rendered and composited. fundamentals of 3d geometry while we'll examine here the required math operations used to compute the positions, orientations, and movement of objects in virtual space—plus the need to integrate the human viewer of the scene into the mix—a thorough introduction to geometry and the use of matrices and vectors to manage 3d representations of a scene is well beyond the scope of what can be accomplished in this article. you can learn more about the individual operations in matrix math for the web. units before discussing the details of the geometry of the 3d space used by webxr, it's first useful to understand the units of measure that are applied to the 3d world. lengths and distances webgl measures all distances and lengths in meters. webxr inherits this standar...
Inputs and input sources - Web APIs
gather information about each input source, then present a user interface describing each input, allowing the user to assign uses to each of them. doing this well could be a big job, but it might be useful for complex apps that may involve several user inputs. much of the information you need in order to implement this can be found in the section on input profiles, below. details are beyond the scope of this article, however. input profiles as mentioned above, each input source has a list of input profile names that correspond to a set of information describing that input source and how it can be used. those names are found in the input source's profiles property, and the official registry of these profile strings is maintained in the webxr input profiles registry on github. for example, t...
Lighting a WebXR setting - Web APIs
ion collects this information about the light sources and the shape and orientation of the objects in the scene, along with information about the materials they're made of, then returns data you can use to create virtual light source objects that approximately match the real world's lighting. the specifics of how lighting estimation works, especially in the context of the proposed api, is out of scope for the moment. once the api has stabilized, we'll update this documentation with the details. security and privacy concerns there are a number of potential security issues involved with collecting all of this data in order to generate and apply lighting to your virtual objects using real-world data. of course, many ar applications make it pretty clear where the user is located. if the user is...
Targeting and hit detection - Web APIs
he device's camera (if available) but also potentially multiple additional sensors. some devices include infrared sensors to help range objects, and others provide powerful lidar systems, which use lasers (usually infrared lasers, which can't be seen by the human eye) to determine range to objects in the world. the details of how to work with an individual platform's ranging system is beyond the scope of this article. however, there's hope: a proposal has been floated for a webxr hit test module that would layer atop webxr to provide an api for performing hit testing and collision detection. ...
Background audio processing using AudioWorklet - Web APIs
this call to registerprocessor() registers your class as the basis for any audioworkletprocessors created when audioworkletnodes are set up. this is the barest framework and actually has no effect until code is added into process() to do something with those inp...
Attestation and Assertion - Web APIs
en being asked to authenticate. authenticatordata - data created and/or used by the authenticator signature - a signature over the clientdatajson and authenticatordata that can be verified with the public key that was created during registration. userhandle - optional. (nullable) a user identifier. this may be a username, or a hash of a username, etc. used by a service to give a scope to credentials. maximum length of 64 bytes. older authenticators (u2f) do not support this output. it's important to highlight that the signature for assertion uses a different key pair than attestation. an assertion is signed using the key pair for a service, which was generated during registration. an attestation is signed using the attestation private key and attestation certificate that w...
Web Locks API - Web APIs
tabs/workers, will be queued. the first queued request will be granted only when the lock is released. the api provides optional functionality that may be used as needed, including: returning values from the asynchronous task shared and exclusive lock modes conditional acquisition diagnostics to query the state of locks in an origin an escape hatch to protect against deadlocks locks are scoped to origins; the locks acquired by a tab from https://example.com have no effect on the locks acquired by a tab from https://example.org:8080 as they are separate origins. the main entry point is navigator.locks.request() which requests a lock. it takes a lock name, an optional set of options, and a callback. the callback is invoked when the lock is granted. the lock is automatically released wh...
Window.controllers - Web APIs
tains the code that supports the global window commands. ...
Window.isSecureContext - Web APIs
the window.issecurecontext read-only property indicates whether a context is capable of using features that require secure contexts. syntax var issecure = window.issecurecontext examples feature detection you can use feature detection to check whether they are in a secure context or not by using the issecurecontext boolean which is exposed on the global scope. if (window.issecurecontext) { // page is a secure context so service workers are now available navigator.serviceworker.register("/offline-worker.js").then(function () { ... }); } specifications specification status comment secure contexts candidate recommendation initial definition. ...
Window: languagechange event - Web APIs
the languagechange event is fired at the global scope object when the user's preferred language changes. bubbles no cancelable no interface event event handler onlanguagechange examples you can use the languagechange event in an addeventlistener method: window.addeventlistener('languagechange', function() { console.log('languagechange event detected!'); }); or use the onlanguagechange event handler property: window.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; specification specification status html living standardthe definition of 'languagechange' in that specification. living standard ...
Window: rejectionhandled event - Web APIs
this can be used in debugging and for general application resiliency, in tandem with the unhandledrejection event, which is sent when a promise is rejected but there is no hander for the rejection. ...
Window.self - Web APIs
Web › API › Window › self
the window.self read-only property returns the window itself, as a windowproxy. it can be used with dot notation on a window object (that is, window.self) or standalone (self). the advantage of the standalone notation is that a similar notation exists for non-window contexts, such as in web workers. by using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to workerglobalscope.self). example uses of window.self like the following could just as well be replaced by window. if (window.parent.frames[0] != window.self) { // this window is not the first frame in the list } furthermore, when executing in the active document of a browsing context, window is a ref...
Window: unhandledrejection event - Web APIs
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. ...
WindowClient - Web APIs
the service worker client independently selects and uses a service worker for its own loading and sub-resources. methods windowclient inherits methods from its parent interface, client. windowclient.focus() gives user input focus to the current client. windowclient.navigate() loads a specified url into a controlled client page. properties windowclient inherits properties from its parent interface, client. windowclient.focused read only a boolean that indicates whether the current client has focus. ...
WindowEventHandlers - Web APIs
es like window, or htmlbodyelement and htmlframesetelement. each of these interfaces can implement additional specific event handlers. note: windoweventhandlers is a mixin and not an interface; you can't actually create an object of type windoweventhandlers. properties the events properties, of the form onxyz, are defined on the windoweventhandlers, and implemented by window, and workerglobalscope for web workers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. windoweventhandlers.onbeforeunload is an eventhandler representing the code to be called when the beforeunload event is rais...
self.createImageBitmap() - Web APIs
it accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. ...
Worker() - Web APIs
Web › API › Worker › Worker
to create. the value can be classic or module. if not specified, the default used is classic. credentials: a domstring specifying the type of credentials to use for the worker. the value can be omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring specifying an identifying name for the dedicatedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. exceptions a securityerror is raised if the document is not allowed to start workers, e.g. if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised...
Worker: message event - Web APIs
the message event is fired on a worker object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using dedicatedworkerglobalscope.postmessage()). bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and listens to messages from it using addeventlistener(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); alternatively, it could listen using the onmessage event handler property: const worker = new worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`received message from...
Worker.prototype.postMessage() - Web APIs
the postmessage() method of the worker interface sends a message to the worker's inner scope. this accepts a single parameter, which is the data to send to the worker. the data may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references. the worker can send back information to the thread that spawned it using the dedicatedworkerglobalscope.postmessage 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 ...
WorkerLocation - Web APIs
this interface is only visible from inside a javascript script executed in the context of a web worker. properties the workerlocation interface doesn't inherit any property, but implements properties defined in the urlutilsreadonly interface. ...
WorkerNavigator - Web APIs
properties the workernavigator interface implements properties from the navigatorid, navigatorlanguage, navigatoronline, navigatordatastore, and navigatorconcurrenthardware interfaces. workernavigator.connectionread only provides a networkinformation object containing information about the network connection of a device. ...
XPathEvaluator.createNSResolver() - Web APIs
current information available in the node's hierarchy at the time the method is called, also correctly resolving the implicit xml prefix. syntax xpathnsresolver xpathevaluator.creatensresolver(noderesolver); parameters noderesolver a node to be used as a context for namespace resolution. return value an xpathnsresolver object which resolves namespaces with respect to the definitions in scope for a specified node. specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.creatensresolver()' in that specification. recommendation initial definition ...
msWriteProfilerMark - Web APIs
filermark 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 in the web worker global scope. for windows xp, this method sends an event to an event tracing session with traceevent; for systems after windows xp, this method writes an event with eventwrite. the event includes a pointer to a window object, current markup, and the event name passed as bstrprofilermarkname. the bstrprofilermarkname property has a 32-character limit when called from script. this method is useful to profil...
ARIA: cell role - Accessibility
containing data arranged in rows and columns, similar to the native <table> html element. role="treegrid" similar to a grid, but with rows that can be expanded and collapsed in the same manner as for a tree. subclass roles role="gridcell" a cell in a row within a grid or treegrid. role="columnheader" a header cell that is the structural equivalent of the html <th> element with a column scope. unlike a plain cell, the columnheader role establishes a relationship between it and all cells in the corresponding column. role="rowheader" a header cell that is the structural equivalent of the html <th> element with a row scope. unlike a plain cell, the rowheader role establishes a relationship between it and all cells in the corresponding row. states and properties aria-colspan sim...
ARIA: row role - Accessibility
e native <table> html element. role="treegrid" similar to a grid, but with rows that can be expanded and collapsed in the same manner as for a tree. descendant roles role="cell" a cell in a row within a tabular container. role="gridcell" a cell in a row within a grid or treegrid. role="columnheader" a header cell that is the structural equivalent of the html <th> element with a column scope. unlike a plain cell, the columnheader role establishes a relationship between it and all cells in the corresponding column. role="rowheader" a header cell that is the structural equivalent of the html <th> element with a row scope. unlike a plain cell, the rowheader role establishes a relationship between it and all cells in the corresponding row. states and properties aria-expanded sta...
Custom properties (--*): CSS variables - CSS: Cascading Style Sheets
Web › CSS › --*
property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function. custom properties are scoped to the element(s) they are declared on, and participate in the cascade: the value of such a custom property is that from the declaration decided by the cascading algorithm. initial valuesee proseapplies toall elementsinheritedyescomputed valueas specified with variables substitutedanimation typediscrete syntax --somekeyword: left; --somecolor: #0000ff; --somecomplexvalue: 3px 6px rgb(20, 32, 54); <declaration-value> this value matches any sequence of one or more tokens, so long as the sequence does not contain an unallowed token. it represents the entirety of what a valid declaratio...
:has() - CSS: Cascading Style Sheets
Web › CSS › :has
the :has() css pseudo-class represents an element if any of the selectors passed as parameters (relative to the :scope of the given element) match at least one element. /* selects any <a>, as long as it has an <img> element directly inside it */ /* note that this is not supported in any browser yet */ let test = document.queryselector('a:has(> img)'); syntax :has( <relative-selector-list> )where <relative-selector-list> = <relative-selector>#where <relative-selector> = <combinator>? <complex-selector>where <combinator> = '>' | '+' | '~' | [ '|' ]<complex-selector> = <compound-selector> [ <combinator>? <compound-selector> ]*where <compound-selector> = [ <type-selector>? <subclass-selector>* [ <pseudo-element-selector> <pseudo-class-selector>* ]* ]!where <type-selector> = <wq-name> | <ns-pre...
Using CSS counters - CSS: Cascading Style Sheets
. the counter's name must not be "none", "inherit", or "initial"; otherwise the declaration is ignored. displaying a counter the value of a counter can be displayed using either the counter() or counters() function in a content property. the counter() function has two forms: 'counter(name)' or 'counter(name, style)'. the generated text is the value of the innermost counter of the given name in scope at the given pseudo-element.the counter is rendered in the specified style (decimal by default). the counters() function also has two forms: 'counters(name, string)' or 'counters(name, string, style)'. the generated text is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string. the counters are rendered ...
CSS selectors - CSS: Cascading Style Sheets
nator the + combinator selects adjacent siblings. this means that the second element directly follows the first, and both share the same parent. syntax: a + b example: h2 + p will match all <p> elements that directly follow an <h2>. column combinator the || combinator selects nodes which belong to a column. syntax: a || b example: col || td will match all <td> elements that belong to the scope of the <col>. pseudo pseudo classes the : pseudo allow the selection of elements based on state information that is not contained in the document tree. example: a:visited will match all <a> elements that have been visited by the user. pseudo elements the :: pseudo represent entities that are not included in html. example: p::first-line will match the first line of all <p> elements. sp...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
Web › CSS › Cascade
and aren't affected by the cascade algorithm. origin of css declarations the css cascade algorithm's job is to select css declarations in order to determine the correct values for css properties. css declarations originate from different origins: the user-agent stylesheets, the author stylesheets, and the user stylesheets. though style sheets come from these different origins, they overlap in scope; to make this work, the cascade algorithm defines how they interact. user-agent stylesheets the browser has a basic style sheet that gives a default style to any document. these style sheets are named user-agent stylesheets. some browsers use actual style sheets for this purpose, while others simulate them in code, but the end result is the same. some browsers let users modify the user-agent s...
CSS reference - CSS: Cascading Style Sheets
Web › CSS › Reference
-eventspolygon()<position>positionprefix (@counter-style)ptpxqqquotesrradradial-gradient()range (@counter-style)<ratio>:read-only:read-writerect()remrepeat()repeating-linear-gradient()repeating-radial-gradient():requiredresize<resolution>revertrgb()rgba():rightright@right-bottom:rootrotaterotate()rotate3d()rotatex()rotatey()rotatez()row-gapsssaturate()scalescale()scale3d()scalex()scaley()scalez():scopescroll-behaviorscroll-marginscroll-margin-blockscroll-margin-block-endscroll-margin-block-startscroll-margin-bottomscroll-margin-inlinescroll-margin-inline-endscroll-margin-inline-startscroll-margin-leftscroll-margin-rightscroll-margin-topscroll-paddingscroll-padding-blockscroll-padding-block-endscroll-padding-block-startscroll-padding-bottomscroll-padding-inlinescroll-padding-inline-endscroll-pad...
Replaced elements - CSS: Cascading Style Sheets
put in simpler terms, they're elements whose contents are not affected by the current document's styles. the position of the replaced element can be affected using css, but not the contents of the replaced element itself. some replaced elements, such as <iframe> elements, may have stylesheets of their own, but they don't inherit the styles of the parent document. the only other impact css can have on a replaced element is that there are properties which support controlling the positioning of the element's content within its box. ...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
ject to the cascade and inherit their value from their parent. basic usage declaring a custom property is done using a custom property name that begins with a double hyphen (--), and a property value that can be any valid css value. like any other property, this is written inside a ruleset, like so: element { --main-bg-color: brown; } note that the selector given to the ruleset defines the scope that the custom property can be used in. a common best practice is to define custom properties on the :root pseudo-class, so that it can be applied globally across your html document: :root { --main-bg-color: brown; } however, this doesn't always have to be the case: you maybe have a good reason for limiting the scope of your custom properties. note: custom property names are case sensitive...
content - CSS: Cascading Style Sheets
Web › CSS › content
> data type, or part of the webpage, defined by the element() function, denoting the content to display. <counter>() the value of a css counter, generally a number. it can be displayed using either the counter() or counters() function. the counter() function has two forms: 'counter(name)' or 'counter(name, style)'. the generated text is the value of the innermost counter of the given name in scope at the given pseudo-element. it is formatted in the specified style (decimal by default). the counters() function also has two forms: 'counters(name, string)' or 'counters(name, string, style)'. the generated text is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string. the counters are rendered in the...
env() - CSS: Cascading Style Sheets
Web › CSS › env
the env() css function can be used to insert the value of a user agent-defined environment variable into your css, in a similar fashion to the var() function and custom properties. the difference is that, as well as being user-agent defined rather than user-defined, environment variables are globally scoped to a document, whereas custom properties are scoped to the element(s) on which they are declared. to tell the browser to use the whole available space on the screen, and so enabling us to use the env() variables, we need to add a new viewport meta value: <meta name="viewport" content="viewport-fit=cover" /> body { padding: env(safe-area-inset-top, 20px) env(safe-area-inset-right, 20px) env(safe-area-inset-bottom, 20px) env(safe-area-inset-left, 20px); } in addition, u...
text-decoration-color - CSS: Cascading Style Sheets
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. ...
CSS: Cascading Style Sheets
Web › CSS
ch, or on other media. css among the core languages of the open web and is standardized across web browsers according to the w3c specification. previously development of various parts of css specification was done synchronously, which allowed versioning of the latest recommendation. you might have heard about css1, css2.1, css3. however, css4 has never become an official version. from css3, the scope of the specification increased significantly and the progress on different css modules started to differ so much, that it became more effective to develop and release recommendations separately per module. instead of versioning the css specification, w3c now periodically takes a snapshot of the latest stable state of the css specification. css introduction if you're new to web development,...
Demos of open web technologies
etarium (source code) loader with blend modes text reveal with clip-path ambient shadow with custom properties luminiscent vial css-based single page application (source code) transformations impress.js (source code) games ioquake3 (source code) kai 'opua (source code) web apis notifications api html5 notifications (source code) web audio api web audio fireworks oscope.js - javascript oscilloscope html5 web audio showcase (source code) html5 audio visualizer (source code) graphical filter editor and visualizer (source code) file api slide my text - presentation from plain text files web workers web worker fractals photo editor coral generator raytracer hotcold touch typing ...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
nline svg and mathml in text/html. this means that you can now use svg and mathml inline in text/html similarly to what has previously been possible in application/xhtml+xml. <svg>…</svg> is assigned to the svg namespace in the dom. <math>…</math> is assigned to the mathml namespace in the dom. foreignobject and annotation-xml (and various less important elements) establish a nested html scope, so you can nest svg, mathml and html as you’d expect to be able to nest them. the parser case-corrects markup so <svg viewbox='0 0 10 10'> works in html source. the dom methods and css selectors behave case-sensitively, so you need to write your dom calls and css selectors using the canonical case, which is camelcase for various parts of svg such as viewbox. the syntax <foo/> opens and imme...
Writing forward-compatible websites - Developer guides
the element itself, then on the element's form if the element is a form control, then on the document, and then on the window (where the global variables you have defined are). for example, if you have this markup: <div onclick="alert(ownerdocument)">click me</div> then clicking on the text alerts the ownerdocument of the div. this happens even if there is a var ownerdocument declared in global scope. what this means is that any time you access a global variable in an event handler content attribute, including calling any function declared globally, you can end up with a name collision if a specification adds a new dom property to elements or documents which has the same name as your function or variable, and a browser implements it. if that happens, then suddenly your function stops being c...
<keygen> - HTML: Hypertext Markup Language
Web › HTML › Element › keygen
the keyparams parameter string is not a recognized curve name string, then a curve is chosen according to the user's chosen key strength (low, medium, high), using the curve named "secp384r1" for high, and the curve named "secp256r1" for medium keys. (note: choice of the number of key strengths, default values for each strength, and the ui by which the user is offered a choice, are outside of the scope of this specification.) the <keygen> element is only valid within an html form. it will cause some sort of selection to be presented to the user for selecting key size. the ui for the selection may be a menu, radio buttons, or possibly something else. the browser presents several possible key strengths. currently, two strengths are offered, high and medium. if the user's browser is configured to...
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
Web › HTML › Element › td
ical values include a period (.) to align numbers or monetary values. if align is not set to char, this attribute is ignored. charoff this attribute is used to shift column data to the right of the character specified by the char attribute. its value specifies the length of this shift. height this attribute is used to define a recommended cell height. use the css height property instead. scope this enumerated attribute defines the cells that the header (defined in the <th>) element relates to. only use this attribute with the <th> element to define the row or column for which it is a header. valign this attribute specifies how a text is vertically aligned inside a cell. possible values for this attribute are: baseline: positions the text near the bottom of the cell and align...
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
ody of the table (<table>). <td> the html <td> element defines a cell of a table that contains data. it participates in the table model. <tfoot> the html <tfoot> element defines a set of rows summarizing the columns of the table. <th> the html <th> element defines a cell as header of a group of table cells. the exact nature of this group is defined by the scope and headers attributes. <thead> the html <thead> element defines a set of rows defining the head of the columns of the table. <tr> the html <tr> element defines a row of cells in a table. the row's cells can then be established using a mix of <td> (data cell) and <th> (header cell) elements. forms html provides a number of elements which can be used together t...
HTTP authentication - HTTP
on scheme is used, so that the client that wishes to authorize knows how to provide the credentials. the syntax for these headers is the following: www-authenticate: <type> realm=<realm> proxy-authenticate: <type> realm=<realm> here, <type> is the authentication scheme ("basic" is the most common scheme and introduced below). the realm is used to describe the protected area or to indicate the scope of protection. this could be a message like "access to the staging site" or similar, so that the user knows to which space they are trying to get access to. authorization and proxy-authorization headers the authorization and proxy-authorization request headers contain the credentials to authenticate a user agent with a (proxy) server. here, the <type> is needed again followed by the credentials...
Using HTTP cookies - HTTP
Web › HTTP › Cookies
t only to the server. for example, cookies that persist server-side sessions don't need to be available to javascript, and should have the httponly attribute. this precaution helps mitigate cross-site scripting (xss) attacks. here is an example: set-cookie: id=a3fwa; expires=wed, 21 oct 2021 07:28:00 gmt; secure; httponly define where cookies are sent the domain and path attributes define the scope of the cookie: what urls the cookies should be sent to. domain attribute the domain attribute specifies which hosts are allowed to receive the cookie. if unspecified, it defaults to the same origin that set the cookie, excluding subdomains. if domain is specified, then subdomains are always included. therefore, specifying domain is less restrictive than omitting it. however, it can be helpful w...
Feature Policy - HTTP
cy-controlled features to allow functionality to be enabled/disabled for specific origins or frames within a website. where available, the feature integrates with the permissions api, or feature-specific mechanisms to check if the feature is available. the features include (see features list): accelerometer ambient light sensor autoplay camera encrypted media fullscreen geolocation gyroscope magnetometer microphone midi paymentrequest picture-in-picture usb vr / xr examples using feature policy see feature policy demos for example usage of many policies. specifications specification status comment feature policythe definition of 'feature-policy' in that specification. editor's draft initial definition. defines the feature-policy header. d...
Feature-Policy - HTTP
owed to use element.requestfullscreen(). when this policy is disabled, the returned promise rejects with a typeerror. 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 positionerror code of permission_denied. gyroscope controls whether the current document is allowed to gather information about the orientation of the device through the gyroscope interface. layout-animations controls whether the current document is allowed to show layout animations. legacy-image-formats controls whether the current document is allowed to display images in legacy formats. magnetometer controls whether the current doc...
HTTP Index - HTTP
Web › HTTP › Index
, feature-policy, geolocation, http, header the http feature-policy header geolocation directive controls whether the current document is allowed to use the geolocation interface. when this policy is enabled, calls to getcurrentposition() and watchposition() will cause those functions' callbacks to be invoked with a positionerror code of permission_denied. 133 feature-policy: gyroscope the http feature-policy header gyroscope directive controls whether the current document is allowed to gather information about the orientation of the device through the gyroscope interface. 134 feature-policy: layout-animations directive, feature-policy, http, reference, layout-animations the http feature-policy header layout-animations directive controls whether ...
Link prefetching FAQ - HTTP
compliant? yes, link prefetching as outlined in this document does not violate any existing web standards. in fact, the html 4.01 specification explicitly allows for the definition of new link relation types (see section 6.12: link types). however, the exact mechanism employed by mozilla is not yet standardized. an internet-draft is in the works. standardization of this technique is part of the scope of html 5, see the current working draft, section §5.11.3.13. link type "prefetch". how is browser idle time determined? in the current implementation (mozilla 1.2), idle time is determined using the nsiwebprogresslistener api. we attach a listener to the toplevel nsiwebprogress object ("@mozilla.org/docloaderservice;1"). from this, we receive document start & stop notifications, and we approx...
An overview of HTTP - HTTP
Web › HTTP › Overview
ing e-commerce shopping baskets. but while the core of http itself is stateless, http cookies allow the use of stateful sessions. using header extensibility, http cookies are added to the 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 htt...
HTTP resources and specifications - HTTP
modern apis for application are defines using the restful pattern nowadays. proposed standard rfc 2324 hyper text coffee pot control protocol (htcpcp/1.0) april 1st joke spec rfc 7168 the hyper text coffee pot control protocol for tea efflux appliances (htcpcp-tea) april 1st joke spec html living standard html defines extension...
JavaScript modules - JavaScript
osed to in standard scripts. this is because modules use strict mode automatically. there is no need to use the defer attribute (see <script> attributes) when loading a module script; modules are deferred automatically. modules are only executed once, even if they have been referenced in multiple <script> tags. last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope. therefore, you will only be able to access imported features in the script they are imported into, and you won't be able to access them from the javascript console, for example. you'll still get syntax errors shown in the devtools, but you'll not be able to use some of the debugging techniques you might have expected to use. defa...
JavaScript technologies overview - JavaScript
of them is the core language (ecmascript), another is the collection of the web apis, including the dom (document object model). javascript, the 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 no...
Private class fields - JavaScript
) } catch(e) { error = e} console.assert(error instanceof typeerror) 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. 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 p...
SyntaxError: missing = in const declaration - JavaScript
ng = in const declaration fixing the error there are multiple options to fix this error. check what was intended to be achieved with the constant in question. adding a constant value specify the constant value in the same statement in which it's declared: const columns = 80; const, let or var? do not use const if you weren't meaning to declare a constant. maybe you meant to declare a block-scoped variable with let or global variable with var. both don't require an initial value. let columns; ...
SyntaxError: redeclaration of formal parameter "x" - JavaScript
taxerror: let/const redeclaration (edge) syntaxerror: redeclaration of formal parameter "x" (firefox) syntaxerror: identifier "x" has already been declared (chrome) error type syntaxerror what went wrong? the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again. redeclaring the same variable within the same function or block scope using let is not allowed in javascript. examples redeclared argument in this case, the variable "arg" redeclares the argument. function f(arg) { let arg = 'foo'; } // syntaxerror: redeclaration of formal parameter "arg" if you want to change the value of "arg" in the function body, you can do so, but you do not need to declare the same variable again. in other words: you can omit the let...
arguments[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the array.prototype.values property. syntax arguments[symbol.iterator]() examples iteration using for...of loop function f() { // your browser must support for..of loop // and let-scoped variables in for loops for (let letter of arguments) { console.log(letter); } } f('w', 'y', 'k', 'o', 'p'); specifications specification ecmascript (ecma-262)the definition of 'createunmappedargumentsobject' in that specification. ecmascript (ecma-262)the definition of 'createmappedargumentsobject' in that specification. ...
arguments.callee - JavaScript
} else { alert('this is the global'); } } sillyfunction(); ecmascript 3 resolved these issues by allowing named function expressions. for example: [1, 2, 3, 4, 5].map(function factorial(n) { return !(n > 1) ? 1 : factorial(n - 1)*n; }); this has numerous benefits: the function can be called like any other from inside your code it does not create a variable in the outer scope (except for ie 8 and below) it has better performance than accessing the arguments object another feature that was deprecated was arguments.callee.caller, or more specifically function.caller. why is this? well, at any point in time you can find the deepest caller of any function on the stack, and as i said above looking at the call stack has one single major effect: it makes a large number of...
Array.prototype[@@unscopables] - JavaScript
ents the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environments, "keys" would now be the method and not the variable. this is where now the built-in @@unscopables array.prototype[@@unscopables] symbol property comes into play and prevents that some of the array methods are being scoped into the with statement. var keys = []; with (array.prototype) { keys.push('something'); } object.keys(array.prototype[symbol.unscopables]); // ["copywithin", "entries", "fill", "find", "findindex", // "includes", "keys", "values"] specifications specification ecmascript (ecma-262)the definition of 'array.prototype[@@unscopables]' in that specification. ...
Array - JavaScript
array.isarray() returns true if the argument is an array, or false otherwise. array.of() creates a new array instance with a variable number of arguments, regardless of number or type of the arguments. instance properties array.prototype.length reflects the number of elements in an array. array.prototype[@@unscopables] a symbol containing property names to exclude from a with binding scope. instance methods array.prototype.concat() returns a new array that is this array joined with other array(s) and/or value(s). array.prototype.copywithin() copies a sequence of array elements within the array. array.prototype.entries() returns a new array iterator object that contains the key/value pairs for each index in the array. array.prototype.every() returns true if every element...
AsyncFunction - JavaScript
n your code, because such functions are parsed with the rest of the code. all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. note: async functions created with the asyncfunction constructor do not create closures to their creation contexts; they are always created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the asyncfunction constructor was called. this is different from using eval with code for an async function expression. invoking the asyncfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. ex...
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. (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).)...
Function() constructor - JavaScript
the source for this interactive example is stored in a github repository. ...
GeneratorFunction - JavaScript
code, because such functions are parsed with the rest of the code. all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. note: generator function created with the generatorfunction constructor do not create closures to their creation contexts; they are always created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the generatorfunction constructor was called. this is different from using eval with code for a generator function expression. invoking the generatorfunction constructor as a function (without using the new operator) has the same effect as invoking it as a const...
Infinity - JavaScript
enumerable no configurable no 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. description infinity is a property of the global object. in other words, it is a variable in global scope. the initial value of infinity is number.positive_infinity. the value infinity (positive infinity) is greater than any other number. this value behaves slightly differently than mathematical infinity; see number.positive_infinity for details. as defined by the ecmascript 5 specification, infinity is read-only (implemented in javascript 1.8.5 / firefox 4). examples using infinity console.log...
NaN - JavaScript
enumerable no configurable no 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. description nan is a property of the global object. in other words, it is a variable in global scope. the initial value of nan is not-a-number — the same as the value of number.nan. in modern browsers, nan is a non-configurable, non-writable property. even when this is not the case, avoid overriding it. it is rather rare to use nan in a program. there are five different types of operations that return nan: number cannot be parsed (e.g. parseint("blabla") or number(undefined)) math operat...
Symbol - JavaScript
n use the object() function: let sym = symbol('foo') typeof sym // "symbol" let symobj = object(sym) typeof symobj // "object" shared symbols in the global symbol registry the above syntax using the symbol() function will not create a global symbol that is available in your whole codebase. to create symbols available across files and even across realms (each of which has its own global scope), use the methods symbol.for() and symbol.keyfor() to set and retrieve symbols from the global symbol registry. finding symbol properties on objects the method object.getownpropertysymbols() returns an array of symbols and lets you find symbol properties on a given object. note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set sym...
TypedArray.prototype[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the values property. syntax arr[symbol.iterator]() return value the array iterator function, which is the values() function by default. ...
TypedArray.prototype.entries() - JavaScript
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 arr.entries() return value a new array iterator object. ...
TypedArray.prototype.keys() - JavaScript
ithub repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.keys() return value a new array iterator object. ...
TypedArray.prototype.values() - JavaScript
b 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 arr.values() return value a new array iterator object. ...
WebAssembly.compileStreaming() - JavaScript
ejects with a webassembly.compileerror. examples compile streaming the following example (see our compile-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles it to a webassembly.module object. because the compilestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the response into the function when it fulfills. var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.compilestreaming(fetch('simple.wasm')) .then(module => webassembly.instantiate(module, importobject)) .then(instance => instance.exports.exported_func()); the resulting module instance is then instantiated using webassembly.inst...
WebAssembly.instantiateStreaming() - JavaScript
amples 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 instantiates it, the promise fulfilling with a resultobject. because the instantiatestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the response into the function when it fulfills. var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the resultobject's instance member is then accessed, and the contained exported function invoked. note: for this to w...
WebAssembly - JavaScript
then compile and instantiate it 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 instantiates it, the promise fulfilling with a resultobject. because the instantiatestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the response into the function when it fulfills. var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the resultobject's instance member is then accessed, and the contained exported function invoked. specifications ...
globalThis - JavaScript
y of accessing the global this value (and hence the global object itself) across environments. unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. in this way, you can access the global object in a consistent manner without having to know which environment the code is being run in.to help you remember the name, just remember that in global scope the this value is globalthis. html and the windowproxy in many engines globalthis will be a reference to the actual global object, but in web browsers, due to iframe and cross-window security considerations, it references a proxy around the actual global object (which you can't directly access). this distinction is rarely relevant in common usage, but important to be aware of. naming several ...
Standard built-in objects - JavaScript
this chapter documents all of javascript's standard, built-in objects, including their methods and properties. the term "global objects" (or standard built-in objects) here is not to be confused with the global object. here, "global objects" refer to objects in the global scope. the global object itself can be accessed using the this operator in the global scope. in fact, the global scope consists of the properties of the global object, including inherited properties, if any. other objects in the global scope are either created by the user script or provided by the host application. the host objects available in browser contexts are documented in the api reference. for more information about the distinction between the dom and core javascript, see javascript technologies overview. standar...
class expression - JavaScript
xpression 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 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; // referenceerror: namedfoo is not defined foo.name; // "namedfoo" specifications specification ecmascript (ecma-262)the definition of 'class definitions' in th...
Function expression - JavaScript
// even though the variable name is hoisted, the definition isn't. so it's undefined. nothoisted(); // typeerror: 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 factorial(n) { console.log(n) if (n <= 1) { return 1; } return n * factorial(n - 1); } }; math.factit(3) //3;2;1; the variable the function expression is assigned to will have a name property. the name doesn't change if it's assigned to a different variable. if functi...
new.target - JavaScript
on which property access is performed, but here, new is not an object. the new.target pseudo-property is available in all functions. in class constructors, it refers to the constructed class. in ordinary functions, it refers to the function itself, assuming it was invoked via the new operator; otherwise new.target is undefined. in arrow functions, new.target is inherited from the surrounding scope. examples new.target in function calls in normal function calls (as opposed to constructor function calls), new.target is undefined. this lets you detect whether a function was called with new as a constructor. function foo() { if (!new.target) { throw 'foo() must be called with new' } console.log('foo instantiated with new') } new foo() // logs "foo instantiated with new" foo() //...
this - JavaScript
(7) and the string 'foo' to an object as if by new string('foo'), e.g. function bar() { console.log(object.prototype.tostring.call(this)); } bar.call(7); // [object number] bar.call('foo'); // [object string] bar.call(undefined); // [object global] the bind method ecmascript 5 introduced function.prototype.bind(). calling f.bind(someobject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used. function f() { return this.a; } var g = f.bind({a: 'azerty'}); console.log(g()); // azerty var h = g.bind({a: 'yoo'}); // bind only works once! console.log(h()); // azerty var o = {a: 37, f: f, g: g, h: h}; console.log...
typeof - JavaScript
ypeof /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 throw a referenceerror. 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; /...
for - JavaScript
tialization]; [condition]; [final-expression]) statement initialization an expression (including assignment expressions) or variable declaration evaluated once before the loop begins. typically used to initialize a counter variable. this expression may optionally declare new variables with var or let keywords. variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. variables declared with let are local to the statement. the result of this expression is discarded. condition an expression to be evaluated before each loop iteration. if this expression evaluates to true, statement is executed. this conditional test is optional. if omitted, the condition always evaluates to true. if the expression evaluates to false, execution skips to the...
function declaration - JavaScript
} } // in chrome: // 'foo' name is hoisted. typeof foo is undefined // // in firefox: // 'foo' name is hoisted. typeof foo is undefined // // in edge: // 'foo' name is not hoisted. typeof foo is undefined // // 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(); // typeerror: 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 ...
Transitioning to strict mode - JavaScript
argument. this made optimizations complicated for javascript engine and made code harder to read/understand. in strict mode, the arguments object is created and initialized with the same values than the named arguments, but changes to either the arguments object or the named arguments aren't reflected in one another. change to eval in strict mode code, eval doesn't create a new variable in the scope from which it was called. also, of course, in strict mode, the string is evaluated with strict mode rules. thorough testing will need to be performed to make sure nothing breaks. not using eval if you don't really need it may be another pragmatic solution. strictness-neutral code a potential "downside" of moving strict code to strict mode is that the semantics may be different in legacy browser...
Web app manifests
resources (among other things). can pwa manifest contain comments? it is a json-formatted file, with one exception: it is allowed to contain "//"-style comments. members web manifests can contain the following keys. ...
MathML attribute reference - MathML
der>, <munderover> a boolean value specifying whether the operator should be treated as an accent. actiontype <maction> a string value specifying the action happening for this element. align <mtable> <munder>, <mover>, <munderover> <mstack> specifies different alignments of several elements (see element pages for details). unimplemented alignmentscope <mtable> a boolean value specifying whether table columns should act as alignment scopes or not. unimplemented altimg altimg-width altimg-height altimg-valign alttext <math> visual and textual fall-back options. bevelled <mfrac> specifies the style how the fraction should be displayed. deprecated. use u+2044 (fraction slash) instead. ...
Authoring MathML - MathML
code latex-to-mathml converter that is intended to be used in many scenarios described here. of course, the list is by no means exhaustive and you are invited to check out the w3c mathml software list where you can find various other tools. note that by design, mathml is well-integrated in html5 and in particular you can use usual web features like css, dom, javascript or svg. this is out of the scope of this document but anyone with basic knowledge of web languages will easily be able to mix these features with mathml. check out our demos and mathml references for more details. using mathml mathml in html pages you can use presentation mathml inside html5 documents: <!doctype html> <html> <head> <title>mathml in html5</title> </head> <body> <h1>mathml in html5</h1> <p> square r...
<mtable> - MathML
Web › MathML › Element › mtable
pecified row of the table rather than the whole table. a negative integer value counts rows from the bottom of the table. starting with gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) the interpretation of negative values has been corrected (bug 601436). in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) the parsing has been updated to treat whitespace correctly. alignmentscope unimplemented class, id, style provided for use with stylesheets. columnalign specifies the horizontal alignment of the cells. multiple values separated by space are allowed and apply to the corresponding columns (e.g. columnalign="left right center"). possible values are: left, center (default) and right. columnlines specifies column borders. multiple values separated by space are allowed...
Digital audio concepts - Web media technologies
lossy compression algorithms generally use psychoacoustics to determine which components of an audio waveform can be lost or subdued in some way that can improve compression ratios while minimizing the audible effect...
Recommended Web Performance Timings: How long is too long? - Web Performance
s: idling goal browsers are single threaded (though background threads are supported for web workers). this means that user interaction, painting, and script execution are all on the same thread. if the thread is busy doing complex javascript execution, the main thread will not be available to react to user input, such as pressing a button. for this reason, script execution should be limited in scope, divided into chunks of code that can be executed in 50ms or less. this makes the thread available for user interactions. animation goal for scrolling and other animations to look smooth and feel responsive, the content repaints should occur at 60 frames per second (60fps), which is once every 16.7ms. the 16.7 milliseconds includes scripting, reflow, and repaint. realize a document takes about ...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
}) ); }); there are two things that need an explanation here: what extendableevent.waituntil does, and what the caches object is. the service worker does not install until the code inside waituntil is executed. it returns a promise — this approach is needed because installing may take some time, so we have to wait for it to finish. caches is a special cachestorage object available in the scope of the given service worker to enable saving data — saving to web storage won't work, because web storage is synchronous. with service workers, we use the cache api instead. here, we open a cache with a given name, then add all the files our app uses to the cache, so they are available next time it loads (identified by request url). activation there is also an activate event, which is used i...
baseProfile - SVG: Scalable Vector Graphics
the baseprofile attribute describes the minimum svg language profile that the author believes is necessary to correctly render the content. the attribute does not specify any processing restrictions; it can be considered metadata. for example, the value of the attribute could be used by an authoring tool to warn the user when they are modifying the document beyond the scope of the specified base profile. each svg profile should define the text that is appropriate for this attribute. only one element is using this attribute: <svg> context notes value profile name default value none animatable no example <svg width="120" height="120" version="1.1" xmlns="http://www.w3.org/2000/svg" baseprofile="full"> ... </svg> specifications sp...
result - SVG: Scalable Vector Graphics
Web › SVG › Attribute › result
cx="100" cy="100" r="100" style="filter: url(#displacementfilter)"/> </svg> usage notes value <filter-primitive-reference> default value none animatable yes <filter-primitive-reference> this value is a <custom-ident> and defines the name for the filter primitive. it is only meaningful within a given <filter> element and thus has only local scope. it is legal for the same <filter-primitive-reference> to appear multiple times within the same <filter> element. when referenced, this value will use the closest preceding filter primitive with the given result. specifications specification status comment filter effects module level 1the definition of 'result' in that specification. working draft clarifies th...
Secure contexts - Web security
if (window.issecurecontext) { // page is a secure context so service workers are now available navigator.serviceworker.register("/offline-worker.js").then(function () { ... }); } specifications specification status comment secure contexts candidate recommendation editor’s draft ...
Using templates and slots - Web Components
the <template> uses <slot> and its name attribute to make three named slots: <slot name="element-name"> <slot name="description"> <slot name="attributes"> the <template> wraps the named slots in a <details> element. creating a new <element-details> element from the <template> next, let’s create a new custom element named <...
namespace - XPath
Web › XPath › Axes › namespace
(not supported) the namespace axis indicates all the nodes that are in scope for the context node. in this case, the context node must be an element node. ...
Axes - XPath
Web › XPath › Axes
, but attribute nodes are not the children of their parents. following indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes. following-sibling indicates all the nodes that have the same parent as the context node and appear after the context node in the source document. namespace (not supported) indicates all the nodes that are in scope for the context node. in this case, the context node must be an element node. parent indicates the single node that is the parent of the context node. it can be abbreviated as two periods (..). preceding indicates all the nodes that precede the context node in the document except any ancestor, attribute and namespace nodes. preceding-sibling indicates all the nodes that have the same parent...
Comparison of CSS Selectors and XPath - XPath
ght tool for the right job. ...
element-available - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the element-available function determines if an element is available and returns true or false. syntax element-available(qname ) arguments qname must evaluate to a valid qname. the qname is expanded into an expanded-name using the namespace declarations in scope for the expression. returns returns true if and only if the expanded-name is the name of an instruction. if the expanded-name has a namespace uri equal to the xslt namespace uri, then it refers to an element defined by xslt. otherwise, it refers to an extension element. if the expanded-name has a null namespace uri, the element-available function will return false. defined xslt 1.0 15 gecko support supported. ...
system-property - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the system-property function returns an object representing the given system-property. syntax system-property(name) arguments name (optional) the name of the system property. the argument must evaluate to a string that is a qname. the qname is expanded into a name using the namespace declarations in scope for the expression. the system-property function returns an object representing the value of the system property identified by the name. if there is no such system property, the empty string should be returned. returns an object representing the given system-property. notes xsl:version, a number giving the version of xslt implemented by the processor; for xslt processors implementing the v...
<xsl:stylesheet> - XSLT: Extensible Stylesheet Language Transformations
tension elements in this document. default-collation specifies the default collation used by all xpath expressions appearing in attributes or text value templates that have the element as an ancestor, unless overridden by another default-collation attribute on an inner element. it also determines the collation used by certain xslt constructs (such as <xsl:key> and xsl:for-each-group) within its scope. default-mode defines the default value for the mode attribute of all <xsl:template> and <xsl:apply-templates> elements within its scope. default-validation defines the default value of the validation attribute of all relevant instructions appearing within its scope. expand-text determines whether descendant text nodes of the element are treated as text value templates. id specifies an id...
An Overview - XSLT: Extensible Stylesheet Language Transformations
an xslt stylesheet is an xml document. unlike css, which has its own specialized syntax, an xslt stylesheet is an xml document, which must conform to all xml rules, including well-formedness. so the model for transformation is that one xml document is used to transform another xml document. ...
Compiling from Rust to WebAssembly - WebAssembly
uces an equivalent package.json. copies your readme.md (if you have one) into the package. the end result? you have an npm package inside of the pkg directory. a digression about code size if you check out the generated webassembly code size, it may be a few hundred kilobytes. we haven't instructed rust to optimize for size at all, and doing so cuts down on the size a lot. this is beyond the scope of this tutorial, but if you'd like to learn more, check out the rust webassembly working group's documentation on shrinking .wasm size. making our package availabe to npm let's use `npm link` to make this package available to other javascript packages installed $ cd pkg $ npm link we now have an npm package, written in rust, but compiled to webassembly. it's ready for use from javascript, an...